@hadoku/service-kernel 0.1.44 → 0.1.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,61 @@
1
+ /**
2
+ * A minimal game booted for real, in its own process, for `handover.test.ts`: the kernel as a
3
+ * deploy generation sees it, started by a supervisor with a socket and a ready pipe. `GEN` names
4
+ * it in every answer, so a test can tell which generation served a request.
5
+ */
6
+ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
7
+ import { tmpdir } from 'node:os';
8
+ import { join } from 'node:path';
9
+ import { createEdgeAuth, rankOf, tierOf } from "../auth/index.js";
10
+ import { createGate } from "../http/index.js";
11
+ import { createGameServer } from "./index.js";
12
+ const dir = mkdtempSync(join(tmpdir(), 'kernel-handover-'));
13
+ mkdirSync(join(dir, 'web'));
14
+ writeFileSync(join(dir, 'web/index.html'), '<!doctype html><script src="/fake/assets/a.js"></script>');
15
+ const edgeAuth = createEdgeAuth({
16
+ edgeAuthSecret: () => 'seal',
17
+ allowUnverifiedEdge: () => false,
18
+ devTier: () => 'friend',
19
+ });
20
+ const gate = createGate({
21
+ ...edgeAuth,
22
+ tierOf,
23
+ rankOf,
24
+ reportSealRefused: () => undefined,
25
+ minTier: () => 'friend',
26
+ });
27
+ const gen = process.env.GEN ?? '?';
28
+ const slow = {
29
+ name: 'slow',
30
+ phase: 'routes',
31
+ setup(ctx) {
32
+ // Above the floor, like /health: a request this generation takes and must finish. Inside the
33
+ // shutdown's request grace (300 ms), which is the kernel's promise to an in-flight request.
34
+ ctx.sealed.get('/slow', (_req, res) => {
35
+ console.log(`taken ${gen}`);
36
+ setTimeout(() => res.type('text').send(`slow ${gen}`), 150);
37
+ });
38
+ },
39
+ };
40
+ await createGameServer({
41
+ id: 'fake',
42
+ config: {
43
+ host: '127.0.0.1',
44
+ port: 0,
45
+ log: (entry) => console.log(JSON.stringify({ gen, ...entry })),
46
+ edgeAuth,
47
+ gate,
48
+ basePrefix: '/fake',
49
+ bundle: {
50
+ indexHtml: join(dir, 'web/index.html'),
51
+ webDir: join(dir, 'web'),
52
+ embedEntries: [],
53
+ },
54
+ repoRoot: dir,
55
+ restartEvent: 'fake-restarting',
56
+ firstSeen: { file: join(dir, 'seen.json'), log: () => undefined },
57
+ erase: { deriveParticipantId: (userId) => `fk:${userId}` },
58
+ },
59
+ state: {},
60
+ plugins: [slow],
61
+ });
@@ -1,45 +1,3 @@
1
- /**
2
- * `createGameServer`: the one boot sequence every game's server runs, so a game is its config
3
- * and a list of plugins.
4
- *
5
- * ## What the kernel owns
6
- *
7
- * The express app and its `/api` router, the HTTP server and the socket.io server; edge
8
- * provenance and the tier floor (the app's `EdgeAuth` and `Gate`, `../auth` and `../http`);
9
- * `/health` and the local-only busy probe; the telemetry sink and the capacity sampler; the
10
- * account-erase route and its registry; the origin stamp; `listen`; and SIGTERM/SIGINT with
11
- * the restart notice, the connection grace and the shutdown deadline.
12
- *
13
- * ## The order a request meets
14
- *
15
- * provenance → capacity → access log → /health, /health/busy, the erase route, the sealed routes
16
- * → the tier floor → first-seen → /api (JSON body, then the plugins' routes)
17
- * → the bundle's static files → the plugins' own app routes, in registration order
18
- *
19
- * Everything above the floor is public on purpose; a plugin registers nothing above it except on
20
- * `sealed`, which answers only a request carrying the edge's seal and passes every other one on to
21
- * the floor. The edge seals each request it proxies whatever the caller's tier, so a route there is
22
- * reachable through hadoku.me by anyone the edge itself lets through (a link-preview crawler, say),
23
- * and never by a direct hit on the tunnel.
24
- *
25
- * ## Boot phases
26
- *
27
- * `config → bundle → stores → routes → sockets → listen → warm`, each plugin's `setup` in
28
- * array order within its phase. The kernel checks the bundle at the start of `bundle` and
29
- * installs telemetry at its end, builds first-seen at the end of `config` (so a state-dir move in `config`
30
- * happens before it reads its file), and starts listening between `sockets` and `listen`:
31
- * `listen` and `warm` run once the server answers, `warm` last. The boot clock stamps each phase as it ends, unless the
32
- * config turns that off to keep a game's own names (`stampPhases: false`, `ctx.bootPhase`).
33
- *
34
- * ## Going down
35
- *
36
- * The first SIGTERM or SIGINT logs `shutdown-begin`, emits `shutdown` on the bus, runs every
37
- * plugin's `shutdown` in REVERSE setup order (the last thing built goes first), then tells
38
- * every socket the game's restart event, closes socket.io and the HTTP server, and lets
39
- * in-flight requests finish within `requestGraceMs`. It exits on the close or at
40
- * `deadlineMs`, whichever comes first, logging `shutdown-done` with the fields the plugins'
41
- * shutdowns returned.
42
- */
43
1
  import { type Server } from 'node:http';
