feat: добавить базовые сервисы image-platform
- добавлены backend, admin, gateway и worker skeleton - добавлены Drizzle schema, database package и initial migration - добавлены shared packages для RabbitMQ topology и S3 helpers - обновлены dev-инфраструктура, env example, scripts и dependencies - обновлена документация под versioned image URLs и read-through flow
This commit is contained in:
12
apps/admin/index.html
Normal file
12
apps/admin/index.html
Normal file
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Image Platform Admin</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
24
apps/admin/package.json
Normal file
24
apps/admin/package.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "@image-platform/admin",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "tsc -b && vite build",
|
||||
"dev": "vite --host 0.0.0.0 --port 5173",
|
||||
"preview": "vite preview --host 0.0.0.0 --port 5173",
|
||||
"typecheck": "tsc -b"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.2.5",
|
||||
"react-dom": "^19.2.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^8.0.10"
|
||||
}
|
||||
}
|
||||
111
apps/admin/src/App.css
Normal file
111
apps/admin/src/App.css
Normal file
@@ -0,0 +1,111 @@
|
||||
:root {
|
||||
color: #171411;
|
||||
background: #f7f4ee;
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
background:
|
||||
radial-gradient(circle at 18% 18%, rgba(123, 76, 255, 0.18), transparent 30rem),
|
||||
#f7f4ee;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
textarea,
|
||||
select {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
min-height: 100vh;
|
||||
padding: 48px 24px;
|
||||
}
|
||||
|
||||
.hero {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: 40px;
|
||||
border: 1px solid #e4ded4;
|
||||
border-radius: 32px;
|
||||
background: rgba(255, 255, 255, 0.82);
|
||||
box-shadow: 0 22px 80px rgba(40, 32, 21, 0.08);
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0 0 16px;
|
||||
color: #7b4cff;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.22em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
h1 {
|
||||
max-width: 760px;
|
||||
margin: 0;
|
||||
font-size: clamp(40px, 7vw, 76px);
|
||||
line-height: 0.92;
|
||||
letter-spacing: -0.06em;
|
||||
}
|
||||
|
||||
.lead {
|
||||
max-width: 680px;
|
||||
margin: 24px 0 0;
|
||||
color: #73695d;
|
||||
font-size: 18px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 16px;
|
||||
max-width: 960px;
|
||||
margin: 24px auto 0;
|
||||
}
|
||||
|
||||
.card {
|
||||
min-height: 150px;
|
||||
padding: 24px;
|
||||
border: 1px solid #e4ded4;
|
||||
border-radius: 24px;
|
||||
background: rgba(255, 255, 255, 0.76);
|
||||
}
|
||||
|
||||
.card h2 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.card p {
|
||||
margin: 12px 0 0;
|
||||
color: #73695d;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.app-shell {
|
||||
padding: 24px 16px;
|
||||
}
|
||||
|
||||
.hero {
|
||||
padding: 28px;
|
||||
border-radius: 24px;
|
||||
}
|
||||
|
||||
.cards {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
40
apps/admin/src/App.tsx
Normal file
40
apps/admin/src/App.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import "./App.css"
|
||||
|
||||
const cards = [
|
||||
{
|
||||
title: "Assets",
|
||||
description: "Каталог исходных изображений и связанной metadata.",
|
||||
},
|
||||
{
|
||||
title: "Variants",
|
||||
description: "Будущие AVIF/WebP/JPEG variants, presets и статусы генерации.",
|
||||
},
|
||||
{
|
||||
title: "Storage",
|
||||
description: "PostgreSQL как source of truth, S3/MinIO как хранилище bytes.",
|
||||
},
|
||||
]
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<main className="app-shell">
|
||||
<section className="hero">
|
||||
<p className="eyebrow">Image Platform Admin</p>
|
||||
<h1>чистый Vite React TS app</h1>
|
||||
<p className="lead">
|
||||
Это стартовая админка без UI-фреймворков. Дальше сюда добавим управление allowed hosts,
|
||||
assets, variants и presets.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="cards" aria-label="Будущие разделы">
|
||||
{cards.map((card) => (
|
||||
<article className="card" key={card.title}>
|
||||
<h2>{card.title}</h2>
|
||||
<p>{card.description}</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
10
apps/admin/src/main.tsx
Normal file
10
apps/admin/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from "react"
|
||||
import { createRoot } from "react-dom/client"
|
||||
|
||||
import { App } from "./App"
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
22
apps/admin/tsconfig.app.json
Normal file
22
apps/admin/tsconfig.app.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
11
apps/admin/tsconfig.json
Normal file
11
apps/admin/tsconfig.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
18
apps/admin/tsconfig.node.json
Normal file
18
apps/admin/tsconfig.node.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
6
apps/admin/vite.config.ts
Normal file
6
apps/admin/vite.config.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import react from "@vitejs/plugin-react"
|
||||
import { defineConfig } from "vite"
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
})
|
||||
8
apps/backend/nest-cli.json
Normal file
8
apps/backend/nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
27
apps/backend/package.json
Normal file
27
apps/backend/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@image-platform/backend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"dev": "nest start --watch",
|
||||
"start": "node dist/main.js",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.0",
|
||||
"@nestjs/core": "^11.0.0",
|
||||
"@nestjs/platform-express": "^11.0.0",
|
||||
"@nestjs/swagger": "^11.0.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"swagger-ui-express": "^5.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/swagger-ui-express": "^4.1.8",
|
||||
"typescript": "^5.9.0"
|
||||
}
|
||||
}
|
||||
9
apps/backend/src/app.module.ts
Normal file
9
apps/backend/src/app.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Module } from "@nestjs/common"
|
||||
|
||||
import { HealthController } from "./health/health.controller"
|
||||
import { InternalImagesController } from "./internal-images/internal-images.controller"
|
||||
|
||||
@Module({
|
||||
controllers: [HealthController, InternalImagesController],
|
||||
})
|
||||
export class AppModule {}
|
||||
9
apps/backend/src/health/health-response.dto.ts
Normal file
9
apps/backend/src/health/health-response.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { ApiProperty } from "@nestjs/swagger"
|
||||
|
||||
export class HealthResponseDto {
|
||||
@ApiProperty({ example: "image-platform-api" })
|
||||
service!: string
|
||||
|
||||
@ApiProperty({ example: "ok" })
|
||||
status!: string
|
||||
}
|
||||
18
apps/backend/src/health/health.controller.ts
Normal file
18
apps/backend/src/health/health.controller.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Controller, Get } from "@nestjs/common"
|
||||
import { ApiOkResponse, ApiOperation, ApiTags } from "@nestjs/swagger"
|
||||
|
||||
import { HealthResponseDto } from "./health-response.dto"
|
||||
|
||||
@ApiTags("system")
|
||||
@Controller("health")
|
||||
export class HealthController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: "Проверить состояние API" })
|
||||
@ApiOkResponse({ type: HealthResponseDto })
|
||||
getHealth(): HealthResponseDto {
|
||||
return {
|
||||
service: "image-platform-api",
|
||||
status: "ok",
|
||||
}
|
||||
}
|
||||
}
|
||||
21
apps/backend/src/internal-images/ensure-image-variant.dto.ts
Normal file
21
apps/backend/src/internal-images/ensure-image-variant.dto.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { ApiProperty } from "@nestjs/swagger"
|
||||
|
||||
export class EnsureImageVariantRequestDto {
|
||||
@ApiProperty({ example: "asset_123" })
|
||||
assetId!: string
|
||||
|
||||
@ApiProperty({ example: 4, minimum: 1 })
|
||||
version!: number
|
||||
|
||||
@ApiProperty({ example: "card" })
|
||||
preset!: string
|
||||
|
||||
@ApiProperty({ example: 640, minimum: 1 })
|
||||
width!: number
|
||||
|
||||
@ApiProperty({ example: 80, minimum: 1 })
|
||||
quality!: number
|
||||
|
||||
@ApiProperty({ enum: ["auto", "avif", "webp", "jpg", "png"], example: "auto" })
|
||||
format!: "auto" | "avif" | "jpg" | "png" | "webp"
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Body, Controller, NotImplementedException, Post } from "@nestjs/common"
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger"
|
||||
|
||||
import { EnsureImageVariantRequestDto } from "./ensure-image-variant.dto"
|
||||
|
||||
@ApiTags("internal-images")
|
||||
@Controller("internal/images")
|
||||
export class InternalImagesController {
|
||||
@Post("ensure")
|
||||
@ApiOperation({ summary: "Ensure image variant for Gateway L1 miss" })
|
||||
@ApiResponse({ status: 501, description: "Read-through image pipeline is not implemented yet" })
|
||||
ensureImageVariant(@Body() request: EnsureImageVariantRequestDto): never {
|
||||
throw new NotImplementedException({
|
||||
message: "image read-through pipeline is not implemented yet",
|
||||
request,
|
||||
status: "not_implemented",
|
||||
})
|
||||
}
|
||||
}
|
||||
37
apps/backend/src/main.ts
Normal file
37
apps/backend/src/main.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { NestFactory } from "@nestjs/core"
|
||||
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger"
|
||||
|
||||
import { AppModule } from "./app.module"
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule)
|
||||
|
||||
app.setGlobalPrefix("api")
|
||||
app.enableShutdownHooks()
|
||||
|
||||
const openApiConfig = new DocumentBuilder()
|
||||
.setTitle("Image Platform API")
|
||||
.setDescription("Control plane for image assets, variants, S3 storage and external imgproxy.")
|
||||
.setVersion("0.1.0")
|
||||
.addTag("system")
|
||||
.addTag("assets")
|
||||
.addTag("variants")
|
||||
.addTag("allowed-hosts")
|
||||
.addTag("internal-images")
|
||||
.build()
|
||||
|
||||
const openApiDocument = SwaggerModule.createDocument(app, openApiConfig)
|
||||
|
||||
SwaggerModule.setup("docs", app, openApiDocument, {
|
||||
jsonDocumentUrl: "docs-json",
|
||||
swaggerOptions: {
|
||||
persistAuthorization: true,
|
||||
},
|
||||
})
|
||||
|
||||
const port = Number.parseInt(process.env.API_PORT ?? "3001", 10)
|
||||
|
||||
await app.listen(port)
|
||||
}
|
||||
|
||||
void bootstrap()
|
||||
8
apps/backend/tsconfig.build.json
Normal file
8
apps/backend/tsconfig.build.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"declaration": true,
|
||||
"noEmit": false
|
||||
},
|
||||
"exclude": ["node_modules", "dist", "test", "**/*.spec.ts"]
|
||||
}
|
||||
23
apps/backend/tsconfig.json
Normal file
23
apps/backend/tsconfig.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"baseUrl": "./",
|
||||
"declaration": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"esModuleInterop": true,
|
||||
"experimentalDecorators": true,
|
||||
"incremental": true,
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"outDir": "./dist",
|
||||
"removeComments": true,
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"strictPropertyInitialization": false,
|
||||
"target": "ES2023",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
20
apps/gateway/package.json
Normal file
20
apps/gateway/package.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "@image-platform/gateway",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"dev": "tsx watch src/main.ts",
|
||||
"start": "node dist/main.js",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"fastify": "^5.8.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.6.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^6.0.3"
|
||||
}
|
||||
}
|
||||
27
apps/gateway/src/config.ts
Normal file
27
apps/gateway/src/config.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
export type GatewayConfig = {
|
||||
backendUpstream: URL
|
||||
host: string
|
||||
port: number
|
||||
}
|
||||
|
||||
export function loadGatewayConfig(): GatewayConfig {
|
||||
return {
|
||||
backendUpstream: new URL(process.env.GATEWAY_BACKEND_UPSTREAM ?? "http://localhost:3001"),
|
||||
host: process.env.GATEWAY_HOST ?? "0.0.0.0",
|
||||
port: parsePort(process.env.GATEWAY_PORT, 8888),
|
||||
}
|
||||
}
|
||||
|
||||
function parsePort(value: string | undefined, fallback: number) {
|
||||
if (!value) {
|
||||
return fallback
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(value, 10)
|
||||
|
||||
if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535) {
|
||||
throw new Error(`Invalid port: ${value}`)
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
12
apps/gateway/src/main.ts
Normal file
12
apps/gateway/src/main.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { loadGatewayConfig } from "./config.js"
|
||||
import { createGatewayServer } from "./server.js"
|
||||
|
||||
const config = loadGatewayConfig()
|
||||
const app = createGatewayServer(config)
|
||||
|
||||
try {
|
||||
await app.listen({ host: config.host, port: config.port })
|
||||
} catch (error) {
|
||||
app.log.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
77
apps/gateway/src/proxy.ts
Normal file
77
apps/gateway/src/proxy.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { Readable } from "node:stream"
|
||||
|
||||
import type { FastifyReply, FastifyRequest } from "fastify"
|
||||
|
||||
const hopByHopHeaders = new Set([
|
||||
"connection",
|
||||
"keep-alive",
|
||||
"proxy-authenticate",
|
||||
"proxy-authorization",
|
||||
"te",
|
||||
"trailer",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
])
|
||||
|
||||
export async function proxyToUpstream(request: FastifyRequest, reply: FastifyReply, upstreamBaseUrl: URL) {
|
||||
const upstreamUrl = new URL(request.url, upstreamBaseUrl)
|
||||
const headers = buildProxyHeaders(request)
|
||||
const init: RequestInit & { duplex?: "half" } = {
|
||||
headers,
|
||||
method: request.method,
|
||||
redirect: "manual",
|
||||
}
|
||||
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.raw as RequestInit["body"]
|
||||
init.duplex = "half"
|
||||
}
|
||||
|
||||
const response = await fetch(upstreamUrl, init)
|
||||
|
||||
reply.code(response.status)
|
||||
|
||||
response.headers.forEach((value, key) => {
|
||||
if (!hopByHopHeaders.has(key.toLowerCase())) {
|
||||
reply.header(key, value)
|
||||
}
|
||||
})
|
||||
|
||||
if (!response.body) {
|
||||
return reply.send()
|
||||
}
|
||||
|
||||
return reply.send(Readable.fromWeb(response.body))
|
||||
}
|
||||
|
||||
function buildProxyHeaders(request: FastifyRequest) {
|
||||
const headers = new Headers()
|
||||
|
||||
for (const [key, rawValue] of Object.entries(request.headers)) {
|
||||
const lowerKey = key.toLowerCase()
|
||||
|
||||
if (lowerKey === "host" || hopByHopHeaders.has(lowerKey)) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (Array.isArray(rawValue)) {
|
||||
for (const value of rawValue) {
|
||||
headers.append(key, value)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (typeof rawValue === "string") {
|
||||
headers.set(key, rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
headers.set("x-forwarded-host", request.headers.host ?? "")
|
||||
headers.set("x-forwarded-proto", "http")
|
||||
|
||||
if (request.ip) {
|
||||
headers.set("x-forwarded-for", request.ip)
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
90
apps/gateway/src/server.ts
Normal file
90
apps/gateway/src/server.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import Fastify from "fastify"
|
||||
|
||||
import type { GatewayConfig } from "./config.js"
|
||||
import { proxyToUpstream } from "./proxy.js"
|
||||
|
||||
export function createGatewayServer(config: GatewayConfig) {
|
||||
const app = Fastify({
|
||||
logger: true,
|
||||
})
|
||||
|
||||
app.get("/health", async () => ({
|
||||
service: "image-platform-gateway",
|
||||
status: "ok",
|
||||
}))
|
||||
|
||||
app.get<{ Params: ImageParams; Querystring: ImageQuery }>(
|
||||
"/images/:assetId/:version/:preset",
|
||||
async (request, reply) => {
|
||||
const version = parseVersionParam(request.params.version)
|
||||
|
||||
if (version === null) {
|
||||
return reply.code(400).send({
|
||||
message: "image version must use v{number} format",
|
||||
statusCode: 400,
|
||||
})
|
||||
}
|
||||
|
||||
const width = parseOptionalInteger(request.query.w)
|
||||
const quality = parseOptionalInteger(request.query.q)
|
||||
const format = request.query.f ?? "auto"
|
||||
|
||||
return reply.code(501).header("cache-control", "no-store").send({
|
||||
assetId: request.params.assetId,
|
||||
format,
|
||||
message: "image gateway read-through pipeline is not implemented yet",
|
||||
preset: request.params.preset,
|
||||
quality,
|
||||
status: "not_implemented",
|
||||
version,
|
||||
width,
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
app.all("/api/*", async (request, reply) => proxyToUpstream(request, reply, config.backendUpstream))
|
||||
app.all("/docs", async (request, reply) => proxyToUpstream(request, reply, config.backendUpstream))
|
||||
app.all("/docs/*", async (request, reply) => proxyToUpstream(request, reply, config.backendUpstream))
|
||||
app.all("/docs-json", async (request, reply) => proxyToUpstream(request, reply, config.backendUpstream))
|
||||
|
||||
app.setNotFoundHandler(async (_request, reply) => {
|
||||
return reply.code(404).send({
|
||||
message: "route not found",
|
||||
statusCode: 404,
|
||||
})
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
type ImageQuery = {
|
||||
f?: string
|
||||
q?: string
|
||||
w?: string
|
||||
}
|
||||
|
||||
type ImageParams = {
|
||||
assetId: string
|
||||
preset: string
|
||||
version: string
|
||||
}
|
||||
|
||||
function parseVersionParam(value: string) {
|
||||
if (!value.startsWith("v")) {
|
||||
return null
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(value.slice(1), 10)
|
||||
|
||||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null
|
||||
}
|
||||
|
||||
function parseOptionalInteger(value: string | undefined) {
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(value, 10)
|
||||
|
||||
return Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
6
apps/gateway/tsconfig.build.json
Normal file
6
apps/gateway/tsconfig.build.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": false
|
||||
}
|
||||
}
|
||||
22
apps/gateway/tsconfig.json
Normal file
22
apps/gateway/tsconfig.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"declaration": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"lib": ["ES2023"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"target": "ES2023",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["dist", "node_modules"]
|
||||
}
|
||||
24
apps/worker/package.json
Normal file
24
apps/worker/package.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "@image-platform/worker",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"dev": "tsx watch src/main.ts",
|
||||
"start": "node dist/main.js",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@image-platform/database": "workspace:*",
|
||||
"@image-platform/queue": "workspace:*",
|
||||
"@image-platform/storage": "workspace:*",
|
||||
"amqplib": "^1.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/amqplib": "^0.10.8",
|
||||
"@types/node": "^25.6.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^6.0.3"
|
||||
}
|
||||
}
|
||||
25
apps/worker/src/config.ts
Normal file
25
apps/worker/src/config.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { loadQueueTopologyFromEnv, type QueueTopology } from "@image-platform/queue"
|
||||
|
||||
export type WorkerConfig = {
|
||||
prefetch: number
|
||||
queueTopology: QueueTopology
|
||||
rabbitmqUrl: string
|
||||
}
|
||||
|
||||
export function loadWorkerConfig(env: NodeJS.ProcessEnv = process.env): WorkerConfig {
|
||||
return {
|
||||
prefetch: parsePositiveInteger(env.WORKER_PREFETCH, 2),
|
||||
queueTopology: loadQueueTopologyFromEnv(env),
|
||||
rabbitmqUrl: env.RABBITMQ_URL ?? "amqp://image:image-password@localhost:5672/image_platform",
|
||||
}
|
||||
}
|
||||
|
||||
function parsePositiveInteger(value: string | undefined, fallback: number) {
|
||||
if (!value) {
|
||||
return fallback
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(value, 10)
|
||||
|
||||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback
|
||||
}
|
||||
67
apps/worker/src/main.ts
Normal file
67
apps/worker/src/main.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import amqp, { type Channel, type ConsumeMessage } from "amqplib"
|
||||
import { parseGenerateVariantJobBuffer, type QueueTopology } from "@image-platform/queue"
|
||||
|
||||
import { loadWorkerConfig } from "./config.js"
|
||||
|
||||
async function bootstrap() {
|
||||
const config = loadWorkerConfig()
|
||||
const connection = await amqp.connect(config.rabbitmqUrl)
|
||||
const channel = await connection.createChannel()
|
||||
|
||||
await assertQueueTopology(channel, config.queueTopology)
|
||||
await channel.prefetch(config.prefetch)
|
||||
await channel.consume(
|
||||
config.queueTopology.generateVariantQueue,
|
||||
(message) => void handleGenerateVariantMessage(channel, message),
|
||||
{ noAck: false },
|
||||
)
|
||||
|
||||
console.log(`worker consuming ${config.queueTopology.generateVariantQueue}`)
|
||||
|
||||
const shutdown = async () => {
|
||||
console.log("worker shutting down")
|
||||
await channel.close().catch((error: unknown) => console.error("failed to close RabbitMQ channel", error))
|
||||
await connection.close().catch((error: unknown) => console.error("failed to close RabbitMQ connection", error))
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
process.once("SIGINT", () => void shutdown())
|
||||
process.once("SIGTERM", () => void shutdown())
|
||||
}
|
||||
|
||||
async function assertQueueTopology(channel: Channel, topology: QueueTopology) {
|
||||
await channel.assertExchange(topology.jobsExchange, "direct", { durable: true })
|
||||
await channel.assertExchange(topology.jobsDeadLetterExchange, "direct", { durable: true })
|
||||
await channel.assertQueue(topology.generateVariantQueue, {
|
||||
deadLetterExchange: topology.jobsDeadLetterExchange,
|
||||
deadLetterRoutingKey: topology.generateVariantDeadLetterRoutingKey,
|
||||
durable: true,
|
||||
})
|
||||
await channel.assertQueue(topology.generateVariantDeadLetterQueue, { durable: true })
|
||||
await channel.bindQueue(topology.generateVariantQueue, topology.jobsExchange, topology.generateVariantRoutingKey)
|
||||
await channel.bindQueue(
|
||||
topology.generateVariantDeadLetterQueue,
|
||||
topology.jobsDeadLetterExchange,
|
||||
topology.generateVariantDeadLetterRoutingKey,
|
||||
)
|
||||
}
|
||||
|
||||
async function handleGenerateVariantMessage(channel: Channel, message: ConsumeMessage | null) {
|
||||
if (message === null) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const job = parseGenerateVariantJobBuffer(message.content)
|
||||
console.log("generate variant job received, handler not implemented yet", job)
|
||||
channel.nack(message, false, false)
|
||||
} catch (error) {
|
||||
console.error("invalid generate variant job", error)
|
||||
channel.nack(message, false, false)
|
||||
}
|
||||
}
|
||||
|
||||
void bootstrap().catch((error: unknown) => {
|
||||
console.error("worker failed to start", error)
|
||||
process.exit(1)
|
||||
})
|
||||
7
apps/worker/tsconfig.build.json
Normal file
7
apps/worker/tsconfig.build.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": false
|
||||
},
|
||||
"exclude": ["dist", "node_modules", "**/*.spec.ts"]
|
||||
}
|
||||
21
apps/worker/tsconfig.json
Normal file
21
apps/worker/tsconfig.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"declaration": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"lib": ["ES2023"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"target": "ES2023",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["dist", "node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user