diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..bbd78d8 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,39 @@ +# The build context is the repo root. The build installs node_modules and writes .next itself, so local +# copies would only break the cache. +**/node_modules +**/.next +**/.nx +**/dist +**/coverage +**/*.tsbuildinfo +**/next-env.d.ts +**/*.log +.git +.github +.vscode +.idea +.claude +docs +graft +server-proxy.js + +# Deploy files: changing them never rebuilds an image. .deploy/ holds each app's server secrets. +.deploy +.dockerignore +Dockerfile +tools/deploy.sh +tools/rollback.sh + +# Generated by the next.config.ts plugins during next build. +apps/*/public/fonts +apps/*/public/icons/symbol-defs.svg +apps/*/public/sw.js + +# Keys and certificates (next dev --experimental-https writes apps//certificates/). +**/*.pem +**/*.key +**/certificates + +# Env files: none. tools/deploy.sh hands the app's env to next build as a bind mount, so no env file, a +# developer's local .env included, reaches a layer or the image. +**/.env* diff --git a/.gitignore b/.gitignore index b118c8d..3766d16 100644 --- a/.gitignore +++ b/.gitignore @@ -41,7 +41,7 @@ test-results # Env (keep examples committed) .env .env.* -!.env.example +!.env.sample # Logs *.log @@ -64,3 +64,6 @@ Thumbs.db # Written by the pwa lib's writeServiceWorker on every build or dev start. apps/*/public/sw.js + +# Deploy host state: each app's .env.production for docker build (Dockerfile), never committed +.deploy/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..3c40817 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,72 @@ +# syntax=docker/dockerfile:1.28 +# check=error=true + +# One Dockerfile for every Next.js app in apps/. The build context is the repo root and APP names the +# app's folder, so a new app needs no edit here. tools/deploy.sh builds and runs it; a build by hand also +# needs --build-context appenv=. + +# Debian 13 (glibc) in every stage: the runner runs the native binaries (sharp) the build installed. +# Change the tag and the digest together. +ARG NODE_IMAGE=docker.io/library/node:24.22.0-trixie-slim@sha256:7f486cabe892bff8fef04c0f7da8dba84a560be3e4e2740b7a86afc57ebec315 + +# The workspace install, shared by every app. Only the manifests and the lockfile come in, so a source +# edit never reinstalls dependencies. +FROM ${NODE_IMAGE} AS deps +ENV CI=true \ + NEXT_TELEMETRY_DISABLED=1 +WORKDIR /repo +# The exact pnpm from the root packageManager field ("pnpm@"). +COPY package.json ./ +RUN --mount=type=cache,id=npm,target=/root/.npm \ + npm install --global --no-audit --no-fund "pnpm@$(node -p "require('./package.json').packageManager.replace(/^pnpm@|\+.*$/g, '')")" +COPY --parents pnpm-lock.yaml pnpm-workspace.yaml .npmrc* patches* **/package.json ./ +RUN --mount=type=cache,id=pnpm-store,target=/pnpm-store \ + pnpm install --frozen-lockfile --store-dir=/pnpm-store + +# next build for one app. The Turbopack cache mount keeps the next build of this app incremental. +FROM deps AS build +COPY . . +ARG APP +ARG NEXT_DEPLOYMENT_ID +WORKDIR /repo/apps/${APP:?} +# The app's env file comes from tools/deploy.sh as a bind mount: it's in no layer, and a changed value +# reruns this step. next build inlines its public values and validates the rest. +RUN --mount=type=cache,id=next-cache-${APP},target=/repo/apps/${APP}/.next/cache \ + --mount=type=bind,from=appenv,source=.env.production,target=/repo/apps/${APP}/.env.production <<'SH' +set -eu +# next build type-checks against the declarations (dist/*.d.ts) of the projects the app's tsconfig.json +# references, and no checkout holds them: build them first, as each project's typecheck target does. +pnpm exec tsc --build --emitDeclarationOnly $(node -p "const ts = require('typescript'); ts.readConfigFile('tsconfig.json', ts.sys.readFile).config.references.map((r) => r.path).join(' ')") +pnpm exec next build +# next.config.ts writes these when it loads; a release without them breaks fonts, icons, or worker updates. +# Only apps that ship a service worker write sw.js (the admin panel has none, 0062). +test -d public/fonts && test -f public/icons/symbol-defs.svg \ + || { echo 'next build did not write public/fonts and public/icons/symbol-defs.svg' >&2; exit 1; } +if grep -q writeServiceWorker next.config.ts; then + test -f public/sw.js || { echo 'next build did not write public/sw.js' >&2; exit 1; } +fi +# Standalone copies the env file; the container mounts it at start instead, so the image holds no secret. +rm -f .next/standalone/apps/${APP}/.env* +SH + +# The runtime image: the standalone server with its traced node_modules, public/, and .next/static. +FROM ${NODE_IMAGE} AS runner +# KEEP_ALIVE_TIMEOUT outlasts a proxy's usual 60 s upstream keepalive, so it never reuses a socket Node closed. +ENV NODE_ENV=production \ + NEXT_TELEMETRY_DISABLED=1 \ + HOSTNAME=0.0.0.0 \ + PORT=3000 \ + KEEP_ALIVE_TIMEOUT=65000 +ARG APP +WORKDIR /app/apps/${APP} +COPY --from=build /repo/apps/${APP}/.next/standalone /app +COPY --from=build /repo/apps/${APP}/.next/static .next/static +COPY --from=build /repo/apps/${APP}/public public +# Every file belongs to root, so the app can't change its own code; only the image optimizer's cache is writable. +RUN install -d -o node -g node .next/cache +USER node +EXPOSE 3000 +# tools/deploy.sh swaps a release in only after this check passes. +HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --start-interval=2s --retries=3 \ + CMD ["node", "-e", "fetch('http://127.0.0.1:' + process.env.PORT + '/healthz').then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))"] +CMD ["node", "server.js"] diff --git a/apps/bear/.env.example b/apps/bear/.env.sample similarity index 60% rename from apps/bear/.env.example rename to apps/bear/.env.sample index 14f9c32..8268029 100644 --- a/apps/bear/.env.example +++ b/apps/bear/.env.sample @@ -1,5 +1,13 @@ # Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one. NEXT_PUBLIC_SITE_URL=http://localhost:7001 + +# The API, one end point per side (0066), each an origin with no path. The browser calls +# NEXT_PUBLIC_CLIENT_END_POINT, the gateway's public origin, directly with the session cookies, so +# the gateway must allow this site's origin in CORS; next build inlines it. Server requests go to +# INTERNAL_END_POINT: the gateway's origin from inside the deployment network, server only. +NEXT_PUBLIC_CLIENT_END_POINT=http://localhost:3000 +INTERNAL_END_POINT=http://localhost:3000 + NEXT_PUBLIC_BALE_HANDLE=lumina_support NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸ @@ -9,10 +17,5 @@ NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸ # there unregisters the worker for every visitor on their next page load (the kill switch). NEXT_PUBLIC_SERVICE_WORKER_ENABLED=false -# Server only: the gateway's origin from inside the deployment network. Server requests go -# there, and so does the browser's /api proxy (next.config rewrite, fixed at build time). -API_INTERNAL_ORIGIN=http://localhost:3000 - -# Only for steps that run without the real env (lint, type-check). A build still needs -# API_INTERNAL_ORIGIN: the /api rewrite keeps the value it was built with. +# Only for steps that run without the real env (lint, type-check). SKIP_ENV_VALIDATION=false diff --git a/apps/bear/next.config.ts b/apps/bear/next.config.ts index 8854907..2583c6b 100644 --- a/apps/bear/next.config.ts +++ b/apps/bear/next.config.ts @@ -8,12 +8,8 @@ import { import type { NextConfig } from 'next'; import path from 'node:path'; -import { - API_PROXY_MAX_BODY, - API_PROXY_PATH, - API_PROXY_TIMEOUT_MS, -} from './src/constants'; -import { apiInternalUrl } from './src/env/env.config'; +// Libs compile from source outside the app, so tracing and Turbopack both start at the workspace root. +const workspaceRoot = path.join(__dirname, '../..'); // Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new // ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again. @@ -30,16 +26,19 @@ const security = [ { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, ]; +// The edge nginx (0001) passes a streamed page on as each part renders instead of buffering it whole. +const streaming = [{ key: 'X-Accel-Buffering', value: 'no' }]; + const nextConfig: NextConfig = { + // The image runs .next/standalone/apps//server.js with only the traced files; it never loads + // this file at runtime, so the plugins below never run in the container. + output: 'standalone', + outputFileTracingRoot: workspaceRoot, + turbopack: { root: workspaceRoot }, + poweredByHeader: false, // Every visitor gets the metadata in , where Chrome looks for the manifest and Safari for // its home-screen tags; Next.js would otherwise stream it to the end of (0054). htmlLimitedBots: /.*/, - // The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default - // and two ID images come close to its 10 MB body limit. - experimental: { - proxyTimeout: API_PROXY_TIMEOUT_MS, - proxyClientMaxBodySize: API_PROXY_MAX_BODY, - }, // Workspace packages export TypeScript source, so Next.js compiles them. transpilePackages: [ '@lumina/market', @@ -48,23 +47,12 @@ const nextConfig: NextConfig = { '@lumina/libs', '@lumina/tools', ], - // The browser calls the API on this site's origin (`/api/v1/…`, `/api/files/…`), and the API - // calls are proxied to the gateway, so there is no CORS and the session cookies are this site's - // (0018). - async rewrites() { - return [ - { - source: `${API_PROXY_PATH}/:path*`, - destination: `${apiInternalUrl()}/:path*`, - }, - ]; - }, async headers() { // Only Next calls `headers()`, on `next dev` and `next build`, so the worker is written here, as // island's plugins write theirs. Next runs from the app's folder, as every Nx target does. writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') }); return [ - { source: '/:path*', headers: security }, + { source: '/:path*', headers: [...security, ...streaming] }, { source: '/fonts/:path*', headers: immutable }, { source: '/icons/:path*', headers: immutable }, // Revalidated on every update check, so a new worker reaches visitors at their next diff --git a/apps/bear/src/app/(landing)/page.tsx b/apps/bear/src/app/(landing)/page.tsx index ab0e0fe..2bca8ae 100644 --- a/apps/bear/src/app/(landing)/page.tsx +++ b/apps/bear/src/app/(landing)/page.tsx @@ -54,6 +54,7 @@ export default async function LandingPage() { siteHost={displayUrl('')} labels={labels} /> +