44
2
  import { type Express, type Router } from 'express';
45
3
  import { Server as SocketIOServer } from 'socket.io';
@@ -51,6 +9,13 @@ import type { JsonLog } from '../log/index.js';
51
9
  import { type Report } from '../telemetry/index.js';
52
10
  import { type Bus, type EventMap, type KernelEvents } from './bus.js';
53
11
  export declare const PHASES: readonly ["config", "bundle", "stores", "routes", "sockets", "listen", "warm"];
12
+ /** The deploy handover's two descriptors (module header). */
13
+ export interface Handover {
14
+ listenFd: number;
15
+ readyFd: number | null;
16
+ }
17
+ /** The handover the supervisor started this process with, or null when it binds its own port. */
18
+ export declare function handoverFromEnv(env?: NodeJS.ProcessEnv): Handover | null;
54
19
  export type Phase = (typeof PHASES)[number];
55
20
  export interface GameServerConfig {
56
21
  host: string;
@@ -98,6 +63,11 @@ export interface GameServerConfig {
98
63
  requestGraceMs?: number;
99
64
  restartFlushMs?: number;
100
65
  };
66
+ /**
67
+ * A listening socket to serve instead of binding `port`, and the pipe to say so on: the deploy
68
+ * handover (module header). Defaults to `HADOKU_LISTEN_FD` / `HADOKU_READY_FD`; null binds.
69
+ */
70
+ handover?: Handover | null;
101
71
  /** Install SIGTERM/SIGINT handlers (default true). */
102
72
  signals?: boolean;
103
73
  /** Ends the process once shut down; `process.exit` unless a test passes its own. */
@@ -39,7 +39,18 @@
39
39
  * in-flight requests finish within `requestGraceMs`. It exits on the close or at
40
40
  * `deadlineMs`, whichever comes first, logging `shutdown-done` with the fields the plugins'
41
41
  * shutdowns returned.
42
+ *
43
+ * ## A socket handed over
44
+ *
45
+ * In production the PM2 wrapper runs this process under hadoku_site's handover supervisor
46
+ * (`services/pm2/lib/handover.py`, deploy continuity's socket mover), which binds the port once and
47
+ * keeps it open across deploys. Started that way (`HADOKU_LISTEN_FD`), the server listens on the
48
+ * socket it inherited instead of binding `port`, and writes one byte to `HADOKU_READY_FD` once it
49
+ * accepts. Connections made while no generation accepts (this one booting, the last one shutting
50
+ * down) wait in the socket's backlog instead of being refused. `close` closes this process's copy
51
+ * only; the supervisor's stays open. Without the variables it binds `port` as it always has.
42
52
  */
53
+ import { closeSync, writeSync } from 'node:fs';
43
54
  import { createServer } from 'node:http';
44
55
  import express from 'express';
45
56
  import { Server as SocketIOServer } from 'socket.io';
@@ -52,6 +63,17 @@ import { bootClock, busyHandler, closeConnections, sendThenFlush } from "../life
52
63
  import { firstSeen, installTelemetry } from "../telemetry/index.js";
53
64
  import { createBus } from "./bus.js";
54
65
  export const PHASES = ['config', 'bundle', 'stores', 'routes', 'sockets', 'listen', 'warm'];
66
+ /** The handover the supervisor started this process with, or null when it binds its own port. */
67
+ export function handoverFromEnv(env = process.env) {
68
+ const listen = env.HADOKU_LISTEN_FD;
69
+ if (listen === undefined || listen === '')
70
+ return null;
71
+ const fd = Number(listen);
72
+ if (!Number.isInteger(fd) || fd < 0)
73
+ throw new Error(`HADOKU_LISTEN_FD is not a descriptor: ${JSON.stringify(listen)}`);
74
+ const ready = env.HADOKU_READY_FD;
75
+ return { listenFd: fd, readyFd: ready === undefined || ready === '' ? null : Number(ready) };
76
+ }
55
77
  const DEFAULT_SHUTDOWN = { deadlineMs: 1_300, requestGraceMs: 300, restartFlushMs: 500 };
56
78
  export async function createGameServer({ id, config, state, plugins }) {
57
79
  const { log } = config;
@@ -225,13 +247,22 @@ export async function createGameServer({ id, config, state, plugins }) {
225
247
  }
226
248
  // After every socket.io attach: engine.io moves itself to the front of the request listeners.
227
249
  stampOrigin(httpServer, config.origin ?? id);
250
+ const handover = config.handover === undefined ? handoverFromEnv() : config.handover;
228
251
  await new Promise((listening, failed) => {
229
252
  httpServer.once('error', failed);
230
- httpServer.listen(config.port, config.host, () => {
253
+ const done = () => {
231
254
  httpServer.off('error', failed);
232
255
  listening();
233
- });
256
+ };
257
+ if (handover === null)
258
+ httpServer.listen(config.port, config.host, done);
259
+ else
260
+ httpServer.listen({ fd: handover.listenFd }, done);
234
261
  });
262
+ if (handover !== null && handover.readyFd !== null) {
263
+ writeSync(handover.readyFd, 'R');
264
+ closeSync(handover.readyFd);
265
+ }
235
266
  capacity.start();
236
267
  const { port } = httpServer.address();
237
268
  console.log(`[${id}] listening on ${config.host}:${port}`);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/service-kernel",
3
- "version": "0.1.44",
4
- "gitHead": "cff61c64decefe8034fe2c3337997377628bbfb5",
3
+ "version": "0.1.46",
4
+ "gitHead": "169a12a10da47b263ed55a1441cbd01a51d2c95b",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The server parts any game keeps: edge auth and the tier gate, base path and bundle check, health and the busy probe, lifecycle, the JSON logger, the state directory, telemetry and capacity, per-caller limits, the browser relays, the erase registry, and createGameServer, which boots a game from its config and plugins. Knows no game; the app binds its service id, prefix and env names. MIT; imports only node built-ins, express, socket.io and @wolffm/*.",
@@ -56,8 +56,8 @@
56
56
  }
57
57
  },
58
58
  "dependencies": {
59
- "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.97",
60
- "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.97",
59
+ "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.98",
60
+ "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.98",
61
61
  "express": "^5.1.0",
62
62
  "socket.io": "^4.8.3"
63
63
  },