Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions apps/api/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -18,4 +18,4 @@ RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist

EXPOSE 8080
CMD ["npm","start"]
CMD ["node", "dist/src/index.js"]
9 changes: 9 additions & 0 deletions apps/api/README.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
19 changes: 17 additions & 2 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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}`)
})
})

let stopping = false
async function shutdown(): Promise<void> {
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() })
47 changes: 47 additions & 0 deletions apps/api/src/lifecycle.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>(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<string>((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<void>(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()
})
20 changes: 20 additions & 0 deletions apps/api/src/lifecycle.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> {
return await new Promise<boolean>((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()
})
}
Loading