amiram v2

diff --git a/apps/bear/src/bootstrap/bootstrap.server.ts b/apps/bear/src/bootstrap/bootstrap.server.ts index 994c332..9263ec5 100644 --- a/apps/bear/src/bootstrap/bootstrap.server.ts +++ b/apps/bear/src/bootstrap/bootstrap.server.ts @@ -8,11 +8,7 @@ import { setEnv as setMarketEnv } from '@lumina/market/env'; import { SERVER_RESOURCES } from '@lumina/market/server'; import { cookies } from 'next/headers'; -import { - API_PROXY_PATH, - API_VERSION_PATH, - FORWARDED_COOKIES, -} from '../constants'; +import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants'; import { clientEnv } from '../env'; import { serverEnv } from '../env/server'; import { i18n } from '../i18n'; @@ -20,16 +16,17 @@ import { ERROR_HANDLER_CONFIG } from './error-reporting'; // Fills the server module graph once, before rendering. Idempotent: safe to run again. setMarketEnv({ - apiBaseUrl: API_PROXY_PATH, + apiBaseUrl: clientEnv.NEXT_PUBLIC_CLIENT_END_POINT, baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE, telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, }); -// Server requests forward only the allowlisted cookies, never the session: the server render is -// the same for every visitor, and the browser loads whatever depends on the viewer. Read on each -// request; nothing per visitor is kept in module state. +// Server requests go straight to the gateway (`INTERNAL_END_POINT`, 0066) and forward only the +// allowlisted cookies, never the session: the server render is the same for every visitor, and the +// browser loads whatever depends on the viewer. Read on each request; nothing per visitor is kept +// in module state. configureServerHttp({ - baseUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`, + baseUrl: `${serverEnv.INTERNAL_END_POINT}${API_VERSION_PATH}`, getCookieHeader: async () => (await cookies()) .getAll() diff --git a/apps/bear/src/constants/api.ts b/apps/bear/src/constants/api.ts index 8ec7915..6535d63 100644 --- a/apps/bear/src/constants/api.ts +++ b/apps/bear/src/constants/api.ts @@ -1,22 +1,2 @@ /** Every gateway route except `/files/*` sits under this prefix. */ export const API_VERSION_PATH = '/v1'; - -/** - * Where the browser reaches the API: this site's own origin, under this path. next.config.ts - * rewrites it to the gateway (`API_INTERNAL_ORIGIN`), so no browser request is cross-origin and - * the session cookies belong to this site (0018). The server render calls the gateway directly. - */ -export const API_PROXY_PATH = '/api'; - -/** - * How long the `/api` proxy waits for the gateway. Next.js stops at 30 seconds by default; an - * upload (two 5 MB ID images, post media) on a slow connection takes longer, and the HTTP lib - * sets no timeout for uploads. - */ -export const API_PROXY_TIMEOUT_MS = 120_000; - -/** - * The largest request body the `/api` proxy passes on (Next.js cuts at 10 MB by default). Creator - * registration and verification send two 5 MB ID images plus the form in one request. - */ -export const API_PROXY_MAX_BODY = '12mb'; diff --git a/apps/bear/src/constants/index.ts b/apps/bear/src/constants/index.ts index 1f14e50..7e3ce17 100644 --- a/apps/bear/src/constants/index.ts +++ b/apps/bear/src/constants/index.ts @@ -1,7 +1,2 @@ -export { - API_PROXY_MAX_BODY, - API_PROXY_PATH, - API_PROXY_TIMEOUT_MS, - API_VERSION_PATH, -} from './api'; +export { API_VERSION_PATH } from './api'; export { FORWARDED_COOKIES } from './cookies'; diff --git a/apps/bear/src/env/env.client.ts b/apps/bear/src/env/env.client.ts index 8875c8f..4098f5f 100644 --- a/apps/bear/src/env/env.client.ts +++ b/apps/bear/src/env/env.client.ts @@ -1,4 +1,4 @@ -import { createClientEnv } from '@lumina/libs/env'; +import { createClientEnv, origin } from '@lumina/libs/env'; import * as v from 'valibot'; const required = v.pipe(v.string(), v.nonEmpty()); @@ -13,6 +13,11 @@ export const clientEnv = createClientEnv({ prefix: 'NEXT_PUBLIC_', schema: { NEXT_PUBLIC_SITE_URL: url, + /** + * The gateway's public origin: the browser calls it directly, with the session cookies (0066). + * Media URLs use it too, so the server render writes the same address. + */ + NEXT_PUBLIC_CLIENT_END_POINT: origin, NEXT_PUBLIC_BALE_HANDLE: required, NEXT_PUBLIC_TELEGRAM_HANDLE: required, NEXT_PUBLIC_SUPPORT_HOURS: required, @@ -21,6 +26,7 @@ export const clientEnv = createClientEnv({ }, runtimeEnv: { NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL, + NEXT_PUBLIC_CLIENT_END_POINT: process.env.NEXT_PUBLIC_CLIENT_END_POINT, NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE, NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE, NEXT_PUBLIC_SUPPORT_HOURS: process.env.NEXT_PUBLIC_SUPPORT_HOURS, diff --git a/apps/bear/src/env/env.config.ts b/apps/bear/src/env/env.config.ts deleted file mode 100644 index 46efa4e..0000000 --- a/apps/bear/src/env/env.config.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { origin } from '@lumina/libs/env'; -import * as v from 'valibot'; - -/** - * For next.config.ts only: the gateway the `/api` rewrite proxies to. No `server-only` here, as - * the config loads outside React. `next build` writes rewrites into its output, so the value is - * the one at build time (0018) and `SKIP_ENV_VALIDATION` can't skip it: a build without it fails - * here, rather than shipping a proxy to the wrong gateway. - */ -export function apiInternalUrl(): string { - const result = v.safeParse(origin, process.env.API_INTERNAL_ORIGIN); - if (result.success) return result.output; - throw new Error( - `API_INTERNAL_ORIGIN is needed to build: next.config rewrites /api to it and next build keeps the value (0018). ${result.issues[0].message}`, - ); -} diff --git a/apps/bear/src/env/env.server.ts b/apps/bear/src/env/env.server.ts index 4094bf6..037df2e 100644 --- a/apps/bear/src/env/env.server.ts +++ b/apps/bear/src/env/env.server.ts @@ -7,8 +7,8 @@ import * as v from 'valibot'; /** Server variables; only server code imports them, through `env/server`. */ export const serverEnv = createServerEnv({ schema: { - /** The gateway from inside the deployment network: server requests and the `/api` proxy. */ - API_INTERNAL_ORIGIN: origin, + /** The gateway from inside the deployment network, for server requests only (0066). */ + INTERNAL_END_POINT: origin, /** * Set by Next.js itself, never in `.env`: `phase-production-build` while `next build` * prerenders pages (the landing, 0026). diff --git a/apps/bull/.env.example b/apps/bull/.env.sample similarity index 60% rename from apps/bull/.env.example rename to apps/bull/.env.sample index f94a1b5..6edf75f 100644 --- a/apps/bull/.env.example +++ b/apps/bull/.env.sample @@ -1,5 +1,13 @@ # Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one. NEXT_PUBLIC_SITE_URL=http://localhost:7000 + +# The API, one end point per side (0066), each an origin with no path. The browser calls +# NEXT_PUBLIC_CLIENT_END_POINT, the gateway's public origin, directly with the session cookies, so +# the gateway must allow this site's origin in CORS; next build inlines it. Server requests go to +# INTERNAL_END_POINT: the gateway's origin from inside the deployment network, server only. +NEXT_PUBLIC_CLIENT_END_POINT=http://localhost:3000 +INTERNAL_END_POINT=http://localhost:3000 + NEXT_PUBLIC_BALE_HANDLE=lumina_support NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸ @@ -9,10 +17,5 @@ NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸ # there unregisters the worker for every visitor on their next page load (the kill switch). NEXT_PUBLIC_SERVICE_WORKER_ENABLED=false -# Server only: the gateway's origin from inside the deployment network. Server requests go -# there, and so does the browser's /api proxy (next.config rewrite, fixed at build time). -API_INTERNAL_ORIGIN=http://localhost:3000 - -# Only for steps that run without the real env (lint, type-check). A build still needs -# API_INTERNAL_ORIGIN: the /api rewrite keeps the value it was built with. +# Only for steps that run without the real env (lint, type-check). SKIP_ENV_VALIDATION=false diff --git a/apps/bull/next.config.ts b/apps/bull/next.config.ts index 8854907..2583c6b 100644 --- a/apps/bull/next.config.ts +++ b/apps/bull/next.config.ts @@ -8,12 +8,8 @@ import { import type { NextConfig } from 'next'; import path from 'node:path'; -import { - API_PROXY_MAX_BODY, - API_PROXY_PATH, - API_PROXY_TIMEOUT_MS, -} from './src/constants'; -import { apiInternalUrl } from './src/env/env.config'; +// Libs compile from source outside the app, so tracing and Turbopack both start at the workspace root. +const workspaceRoot = path.join(__dirname, '../..'); // Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new // ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again. @@ -30,16 +26,19 @@ const security = [ { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, ]; +// The edge nginx (0001) passes a streamed page on as each part renders instead of buffering it whole. +const streaming = [{ key: 'X-Accel-Buffering', value: 'no' }]; + const nextConfig: NextConfig = { + // The image runs .next/standalone/apps//server.js with only the traced files; it never loads + // this file at runtime, so the plugins below never run in the container. + output: 'standalone', + outputFileTracingRoot: workspaceRoot, + turbopack: { root: workspaceRoot }, + poweredByHeader: false, // Every visitor gets the metadata in , where Chrome looks for the manifest and Safari for // its home-screen tags; Next.js would otherwise stream it to the end of (0054). htmlLimitedBots: /.*/, - // The `/api` proxy's wait for the gateway (0018); uploads outlast Next.js's 30-second default - // and two ID images come close to its 10 MB body limit. - experimental: { - proxyTimeout: API_PROXY_TIMEOUT_MS, - proxyClientMaxBodySize: API_PROXY_MAX_BODY, - }, // Workspace packages export TypeScript source, so Next.js compiles them. transpilePackages: [ '@lumina/market', @@ -48,23 +47,12 @@ const nextConfig: NextConfig = { '@lumina/libs', '@lumina/tools', ], - // The browser calls the API on this site's origin (`/api/v1/…`, `/api/files/…`), and the API - // calls are proxied to the gateway, so there is no CORS and the session cookies are this site's - // (0018). - async rewrites() { - return [ - { - source: `${API_PROXY_PATH}/:path*`, - destination: `${apiInternalUrl()}/:path*`, - }, - ]; - }, async headers() { // Only Next calls `headers()`, on `next dev` and `next build`, so the worker is written here, as // island's plugins write theirs. Next runs from the app's folder, as every Nx target does. writeServiceWorker({ publicDir: path.join(process.cwd(), 'public') }); return [ - { source: '/:path*', headers: security }, + { source: '/:path*', headers: [...security, ...streaming] }, { source: '/fonts/:path*', headers: immutable }, { source: '/icons/:path*', headers: immutable }, // Revalidated on every update check, so a new worker reaches visitors at their next diff --git a/apps/bull/src/app/healthz/route.ts b/apps/bull/src/app/healthz/route.ts new file mode 100644 index 0000000..20d290e --- /dev/null +++ b/apps/bull/src/app/healthz/route.ts @@ -0,0 +1,12 @@ +import { serverEnv } from '../../env/server'; + +export const dynamic = 'force-dynamic'; + +// The image's health check: importing the server env validates it, so a release with missing or invalid +// env answers 500. It calls no back end, so a back-end outage never fails the check. +export function GET(): Response { + void serverEnv; + return new Response('ok', { + headers: { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' }, + }); +} diff --git a/apps/bull/src/bootstrap/bootstrap.client.ts b/apps/bull/src/bootstrap/bootstrap.client.ts index bd5aaa1..de32613 100644 --- a/apps/bull/src/bootstrap/bootstrap.client.ts +++ b/apps/bull/src/bootstrap/bootstrap.client.ts @@ -12,25 +12,25 @@ import { suspendedSessionOf, } from '@lumina/market/features/auth'; -import { API_PROXY_PATH, API_VERSION_PATH } from '../constants'; +import { API_VERSION_PATH } from '../constants'; import { clientEnv } from '../env'; import { ERROR_HANDLER_CONFIG } from './error-reporting'; // Fills the client module graph with public values only, before client components render (during // SSR and in the browser). Idempotent: safe to run again. setMarketEnv({ - apiBaseUrl: API_PROXY_PATH, + apiBaseUrl: clientEnv.NEXT_PUBLIC_CLIENT_END_POINT, baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE, telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, }); -// The browser calls the API on this site's origin, proxied to the gateway (0018). The session +// The browser calls the gateway directly at its public origin (0066). The session // lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the whole app; // when that fails the session is over and the shell signs the user out. A 401 `ACCOUNT_SUSPENDED` // never refreshes: the account was suspended mid-session, so the session ends and the page halts // (J01-3d), once, whichever request learns it first. http.configure({ - baseUrl: `${API_PROXY_PATH}${API_VERSION_PATH}`, + baseUrl: `${clientEnv.NEXT_PUBLIC_CLIENT_END_POINT}${API_VERSION_PATH}`, refresh: { endpoint: AUTH_ENDPOINTS.refresh, shouldRefresh: (error) => diff --git a/apps/bull/src/bootstrap/bootstrap.server.ts b/apps/bull/src/bootstrap/bootstrap.server.ts index 994c332..9263ec5 100644 --- a/apps/bull/src/bootstrap/bootstrap.server.ts +++ b/apps/bull/src/bootstrap/bootstrap.server.ts @@ -8,11 +8,7 @@ import { setEnv as setMarketEnv } from '@lumina/market/env'; import { SERVER_RESOURCES } from '@lumina/market/server'; import { cookies } from 'next/headers'; -import { - API_PROXY_PATH, - API_VERSION_PATH, - FORWARDED_COOKIES, -} from '../constants'; +import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants'; import { clientEnv } from '../env'; import { serverEnv } from '../env/server'; import { i18n } from '../i18n'; @@ -20,16 +16,17 @@ import { ERROR_HANDLER_CONFIG } from './error-reporting'; // Fills the server module graph once, before rendering. Idempotent: safe to run again. setMarketEnv({ - apiBaseUrl: API_PROXY_PATH, + apiBaseUrl: clientEnv.NEXT_PUBLIC_CLIENT_END_POINT, baleHandle: clientEnv.NEXT_PUBLIC_BALE_HANDLE, telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, }); -// Server requests forward only the allowlisted cookies, never the session: the server render is -// the same for every visitor, and the browser loads whatever depends on the viewer. Read on each -// request; nothing per visitor is kept in module state. +// Server requests go straight to the gateway (`INTERNAL_END_POINT`, 0066) and forward only the +// allowlisted cookies, never the session: the server render is the same for every visitor, and the +// browser loads whatever depends on the viewer. Read on each request; nothing per visitor is kept +// in module state. configureServerHttp({ - baseUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`, + baseUrl: `${serverEnv.INTERNAL_END_POINT}${API_VERSION_PATH}`, getCookieHeader: async () => (await cookies()) .getAll() diff --git a/apps/bull/src/constants/api.ts b/apps/bull/src/constants/api.ts index 8ec7915..6535d63 100644 --- a/apps/bull/src/constants/api.ts +++ b/apps/bull/src/constants/api.ts @@ -1,22 +1,2 @@ /** Every gateway route except `/files/*` sits under this prefix. */ export const API_VERSION_PATH = '/v1'; - -/** - * Where the browser reaches the API: this site's own origin, under this path. next.config.ts - * rewrites it to the gateway (`API_INTERNAL_ORIGIN`), so no browser request is cross-origin and - * the session cookies belong to this site (0018). The server render calls the gateway directly. - */ -export const API_PROXY_PATH = '/api'; - -/** - * How long the `/api` proxy waits for the gateway. Next.js stops at 30 seconds by default; an - * upload (two 5 MB ID images, post media) on a slow connection takes longer, and the HTTP lib - * sets no timeout for uploads. - */ -export const API_PROXY_TIMEOUT_MS = 120_000; - -/** - * The largest request body the `/api` proxy passes on (Next.js cuts at 10 MB by default). Creator - * registration and verification send two 5 MB ID images plus the form in one request. - */ -export const API_PROXY_MAX_BODY = '12mb'; diff --git a/apps/bull/src/constants/index.ts b/apps/bull/src/constants/index.ts index 1f14e50..7e3ce17 100644 --- a/apps/bull/src/constants/index.ts +++ b/apps/bull/src/constants/index.ts @@ -1,7 +1,2 @@ -export { - API_PROXY_MAX_BODY, - API_PROXY_PATH, - API_PROXY_TIMEOUT_MS, - API_VERSION_PATH, -} from './api'; +export { API_VERSION_PATH } from './api'; export { FORWARDED_COOKIES } from './cookies'; diff --git a/apps/bull/src/env/env.client.ts b/apps/bull/src/env/env.client.ts index 8875c8f..4098f5f 100644 --- a/apps/bull/src/env/env.client.ts +++ b/apps/bull/src/env/env.client.ts @@ -1,4 +1,4 @@ -import { createClientEnv } from '@lumina/libs/env'; +import { createClientEnv, origin } from '@lumina/libs/env'; import * as v from 'valibot'; const required = v.pipe(v.string(), v.nonEmpty()); @@ -13,6 +13,11 @@ export const clientEnv = createClientEnv({ prefix: 'NEXT_PUBLIC_', schema: { NEXT_PUBLIC_SITE_URL: url, + /** + * The gateway's public origin: the browser calls it directly, with the session cookies (0066). + * Media URLs use it too, so the server render writes the same address. + */ + NEXT_PUBLIC_CLIENT_END_POINT: origin, NEXT_PUBLIC_BALE_HANDLE: required, NEXT_PUBLIC_TELEGRAM_HANDLE: required, NEXT_PUBLIC_SUPPORT_HOURS: required, @@ -21,6 +26,7 @@ export const clientEnv = createClientEnv({ }, runtimeEnv: { NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL, + NEXT_PUBLIC_CLIENT_END_POINT: process.env.NEXT_PUBLIC_CLIENT_END_POINT, NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE, NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE, NEXT_PUBLIC_SUPPORT_HOURS: process.env.NEXT_PUBLIC_SUPPORT_HOURS, diff --git a/apps/bull/src/env/env.config.ts b/apps/bull/src/env/env.config.ts deleted file mode 100644 index 46efa4e..0000000 --- a/apps/bull/src/env/env.config.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { origin } from '@lumina/libs/env'; -import * as v from 'valibot'; - -/** - * For next.config.ts only: the gateway the `/api` rewrite proxies to. No `server-only` here, as - * the config loads outside React. `next build` writes rewrites into its output, so the value is - * the one at build time (0018) and `SKIP_ENV_VALIDATION` can't skip it: a build without it fails - * here, rather than shipping a proxy to the wrong gateway. - */ -export function apiInternalUrl(): string { - const result = v.safeParse(origin, process.env.API_INTERNAL_ORIGIN); - if (result.success) return result.output; - throw new Error( - `API_INTERNAL_ORIGIN is needed to build: next.config rewrites /api to it and next build keeps the value (0018). ${result.issues[0].message}`, - ); -} diff --git a/apps/bull/src/env/env.server.ts b/apps/bull/src/env/env.server.ts index 4094bf6..037df2e 100644 --- a/apps/bull/src/env/env.server.ts +++ b/apps/bull/src/env/env.server.ts @@ -7,8 +7,8 @@ import * as v from 'valibot'; /** Server variables; only server code imports them, through `env/server`. */ export const serverEnv = createServerEnv({ schema: { - /** The gateway from inside the deployment network: server requests and the `/api` proxy. */ - API_INTERNAL_ORIGIN: origin, + /** The gateway from inside the deployment network, for server requests only (0066). */ + INTERNAL_END_POINT: origin, /** * Set by Next.js itself, never in `.env`: `phase-production-build` while `next build` * prerenders pages (the landing, 0026). diff --git a/apps/wall-street-plaza/.env.example b/apps/wall-street-plaza/.env.example deleted file mode 100644 index d2e1012..0000000 --- a/apps/wall-street-plaza/.env.example +++ /dev/null @@ -1,11 +0,0 @@ -# Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one. -NEXT_PUBLIC_SITE_URL=http://localhost:7002 - -# Server only: the admin API's origin from inside the deployment network (0061). The browser's -# /api proxy goes there (next.config rewrite, fixed at build time). The admin app never calls the -# public gateway. -ADMIN_API_INTERNAL_ORIGIN=http://localhost:9010 - -# Only for steps that run without the real env (lint, type-check). A build still needs -# ADMIN_API_INTERNAL_ORIGIN: the /api rewrite keeps the value it was built with. -SKIP_ENV_VALIDATION=false diff --git a/apps/wall-street-plaza/.env.sample b/apps/wall-street-plaza/.env.sample new file mode 100644 index 0000000..8801918 --- /dev/null +++ b/apps/wall-street-plaza/.env.sample @@ -0,0 +1,12 @@ +# Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one. +NEXT_PUBLIC_SITE_URL=http://localhost:7002 + +# The API, one end point per side (0066), each an origin with no path. The browser calls +# NEXT_PUBLIC_CLIENT_END_POINT, the admin API's public origin, directly with the session cookies, so +# the admin API must allow this site's origin in CORS; next build inlines it. Server requests go to +# INTERNAL_END_POINT: the admin API's origin from inside the deployment network, server only. +NEXT_PUBLIC_CLIENT_END_POINT=http://localhost:9010 +INTERNAL_END_POINT=http://localhost:9010 + +# Only for steps that run without the real env (lint, type-check). +SKIP_ENV_VALIDATION=false diff --git a/apps/wall-street-plaza/next.config.ts b/apps/wall-street-plaza/next.config.ts index 3b8f508..304c47c 100644 --- a/apps/wall-street-plaza/next.config.ts +++ b/apps/wall-street-plaza/next.config.ts @@ -1,13 +1,10 @@ import { withFontCopy } from '@lumina/island/tools/font-copy-plugin'; import { withIconSprite } from '@lumina/island/tools/icon-sprite-plugin'; import type { NextConfig } from 'next'; +import path from 'node:path'; -import { - API_PROXY_MAX_BODY, - API_PROXY_PATH, - API_PROXY_TIMEOUT_MS, -} from './src/constants'; -import { adminApiInternalUrl } from './src/env/env.config'; +// Libs compile from source outside the app, so tracing and Turbopack both start at the workspace root. +const workspaceRoot = path.join(__dirname, '../..'); // Fonts and the icon sprite keep fixed names (0011, 0012); Next serves public/ with max-age=0. const immutable = [ @@ -23,16 +20,21 @@ const security = [ { key: 'X-Robots-Tag', value: 'noindex, nofollow' }, ]; +// The edge nginx (0001) passes a streamed page on as each part renders instead of buffering it whole. +const streaming = [{ key: 'X-Accel-Buffering', value: 'no' }]; + const nextConfig: NextConfig = { + // The image runs .next/standalone/apps//server.js with only the traced files; it never loads + // this file at runtime, so the plugins below never run in the container. + output: 'standalone', + outputFileTracingRoot: workspaceRoot, + turbopack: { root: workspaceRoot }, + poweredByHeader: false, // Set when the panel shares an origin with the market apps under a path (e.g. `/admin`); empty // in local dev, where the panel has its own port. basePath: process.env.NEXT_BASE_PATH ?? '', // Metadata always in (0054). htmlLimitedBots: /.*/, - experimental: { - proxyTimeout: API_PROXY_TIMEOUT_MS, - proxyClientMaxBodySize: API_PROXY_MAX_BODY, - }, // Workspace packages export TypeScript source, so Next.js compiles them. transpilePackages: [ '@lumina/garden-roof', @@ -41,20 +43,10 @@ const nextConfig: NextConfig = { '@lumina/libs', '@lumina/tools', ], - // The browser calls the admin API on this site's origin (`/api/v1/admin/…`), proxied to - // admin-api, so there is no CORS and the session cookies are this site's (0061). No service - // worker or manifest: the panel isn't installable (0062). - async rewrites() { - return [ - { - source: `${API_PROXY_PATH}/:path*`, - destination: `${adminApiInternalUrl()}/:path*`, - }, - ]; - }, + // No service worker or manifest: the panel isn't installable (0062). async headers() { return [ - { source: '/:path*', headers: security }, + { source: '/:path*', headers: [...security, ...streaming] }, { source: '/fonts/:path*', headers: immutable }, { source: '/icons/:path*', headers: immutable }, ]; diff --git a/apps/wall-street-plaza/src/app/healthz/route.ts b/apps/wall-street-plaza/src/app/healthz/route.ts new file mode 100644 index 0000000..df7b7a7 --- /dev/null +++ b/apps/wall-street-plaza/src/app/healthz/route.ts @@ -0,0 +1,12 @@ +import { serverEnv } from '../../env/server'; + +export const dynamic = 'force-dynamic'; + +// The image's health check: importing the server env validates it, so a release with missing or invalid +// env answers 500. It calls no back end, so an admin-api outage never fails the check. +export function GET(): Response { + void serverEnv; + return new Response('ok', { + headers: { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' }, + }); +} diff --git a/apps/wall-street-plaza/src/bootstrap/bootstrap.client.ts b/apps/wall-street-plaza/src/bootstrap/bootstrap.client.ts index 5e0733c..8c0676b 100644 --- a/apps/wall-street-plaza/src/bootstrap/bootstrap.client.ts +++ b/apps/wall-street-plaza/src/bootstrap/bootstrap.client.ts @@ -5,17 +5,18 @@ import { configureErrorHandler } from '@lumina/libs/error-handler'; import { eventEmitter } from '@lumina/libs/event-emitter'; import { http } from '@lumina/libs/http'; -import { API_PROXY_PATH, API_VERSION_PATH } from '../constants'; +import { API_VERSION_PATH } from '../constants'; +import { clientEnv } from '../env'; import { ERROR_HANDLER_CONFIG } from './error-reporting'; // Fills the client module graph with public values only, before client components render (during // SSR and in the browser). Idempotent: safe to run again. -setGardenRoofEnv({ apiBaseUrl: API_PROXY_PATH }); -// The browser calls the admin API on this site's origin, proxied to admin-api (0061). The session +setGardenRoofEnv({ apiBaseUrl: clientEnv.NEXT_PUBLIC_CLIENT_END_POINT }); +// The browser calls admin-api directly at its public origin (0061, 0066). The session // lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the whole app; // when that fails the session is over and the shell signs the admin out. http.configure({ - baseUrl: `${API_PROXY_PATH}${API_VERSION_PATH}`, + baseUrl: `${clientEnv.NEXT_PUBLIC_CLIENT_END_POINT}${API_VERSION_PATH}`, refresh: { endpoint: AUTH_ENDPOINTS.refresh, onFailure: () => { diff --git a/apps/wall-street-plaza/src/bootstrap/bootstrap.server.ts b/apps/wall-street-plaza/src/bootstrap/bootstrap.server.ts index fd3f80c..c9603e3 100644 --- a/apps/wall-street-plaza/src/bootstrap/bootstrap.server.ts +++ b/apps/wall-street-plaza/src/bootstrap/bootstrap.server.ts @@ -3,10 +3,10 @@ import 'server-only'; import { setEnv as setGardenRoofEnv } from '@lumina/garden-roof/env'; import { configureErrorHandler } from '@lumina/libs/error-handler'; -import { API_PROXY_PATH } from '../constants'; +import { clientEnv } from '../env'; import { ERROR_HANDLER_CONFIG } from './error-reporting'; // Fills the server module graph once, before rendering. The server reads nothing from the admin // API (0062): every panel read runs in the browser, so no server HTTP client is configured. -setGardenRoofEnv({ apiBaseUrl: API_PROXY_PATH }); +setGardenRoofEnv({ apiBaseUrl: clientEnv.NEXT_PUBLIC_CLIENT_END_POINT }); configureErrorHandler(ERROR_HANDLER_CONFIG); diff --git a/apps/wall-street-plaza/src/constants/api.ts b/apps/wall-street-plaza/src/constants/api.ts index 83fa79f..a4384da 100644 --- a/apps/wall-street-plaza/src/constants/api.ts +++ b/apps/wall-street-plaza/src/constants/api.ts @@ -1,15 +1,2 @@ /** Every admin API route sits under this prefix. */ export const API_VERSION_PATH = '/v1'; - -/** - * Where the browser reaches the admin API: this site's own origin, under this path. - * next.config.ts rewrites it to `admin-api` (`ADMIN_API_INTERNAL_ORIGIN`), so no browser request - * is cross-origin and the session cookies belong to this site (0061, as 0018). - */ -export const API_PROXY_PATH = '/api'; - -/** How long the `/api` proxy waits for the admin API; a payout receipt upload outlasts 30 s. */ -export const API_PROXY_TIMEOUT_MS = 120_000; - -/** The largest request body the `/api` proxy passes on: a payout receipt (5 MB) with its form. */ -export const API_PROXY_MAX_BODY = '8mb'; diff --git a/apps/wall-street-plaza/src/constants/index.ts b/apps/wall-street-plaza/src/constants/index.ts index f2400a0..80dfdd5 100644 --- a/apps/wall-street-plaza/src/constants/index.ts +++ b/apps/wall-street-plaza/src/constants/index.ts @@ -1,6 +1 @@ -export { - API_PROXY_MAX_BODY, - API_PROXY_PATH, - API_PROXY_TIMEOUT_MS, - API_VERSION_PATH, -} from './api'; +export { API_VERSION_PATH } from './api'; diff --git a/apps/wall-street-plaza/src/env/env.client.ts b/apps/wall-street-plaza/src/env/env.client.ts index 16b1317..efbb6b7 100644 --- a/apps/wall-street-plaza/src/env/env.client.ts +++ b/apps/wall-street-plaza/src/env/env.client.ts @@ -1,4 +1,4 @@ -import { createClientEnv } from '@lumina/libs/env'; +import { createClientEnv, origin } from '@lumina/libs/env'; import * as v from 'valibot'; const url = v.pipe(v.string(), v.url()); @@ -8,8 +8,14 @@ export const clientEnv = createClientEnv({ prefix: 'NEXT_PUBLIC_', schema: { NEXT_PUBLIC_SITE_URL: url, + /** + * The admin API's public origin: the browser calls it directly, with the session cookies + * (0061, 0066). Upload URLs use it too. + */ + NEXT_PUBLIC_CLIENT_END_POINT: origin, }, runtimeEnv: { NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL, + NEXT_PUBLIC_CLIENT_END_POINT: process.env.NEXT_PUBLIC_CLIENT_END_POINT, }, }); diff --git a/apps/wall-street-plaza/src/env/env.config.ts b/apps/wall-street-plaza/src/env/env.config.ts deleted file mode 100644 index 45a3289..0000000 --- a/apps/wall-street-plaza/src/env/env.config.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { origin } from '@lumina/libs/env'; -import * as v from 'valibot'; - -/** - * For next.config.ts only: the admin API the `/api` rewrite proxies to. No `server-only` here, as - * the config loads outside React. `next build` writes rewrites into its output, so the value is - * the one at build time and `SKIP_ENV_VALIDATION` can't skip it. - */ -export function adminApiInternalUrl(): string { - const result = v.safeParse(origin, process.env.ADMIN_API_INTERNAL_ORIGIN); - if (result.success) return result.output; - throw new Error( - `ADMIN_API_INTERNAL_ORIGIN is needed to build: next.config rewrites /api to it and next build keeps the value (0061). ${result.issues[0].message}`, - ); -} diff --git a/apps/wall-street-plaza/src/env/env.server.ts b/apps/wall-street-plaza/src/env/env.server.ts index 9fb35f9..f683ca1 100644 --- a/apps/wall-street-plaza/src/env/env.server.ts +++ b/apps/wall-street-plaza/src/env/env.server.ts @@ -6,8 +6,11 @@ import { createServerEnv } from '@lumina/libs/env/server'; /** Server variables; only server code imports them, through `env/server`. */ export const serverEnv = createServerEnv({ schema: { - /** The admin API from inside the deployment network: the `/api` proxy's destination. */ - ADMIN_API_INTERNAL_ORIGIN: origin, + /** + * The admin API from inside the deployment network (0061), for server requests only (0066). The + * server reads nothing from it yet (0062). + */ + INTERNAL_END_POINT: origin, }, runtimeEnv: process.env, skipValidation: process.env.SKIP_ENV_VALIDATION === 'true', diff --git a/docs/decisions/0018-browser-calls-the-api-through-a-next-rewrite.md b/docs/decisions/0018-browser-calls-the-api-through-a-next-rewrite.md index 70026d8..8698e40 100644 --- a/docs/decisions/0018-browser-calls-the-api-through-a-next-rewrite.md +++ b/docs/decisions/0018-browser-calls-the-api-through-a-next-rewrite.md @@ -1,6 +1,6 @@ # 0018 The browser calls the API through a Next.js rewrite -Status: Accepted · Area: architecture · Date: 2026-10-06 · Decided by: user +Status: Superseded by 0065 · Area: architecture · Date: 2026-10-06 · Decided by: user ## Context The browser called the gateway on its own origin with credentials, so every call was cross-origin: CORS preflights, a CORS allowlist to keep in step, and session cookies that belonged to the API host. diff --git a/docs/decisions/0061-admin-app-and-platform.md b/docs/decisions/0061-admin-app-and-platform.md index 5e17df4..f3367e1 100644 --- a/docs/decisions/0061-admin-app-and-platform.md +++ b/docs/decisions/0061-admin-app-and-platform.md @@ -7,7 +7,7 @@ The admin panel (journey J11 in the app design) was out of scope, and admin-only ## Decision - `apps/wall-street-plaza` is the admin app and `platforms/garden-roof` its platform; both are tagged `scope:admin`. `scope:admin` depends only on `scope:admin` and `scope:shared`. `scope:market` never imports `scope:admin`, and the reverse is also not allowed. -- The admin app talks only to the back end's admin API (`apps/admin-api` in the Nest monorepo), never to the public gateway. The browser calls it on the app's own origin under `/api`, rewritten to `ADMIN_API_INTERNAL_ORIGIN`, as 0018 does for the gateway. +- The admin app talks only to the back end's admin API (`apps/admin-api` in the Nest monorepo), never to the public gateway. The browser calls it directly at its public origin, as 0066 does for the gateway. - The admin app builds and deploys on its own origin (dev port 7002), so no admin code ships in bull or bear. ## Alternatives diff --git a/docs/decisions/0065-api-end-points-per-side.md b/docs/decisions/0065-api-end-points-per-side.md new file mode 100644 index 0000000..677b91a --- /dev/null +++ b/docs/decisions/0065-api-end-points-per-side.md @@ -0,0 +1,21 @@ +# 0065 One API end point per side + +Status: Superseded by 0066 · Area: architecture · Date: 2026-10-16 · Decided by: user · Supersedes: 0018 + +## Context +The server's API address was an env value (`API_INTERNAL_ORIGIN`, `ADMIN_API_INTERNAL_ORIGIN` in the admin app) and the browser's was a constant (`API_PROXY_PATH = '/api'`). The user wants both as env values with the same keys in every app, set in the bootstraps. + +## Decision +- Every app's env has `INTERNAL_END_POINT` (server only) and `NEXT_PUBLIC_CLIENT_END_POINT` (public), with the same names in bull, bear and wall-street-plaza. +- `INTERNAL_END_POINT` is the API's origin from inside the deployment network (the gateway, or admin-api in the admin app). The server bootstrap's HTTP client calls it directly and sends no session cookies. +- `NEXT_PUBLIC_CLIENT_END_POINT` is a path on the app's own origin (`/api`), never another origin. The client bootstrap's HTTP client and the platform's `apiBaseUrl` (media URLs) use it, and each app's `next.config.ts` rewrites `/:path*` to `INTERNAL_END_POINT`. +- The gateway still scopes the refresh cookie to `/api/v1/auth` (`AUTH_COOKIE_PATH_PREFIX=/api`) and keeps the apps' origins in `CORS_ORIGINS`. + +## Alternatives +- A constant `/api` for the browser (0018): replaced, the user wants both sides set by env. +- A full URL for the browser end point: not chosen; cross-origin calls bring back CORS and API-host cookies (0018's context). The env lib's `sitePath` rejects an origin. + +## Consequences +- `next build` fixes the rewrite, so each environment's build needs both values; `SKIP_ENV_VALIDATION` can't skip them, and a build without them fails. +- Changing `NEXT_PUBLIC_CLIENT_END_POINT` from `/api` also needs the gateway's `AUTH_COOKIE_PATH_PREFIX` changed, or the refresh cookie never reaches the refresh call. +- 0018's proxy consequences still hold: API traffic passes through the Next.js server (`API_PROXY_TIMEOUT_MS`), and the client IP comes from the edge's `X-Forwarded-For`. diff --git a/docs/decisions/0066-browser-calls-the-api-directly.md b/docs/decisions/0066-browser-calls-the-api-directly.md new file mode 100644 index 0000000..49e3ae0 --- /dev/null +++ b/docs/decisions/0066-browser-calls-the-api-directly.md @@ -0,0 +1,22 @@ +# 0066 The browser calls the API directly + +Status: Accepted · Area: architecture · Date: 2026-10-16 · Decided by: user · Supersedes: 0065 + +## Context +Each app's `next.config.ts` rewrote `NEXT_PUBLIC_CLIENT_END_POINT` (`/api`) to `INTERNAL_END_POINT`, so all browser API traffic, uploads included, passed through the Next.js server (0018, 0065). The user removed the rewrite. + +## Decision +- Every app's env keeps `INTERNAL_END_POINT` (server only) and `NEXT_PUBLIC_CLIENT_END_POINT` (public), with the same names in bull, bear and wall-street-plaza. Both are origins with no path. +- `NEXT_PUBLIC_CLIENT_END_POINT` is the API's public origin (the gateway, or admin-api in the admin app). The client bootstrap's HTTP client calls it directly with `credentials: 'include'`, and the platform's `apiBaseUrl` (media and upload URLs) uses it. +- `INTERNAL_END_POINT` is the API's origin from inside the deployment network. The server bootstrap's HTTP client calls it and sends no session cookies. +- No `rewrites()` and no proxy settings in `next.config.ts`. + +## Alternatives +- The Next.js rewrite (0065): removed by the user. +- The app's nginx proxying `/api` to the API: not chosen; `next dev` has no nginx. + +## Consequences +- Back end: CORS must allow each app's origin with credentials (`CORS_ORIGINS`), and the refresh cookie path must drop the `/api` prefix (`AUTH_COOKIE_PATH_PREFIX`), or the session never refreshes. +- Session cookies belong to the API host. The API and the apps must stay on one site (for example `api.example.com` and `example.com`), so `SameSite=Lax` cookies reach the API and its media. +- Browser calls pay a CORS preflight. Upload limits and timeouts are the API's own, not Next.js's. +- The client IP reaches the API without an extra proxy hop. diff --git a/docs/decisions/0067-no-per-app-nginx.md b/docs/decisions/0067-no-per-app-nginx.md new file mode 100644 index 0000000..9bdc85a --- /dev/null +++ b/docs/decisions/0067-no-per-app-nginx.md @@ -0,0 +1,19 @@ +# 0067 No nginx per app + +Status: Accepted · Area: architecture · Date: 2026-10-16 · Decided by: user + +## Context +Each app had its own `apps//nginx.conf` and `-nginx` container in front of its release, so `tools/deploy.sh` could swap releases with no refused request. The user removed it. + +## Decision +- No `nginx.conf` in this repo. Each app's container publishes `HTTP_PORT` on the host itself (3000 inside the container). +- `tools/deploy.sh ` checks the new release's `/healthz` in a container with no published port, then stops the old release and starts the new one on `HTTP_PORT`. A failed check leaves the old release serving; a failed start brings the old one back. +- The edge that routes phones to bull and desktops to bear (0001) points at each app's `HTTP_PORT`. + +## Alternatives +- One nginx per app, reloaded onto the new release: no refused requests during a swap, but one more container and config per app. Removed by the user. + +## Consequences +- Each deploy refuses connections for the old release's shutdown (in-flight requests finish, 30 s at most) plus the new one's start, about half a second when idle. +- `/healthz` answers on `HTTP_PORT`; the edge should hide it from visitors. +- The edge must set `Vary: User-Agent` (0001) and must not buffer streamed pages (the apps send `X-Accel-Buffering: no`). diff --git a/docs/decisions/0068-keep-the-previous-release-for-rollback.md b/docs/decisions/0068-keep-the-previous-release-for-rollback.md new file mode 100644 index 0000000..dd3dcfb --- /dev/null +++ b/docs/decisions/0068-keep-the-previous-release-for-rollback.md @@ -0,0 +1,20 @@ +# 0068 Keep the previous release for rollback + +Status: Accepted · Area: architecture · Date: 2026-10-16 · Decided by: user + +## Context +`tools/deploy.sh` (0067) swapped two fixed containers, `-blue` and `-green`, and removed the old release, so going back meant a full rebuild of an earlier commit. The user asked for a rollback beside the deploy. + +## Decision +- Name each deploy's container `-`, with its env file in `.deploy///`. +- After a swap, keep the old release as a stopped container with its env folder; remove every older one. +- `bash tools/rollback.sh ` stops the serving container and starts the previous one, checked against `/healthz`; a failing previous release leaves the serving one in place. Running it again rolls forward. +- Deploy and rollback of one app share `.deploy//.lock`. + +## Alternatives +- Rebuild an earlier commit with `tools/deploy.sh`: still works for older releases, but takes a build, and the env may have changed since. +- Keep more than one previous release: more disk and more env folders with secrets, for a case a checkout and deploy already covers. + +## Consequences +- A rollback takes seconds and builds nothing; the previous release keeps the port it was deployed with. +- Containers from the blue/green script (`-blue`, `-green`) are invisible to both scripts: remove them, and `.deploy//blue` and `green`, before the first deploy with this one. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 4401b07..9d6664c 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -12,7 +12,6 @@ - 0001 Share one platform, `platforms/market`, between `apps/bull` and `apps/bear`; tag all three `scope:market`. - 0012 Wrap each app's `next.config` in island's `withIconSprite` and `withFontCopy`; they write `symbol-defs.svg` and the fonts into `public/` unhashed, served immutable; link the sprite as `?v=`. - 0013 Render every `(auth)` page's steps only in the browser behind `GuestGuard`: the server sends the frame, a same-size skeleton and `noindex`; flow state stays in memory, never in the URL or storage. -- 0018 Call the API from the browser only on the app's own origin under `/api`, rewritten by `next.config.ts` to `API_INTERNAL_ORIGIN`; media URLs use the same path, and the server render calls the gateway directly. - 0026 Prerender the landing (`/`) with `force-static` and `revalidate = 600`; every other route keeps `force-dynamic` in its route group's layout, never the root's. - 0027 Serve خانه at `/feed` and the landing at `/`; send a signed-in visitor of `/` to `homeRoute` in the browser with `LandingRedirect`, never in a proxy. - 0051 Serve `/_next/static/` JS and CSS cache first in the service worker; `strategy` (default stale-while-revalidate) applies to fonts and the sprite only. @@ -24,8 +23,11 @@ - 0058 Opening notifications records "seen" and clears the bell; a row stays unread until tapped; creators filter one list by «همه · پیش‌بینی‌ها · مالی · حساب». - 0059 Checkout and the channel save `?code=` into the per-creator checkout draft on arrival; checkout then strips it from the URL. - 0060 Composers send a creator who can't publish to their own channel with the locked dialog; every publish carries a stable `Idempotency-Key`. -- 0061 Build the admin panel as `apps/wall-street-plaza` with `platforms/garden-roof`, tagged `scope:admin`; it calls only the back end's `admin-api`, through its own `/api` rewrite. +- 0061 Build the admin panel as `apps/wall-street-plaza` with `platforms/garden-roof`, tagged `scope:admin`; it calls only the back end's `admin-api`. - 0064 Serve a channel at `/channels/username`, built only through `ROUTES`; both apps 308-redirect `/@username/…` there, and no other code reads «@» in a path. +- 0066 Give every app `INTERNAL_END_POINT` (server calls) and `NEXT_PUBLIC_CLIENT_END_POINT` (the API's public origin, called directly by the browser with credentials), both set in the bootstraps; no `next.config.ts` rewrite. +- 0067 Run each app as one container publishing `HTTP_PORT`, with no per-app nginx; `tools/deploy.sh` checks the new release's `/healthz` off to the side, then replaces the old release. +- 0068 Keep the previous release as a stopped `-` container with its env folder; `tools/rollback.sh ` starts it in place of the serving one. ## Proposed diff --git a/platforms/garden-roof/src/env/types.ts b/platforms/garden-roof/src/env/types.ts index fea0e36..c34582b 100644 --- a/platforms/garden-roof/src/env/types.ts +++ b/platforms/garden-roof/src/env/types.ts @@ -1,8 +1,8 @@ /** The platform's own settings, named for what they are, not for the variables behind them. */ export type GardenRoofEnv = { /** - * Where the browser loads the admin API from: a path on this site (`/api`) that the app proxies - * to `admin-api` (0061). For what the browser loads itself, such as ID card images. + * Where the browser loads the admin API from: `admin-api`'s public origin (0061, 0066). For what + * the browser loads itself, such as ID card images. */ apiBaseUrl: string; }; diff --git a/platforms/garden-roof/src/features/analysts/repositories/analysts/types.ts b/platforms/garden-roof/src/features/analysts/repositories/analysts/types.ts index 0b16ea3..630da12 100644 --- a/platforms/garden-roof/src/features/analysts/repositories/analysts/types.ts +++ b/platforms/garden-roof/src/features/analysts/repositories/analysts/types.ts @@ -32,7 +32,7 @@ export type AnalystListItemPayload = { username: string; /** E.164; '' when the account can't be read. */ phone: string; - /** Loadable through this site's API proxy. */ + /** Loadable from admin-api's public origin. */ avatarUrl: string | null; verificationStatus: VerificationStatus; accountStatus: AccountStatus; diff --git a/platforms/garden-roof/src/features/health/repositories/beta-health/types.ts b/platforms/garden-roof/src/features/health/repositories/beta-health/types.ts index c05f42b..24f09f1 100644 --- a/platforms/garden-roof/src/features/health/repositories/beta-health/types.ts +++ b/platforms/garden-roof/src/features/health/repositories/beta-health/types.ts @@ -93,7 +93,7 @@ export type BetaAnalystPayload = { /** First and last name, or the username when the account has neither. */ fullName: string; username: string; - /** Loadable through the panel's API proxy (`/api/uploads/…`). */ + /** Loadable from admin-api's public origin (`…/uploads/…`). */ avatarUrl: string | null; isActive: boolean; inactiveReason: BetaInactiveReason | null; diff --git a/platforms/garden-roof/src/features/payouts/repositories/payouts/mappers.ts b/platforms/garden-roof/src/features/payouts/repositories/payouts/mappers.ts index feb369a..a3bb5f8 100644 --- a/platforms/garden-roof/src/features/payouts/repositories/payouts/mappers.ts +++ b/platforms/garden-roof/src/features/payouts/repositories/payouts/mappers.ts @@ -133,7 +133,7 @@ export function toPayoutDetailPayload( ): PayoutDetailPayload { return { ...toPayoutListItemPayload(dto), - // admin-api's route (`/v1/admin/payouts/:id/receipt`), through this site's API proxy. + // admin-api's route (`/v1/admin/payouts/:id/receipt`), on admin-api's public origin. receiptUrl: toApiUrl(dto.receiptUrl), cancelReason: dto.cancelReason, lines: dto.lines.map(toLedgerLinePayload), diff --git a/platforms/garden-roof/src/features/verification/repositories/verifications/types.ts b/platforms/garden-roof/src/features/verification/repositories/verifications/types.ts index 944c9a3..cdef4b7 100644 --- a/platforms/garden-roof/src/features/verification/repositories/verifications/types.ts +++ b/platforms/garden-roof/src/features/verification/repositories/verifications/types.ts @@ -67,7 +67,7 @@ export type VerificationDetailPayload = { submittedAt: string; status: VerificationStatus; accountStatus: AccountStatus; - /** The card's sides as the browser loads them (through the panel's `/api` proxy). */ + /** The card's sides as the browser loads them (from admin-api's public origin). */ idImages: { front: string; back: string }; rejectionReason: string | null; pastSubmissions: { diff --git a/platforms/garden-roof/src/shared/utils/api-url.ts b/platforms/garden-roof/src/shared/utils/api-url.ts index cf1bcde..81aa7aa 100644 --- a/platforms/garden-roof/src/shared/utils/api-url.ts +++ b/platforms/garden-roof/src/shared/utils/api-url.ts @@ -21,8 +21,8 @@ function legacyUploadPath(address: string): string | null { /** * A path the admin API returns (`/v1/admin/verifications/…/id-images/front`, `/uploads/avatars/…`) → the URL the browser - * loads it from, through this site's API proxy (0061), so private files get the session cookie: - * `/api/v1/admin/…`. Other absolute addresses (another site's, a CDN's) pass through, as does one + * loads it from, admin-api's public origin (0061, 0066), so private files get the session cookie: + * `https://admin-api.example.com/v1/admin/…`. Other absolute addresses (another site's, a CDN's) pass through, as does one * that isn't a valid URL; empty stays `null`. Reads env inside the call, so bootstrap has always * run. */ diff --git a/platforms/market/src/env/types.ts b/platforms/market/src/env/types.ts index 1402e97..e510b42 100644 --- a/platforms/market/src/env/types.ts +++ b/platforms/market/src/env/types.ts @@ -1,9 +1,9 @@ /** The platform's own settings, named for what they are, not for the variables behind them. */ export type MarketEnv = { /** - * Where the browser loads the API from: a path on this site (`/api`) that the app proxies to the - * gateway (0018). For what the browser loads itself: post media, avatars and uploads (`/files/*` - * sits outside `/v1`). A relative URL, so the server render writes the same address. + * Where the browser loads the API from: the gateway's public origin (0066). For what the browser + * loads itself: post media, avatars and uploads (`/files/*` sits outside `/v1`). The server + * render writes the same address. */ apiBaseUrl: string; /** Support chat handles and hours: config values, never hard-coded in a component. */ diff --git a/platforms/market/src/features/discovery/repositories/discovery/types.ts b/platforms/market/src/features/discovery/repositories/discovery/types.ts index 70de3cc..1bce6d3 100644 --- a/platforms/market/src/features/discovery/repositories/discovery/types.ts +++ b/platforms/market/src/features/discovery/repositories/discovery/types.ts @@ -8,7 +8,7 @@ export type CreatorSummaryPayload = { /** Without «@». */ username: string; displayName: string | null; - /** Absolute, through the API proxy; `null` without a photo. */ + /** Absolute, on the API's public origin; `null` without a photo. */ avatarUrl: string | null; verified: boolean; markets: Market[]; diff --git a/platforms/market/src/features/feed/repositories/feed/types.ts b/platforms/market/src/features/feed/repositories/feed/types.ts index c4a81c5..2c16db7 100644 --- a/platforms/market/src/features/feed/repositories/feed/types.ts +++ b/platforms/market/src/features/feed/repositories/feed/types.ts @@ -22,7 +22,7 @@ export type FeedCreatorPayload = { username: string; /** Shown as the name with @username beside it (R15); `null` shows @username alone. */ displayName: string | null; - /** Absolute, through the API proxy; `null` without a photo. */ + /** Absolute, on the API's public origin; `null` without a photo. */ avatarUrl: string | null; verified: boolean; /** Always `false` on the feed: a suspended creator's posts are left out. */ diff --git a/platforms/market/src/features/finance/repositories/earnings/types.ts b/platforms/market/src/features/finance/repositories/earnings/types.ts index 0bae72f..1db3a6f 100644 --- a/platforms/market/src/features/finance/repositories/earnings/types.ts +++ b/platforms/market/src/features/finance/repositories/earnings/types.ts @@ -53,7 +53,7 @@ type LedgerItemBasePayload = { occurredAt: string; }; -/** Where a payout's receipt opens and downloads, through this site's API proxy. */ +/** Where a payout's receipt opens and downloads, on the API's public origin. */ export type PayoutReceiptPayload = { url: string; downloadUrl: string; diff --git a/platforms/market/src/features/follow/repositories/follow/types.ts b/platforms/market/src/features/follow/repositories/follow/types.ts index c46acb2..0d6a9d2 100644 --- a/platforms/market/src/features/follow/repositories/follow/types.ts +++ b/platforms/market/src/features/follow/repositories/follow/types.ts @@ -46,7 +46,7 @@ export type FollowedCreatorPayload = { username: string; /** Shown as the name with @username beside it (R15); `null` shows @username alone. */ displayName: string | null; - /** Absolute, through the API proxy; `null` without a photo. */ + /** Absolute, on the API's public origin; `null` without a photo. */ avatarUrl: string | null; verified: boolean; /** The channel is blacked out: the row is dimmed and opens nothing. */ diff --git a/platforms/market/src/features/post/http.ts b/platforms/market/src/features/post/http.ts index b2cd9f7..d8b4f70 100644 --- a/platforms/market/src/features/post/http.ts +++ b/platforms/market/src/features/post/http.ts @@ -4,7 +4,7 @@ import { getEnv } from '../../env'; export const postHttp = http.extend({}); -/** `/files/*` sits outside `/v1`: straight under the API's base (`/api/files/…`). Browser only. */ +/** `/files/*` sits outside `/v1`: straight under the API's base (`https://api.example.com/files/…`). Browser only. */ export const postFilesHttp = http.extend({ baseUrl: () => getEnv().apiBaseUrl, }); diff --git a/platforms/market/src/shared/utils/api-url.ts b/platforms/market/src/shared/utils/api-url.ts index 41bff93..1bda7ae 100644 --- a/platforms/market/src/shared/utils/api-url.ts +++ b/platforms/market/src/shared/utils/api-url.ts @@ -21,8 +21,8 @@ function legacyUploadPath(address: string): string | null { /** * A path the API returns (`/v1/posts/…/media/…`, `/files/…`, `/uploads/…`) → the URL the browser - * loads it from, through this site's API proxy (0018), so private media gets the session cookie: - * `/api/v1/posts/…`. Other absolute addresses (another site's, a CDN's) pass through, as does one + * loads it from, the gateway's public origin (0066), so private media gets the session cookie: + * `https://api.example.com/v1/posts/…`. Other absolute addresses (another site's, a CDN's) pass through, as does one * that isn't a valid URL; empty stays `null`. Reads env inside the call, so bootstrap has always * run. */ diff --git a/tools/deploy.sh b/tools/deploy.sh new file mode 100755 index 0000000..decf6df --- /dev/null +++ b/tools/deploy.sh @@ -0,0 +1,118 @@ +#!/usr/bin/env bash +# Deploys one app on this host: builds its image with apps//.env.production, checks the new release's +# health check (/healthz) in a container off to the side, then swaps the containers: stops the old release +# and starts the new one on HTTP_PORT. The old release stays as a stopped container, the one to roll back +# to; older ones are removed. A failed build or health check leaves the old release serving. The swap +# refuses connections for a few seconds: the old release finishes its in-flight requests (30 s at most), +# then the new one starts. Whatever sits in front (the edge that routes between bull and bear, 0001; this +# repo sets none up, 0067) points at HTTP_PORT. +# +# bash tools/deploy.sh [KEY=VALUE]... +# HTTP_PORT=7001 bash tools/deploy.sh bear +# bash tools/deploy.sh bull NEXT_PUBLIC_SERVICE_WORKER_ENABLED=false +# +# HTTP_PORT ([host:]port) is where the app answers on this host; inside its container it listens on 3000. +# Default: the port the serving release publishes, or 8080 on the first deploy. +# +# apps//.env.production lives on this host only (git keeps .env.sample) and holds every value, secrets +# included. A KEY=VALUE argument overrides the file's value for this deploy, at build time and at runtime. +# +# Each deploy's container is -, such as bull-20261016143005: the one that +# serves and the previous one, stopped, which tools/rollback.sh starts in its place. +# State in .deploy//, ignored by git and Docker, and readable by this user only: one folder per +# container, named after it, holds its .env.production (the app's file plus the overrides), mounted into it. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +app=${1:?Usage: tools/deploy.sh [KEY=VALUE]...} +shift +[ -f "apps/$app/next.config.ts" ] || { echo "apps/$app/next.config.ts is missing" >&2; exit 1; } +[ -f "apps/$app/.env.production" ] \ + || { echo "apps/$app/.env.production is missing: copy apps/$app/.env.sample and fill it in" >&2; exit 1; } +for override in "$@"; do + [[ $override =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || { echo "Overrides are KEY=VALUE, got: $override" >&2; exit 1; } +done +state="$PWD/.deploy/$app" +mkdir -p "$state" +chmod 700 .deploy +exec 9>"$state/.lock" +flock --nonblock 9 || { echo "A deploy or rollback of $app is running" >&2; exit 1; } + +# 1. The release that serves now, the new one's name, and the port. The port is checked before the build, +# unless the serving release already holds it. +containers() { docker ps "$@" --filter "name=^$app-[0-9]{14}\$" --format '{{.Names}}'; } +current=$(containers | head -n 1) +next=$app-$(date -u +%Y%m%d%H%M%S) +published= +if [ -n "$current" ]; then + published=$(docker port "$current" 3000/tcp 2>/dev/null | head -n 1 || true) + published=${published#0.0.0.0:} + published=${published#\[::\]:} +fi +http_port=${HTTP_PORT:-${published:-8080}} +port_host=127.0.0.1 +[[ $http_port == *:* ]] && port_host=${http_port%:*} +if [ "$http_port" != "$published" ] && (exec 3<>"/dev/tcp/$port_host/${http_port##*:}") 2>/dev/null; then + echo "Port $http_port is taken; pass a free one: HTTP_PORT=8081 bash tools/deploy.sh $app" >&2 + exit 1 +fi + +# 2. The release's env, in its own folder: the app's file, then the overrides; for a repeated key, the last +# line wins. The container's node user reads it, so it's 644 inside .deploy/, which only this user can +# open. Until the swap, any failure removes the new release and its folder. +mkdir -p "$state/$next" +{ cat "apps/$app/.env.production"; echo; printf '%s\n' "$@"; } > "$state/$next/.env.production" +chmod 644 "$state/$next/.env.production" +trap 'docker rm --force "$next" >/dev/null 2>&1 || true; rm -rf "${state:?}/$next"' EXIT + +# 3. Build. The commit names the release and becomes NEXT_DEPLOYMENT_ID; uncommitted changes get their own. +release=$(git rev-parse --short=12 HEAD) +git diff --quiet HEAD || release="$release-dirty-$(date +%s)" +docker build --build-context appenv="$state/$next" \ + --build-arg APP="$app" --build-arg NEXT_DEPLOYMENT_ID="$release" --tag "$app:$release" . + +start_next() { + docker rm --force "$next" >/dev/null 2>&1 || true + docker run --detach --name "$next" --restart unless-stopped \ + --cap-drop ALL --security-opt no-new-privileges --stop-timeout 30 \ + --volume "$state/$next/.env.production:/app/apps/$app/.env.production:ro" "$@" "$app:$release" >/dev/null +} +# Docker turns the image's HEALTHCHECK unhealthy when /healthz keeps failing. +wait_healthy() { + local status + while status=$(docker inspect --format '{{.State.Status}} {{.State.Health.Status}}' "$next") \ + && [ "$status" = 'running starting' ]; do + sleep 2 + done + [ "$status" = 'running healthy' ] && return 0 + docker logs --tail 50 "$next" >&2 + echo "$next ($app:$release) is $status" >&2 + return 1 +} + +# 4. Check the new release off to the side, with no published port, while the old one keeps serving. +echo "Checking $app:$release against /healthz" +start_next +wait_healthy || { echo "${current:-No release} keeps serving" >&2; exit 1; } +docker rm --force "$next" >/dev/null + +# 5. Swap. Stopping the old release frees the port; SIGTERM lets Next.js finish what it's serving, for up +# to 30 s (--stop-timeout). If the new release fails now, the old one starts again. +trap 'docker rm --force "$next" >/dev/null 2>&1 || true; rm -rf "${state:?}/$next" + if [ -n "$current" ]; then docker start "$current" >/dev/null && echo "$current serves again" >&2; fi' EXIT +if [ -n "$current" ]; then docker stop "$current" >/dev/null; fi +start_next --publish "$http_port:3000" +wait_healthy +trap - EXIT + +# 6. Keep one previous release: the old one, stopped, with its env folder. Remove every older container and +# folder, and keep the app's three newest images (Docker never removes an image a container uses). +for old in $(containers --all); do + [ "$old" = "$next" ] || [ "$old" = "$current" ] || docker rm --force "$old" >/dev/null +done +for dir in "$state"/*/; do + dir=${dir%/} + [ "${dir##*/}" = "$next" ] || [ "${dir##*/}" = "$current" ] || rm -rf "$dir" +done +docker image ls "$app" --format '{{.Repository}}:{{.Tag}}' | tail -n +4 | xargs --no-run-if-empty docker image rm >/dev/null 2>&1 || true +echo "$app $release serves at $(docker port "$next" 3000/tcp | head -n 1) as $next${current:+; $current is stopped, kept for a rollback}" diff --git a/tools/rollback.sh b/tools/rollback.sh new file mode 100755 index 0000000..1ce76c3 --- /dev/null +++ b/tools/rollback.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Rolls one app back to its previous release: stops the container that serves and starts the previous one, +# which tools/deploy.sh keeps stopped with its own image and env. The container that served stays stopped as +# the new previous one, so running this again rolls forward. If the previous release fails its health check +# (/healthz), the one that served starts again. The port refuses connections for a few seconds, as in a +# deploy, and the previous release answers on the port it was deployed with. +# +# bash tools/rollback.sh +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +app=${1:?Usage: tools/rollback.sh } +state="$PWD/.deploy/$app" +[ -d "$state" ] || { echo "$app was never deployed on this host" >&2; exit 1; } +exec 9>"$state/.lock" +flock --nonblock 9 || { echo "A deploy or rollback of $app is running" >&2; exit 1; } + +# The container that serves, and the previous one: tools/deploy.sh keeps one, stopped. +containers() { docker ps "$@" --filter "name=^$app-[0-9]{14}\$" --format '{{.Names}}'; } +current=$(containers | head -n 1) +[ -n "$current" ] || { echo "No container of $app serves; deploy it, or start one with docker start" >&2; exit 1; } +previous=$(containers --all | grep -vx "$current" | sort | tail -n 1 || true) +[ -n "$previous" ] || { echo "$app has no previous release to roll back to" >&2; exit 1; } + +# Swap. SIGTERM lets Next.js finish what it's serving, for up to 30 s (--stop-timeout). If the previous +# release fails, the one that served starts again. +trap 'docker stop "$previous" >/dev/null 2>&1 || true; docker start "$current" >/dev/null && echo "$current serves again" >&2' EXIT +docker stop "$current" >/dev/null +docker start "$previous" >/dev/null +# Docker turns the image's HEALTHCHECK unhealthy when /healthz keeps failing. +while status=$(docker inspect --format '{{.State.Status}} {{.State.Health.Status}}' "$previous") \ + && [ "$status" = 'running starting' ]; do + sleep 2 +done +if [ "$status" != 'running healthy' ]; then + docker logs --tail 50 "$previous" >&2 + echo "$previous is $status" >&2 + exit 1 +fi +trap - EXIT +echo "$app rolled back: $previous serves at $(docker port "$previous" 3000/tcp | head -n 1); $current is stopped, kept to roll forward"