From e3f2a25056ccd600ff107fb7d7b4954566afdf49 Mon Sep 17 00:00:00 2001 From: Ty J Everett Date: Thu, 22 Oct 2026 23:22:38 -0700 Subject: [PATCH 1/2] Drain accepted API requests on shutdown and run Node as PID 1 --- apps/api/Dockerfile | 4 +-- apps/api/package.json | 3 ++- apps/api/src/index.ts | 19 ++++++++++++-- apps/api/src/lifecycle.test.ts | 47 ++++++++++++++++++++++++++++++++++ apps/api/src/lifecycle.ts | 20 +++++++++++++++ 5 files changed, 88 insertions(+), 5 deletions(-) create mode 100644 apps/api/src/lifecycle.test.ts create mode 100644 apps/api/src/lifecycle.ts diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile index 3ec829e..863d5b6 100644 --- a/apps/api/Dockerfile +++ b/apps/api/Dockerfile @@ -5,7 +5,7 @@ WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . -RUN npm run build +RUN npm run build && npm test # ---- runtime stage ---- FROM node:22.23.4-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 @@ -18,4 +18,4 @@ RUN npm ci --omit=dev COPY --from=build /app/dist ./dist EXPOSE 8080 -CMD ["npm","start"] \ No newline at end of file +CMD ["node", "dist/src/index.js"] \ No newline at end of file diff --git a/apps/api/package.json b/apps/api/package.json index 7539b3a..65dc32c 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -5,7 +5,8 @@ "scripts": { "dev": "ts-node --transpile-only src/index.ts", "build": "tsc -p tsconfig.json", - "start": "node dist/src/index.js" + "start": "node dist/src/index.js", + "test": "node --test dist/src/lifecycle.test.js" }, "dependencies": { "@bsv/sdk": "^1.9.31", diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 114befb..df0f8d3 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -3,6 +3,7 @@ import express from 'express' import cors from 'cors' import crypto from 'crypto' import cookieParser from 'cookie-parser' +import { drainHttpServer } from './lifecycle.js' import { HandCashConnect } from '@handcash/handcash-connect' import { PrivateKey } from '@bsv/sdk' @@ -266,8 +267,22 @@ app.post('/api/handcash/pay', async (req, res) => { } }) -app.listen(PORT, () => { +const server = app.listen(PORT, () => { console.log(`metabridge backend listening on http://localhost:${PORT}`) console.log(`FRONTEND_URL=${FRONTEND_URL}`) console.log(`senderIdentityKey=${senderIdentityKey}`) -}) \ No newline at end of file +}) + +let stopping = false +async function shutdown(): Promise { + if (stopping) return + stopping = true + try { + const forced = await drainHttpServer(server) + process.exit(forced ? 1 : 0) + } catch { + process.exit(1) + } +} +process.once('SIGTERM', () => { void shutdown() }) +process.once('SIGINT', () => { void shutdown() }) diff --git a/apps/api/src/lifecycle.test.ts b/apps/api/src/lifecycle.test.ts new file mode 100644 index 0000000..c8d120b --- /dev/null +++ b/apps/api/src/lifecycle.test.ts @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { createServer, get } from 'node:http' +import { once } from 'node:events' +import { drainHttpServer } from './lifecycle.js' + +test('drain completes an accepted HTTP response', async () => { + let accepted!: () => void + const requestAccepted = new Promise(resolve => { accepted = resolve }) + const server = createServer((_req, res) => { + accepted() + setTimeout(() => res.end('completed'), 60) + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + assert.ok(address && typeof address !== 'string') + const response = new Promise((resolve, reject) => { + get(`http://127.0.0.1:${address.port}`, res => { + let body = '' + res.on('data', data => { body += data }) + res.on('end', () => resolve(body)) + res.on('error', reject) + }).on('error', reject) + }) + await requestAccepted + const drain = drainHttpServer(server, 1000) + assert.equal(await response, 'completed') + assert.equal(await drain, false) +}) + +test('drain bounds a stalled request', async () => { + let accepted!: () => void + const requestAccepted = new Promise(resolve => { accepted = resolve }) + const server = createServer(() => { accepted() }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + assert.ok(address && typeof address !== 'string') + const request = get(`http://127.0.0.1:${address.port}`) + request.on('error', () => {}) + await requestAccepted + const started = Date.now() + assert.equal(await drainHttpServer(server, 50), true) + assert.ok(Date.now() - started < 1000) + request.destroy() +}) diff --git a/apps/api/src/lifecycle.ts b/apps/api/src/lifecycle.ts new file mode 100644 index 0000000..9489c51 --- /dev/null +++ b/apps/api/src/lifecycle.ts @@ -0,0 +1,20 @@ +import type { Server } from 'node:http' + +/** Complete accepted requests after the owning rollout withdraws the endpoint. */ +export async function drainHttpServer(server: Server, graceMs = 100_000): Promise { + return await new Promise((resolve, reject) => { + let forced = false + const idleSweep = setInterval(() => server.closeIdleConnections(), 25) + const timeout = setTimeout(() => { + forced = true + server.closeAllConnections() + }, graceMs) + server.close(error => { + clearTimeout(timeout) + clearInterval(idleSweep) + if (error !== undefined) reject(error) + else resolve(forced) + }) + server.closeIdleConnections() + }) +} From 5af392a4e24ebd90d7d4a4b12d4051704146dcfa Mon Sep 17 00:00:00 2001 From: Ty J Everett Date: Thu, 22 Oct 2026 23:22:47 -0700 Subject: [PATCH 2/2] Document API endpoint withdrawal and termination budget --- apps/api/README.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 apps/api/README.md diff --git a/apps/api/README.md b/apps/api/README.md new file mode 100644 index 0000000..e0ca5c2 --- /dev/null +++ b/apps/api/README.md @@ -0,0 +1,9 @@ +# API runtime lifecycle + +The container runs Node directly as PID 1. On SIGTERM or SIGINT, it stops accepting connections and lets accepted HTTP requests finish for up to 100 seconds before forcing remaining sockets closed. + +A Kubernetes deployment must withdraw the endpoint before termination (for example, a 10-second preStop delay) and allow at least 120 seconds of termination grace. Those settings leave time for endpoint propagation, the application drain, and process cleanup. + +When migrating an image without this shutdown handler, qualify the new image in a non-serving pool, switch traffic only after it is ready, and keep the withdrawn old pool alive for the accepted-request drain interval before terminating it. The new handler cannot protect requests already running in an old image. + +`npm run build && npm test` verifies that an accepted response completes during shutdown and that a stalled request reaches the bounded cutoff. These tests do not call a payment provider or send transactions.