@hadoku/service-kernel 0.1.187 → 0.1.188

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.
@@ -1,5 +1,6 @@
1
1
  import type { NextFunction, Request, Response } from 'express';
2
2
  import { type Report } from '../telemetry/telemetry.js';
3
+ import { type HostPressure } from './host-pressure.js';
3
4
  export declare const CAPACITY_WINDOW_MS: number;
4
5
  export declare const SAMPLE_MS = 15000;
5
6
  export type Gauges = Record<string, () => number>;
@@ -17,6 +18,8 @@ export interface CapacityDeps {
17
18
  uncountedPath?: (path: string) => boolean;
18
19
  /** The capacity event's field for `uncountedPath`'s count. Default: `'uncounted'`. */
19
20
  uncountedField?: string;
21
+ /** The host's pressure, read each sample (`host-pressure.ts`). Default: not read. */
22
+ pressure?: () => HostPressure;
20
23
  }
21
24
  export interface CapacitySampler {
22
25
  /** Express middleware: counts each finished request and its duration. */
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import { monitorEventLoopDelay } from 'node:perf_hooks';
18
18
  import { report as defaultReport } from "../telemetry/telemetry.js";
19
+ import { PressureWindow } from "./host-pressure.js";
19
20
  export const CAPACITY_WINDOW_MS = 5 * 60_000;
20
21
  export const SAMPLE_MS = 15_000;
21
22
  const MB = 1024 * 1024;
@@ -35,6 +36,7 @@ export function capacitySampler(deps) {
35
36
  let errors = 0;
36
37
  /** Requests matching `uncountedPath`: counted, never timed. */
37
38
  let uncounted = 0;
39
+ const pressure = new PressureWindow();
38
40
  const sample = () => {
39
41
  samples += 1;
40
42
  const m = memory();
@@ -50,6 +52,13 @@ export function capacitySampler(deps) {
50
52
  for (const [k, v] of Object.entries(reading))
51
53
  peaks[k] = Math.max(peaks[k] ?? v, v);
52
54
  last = reading;
55
+ if (deps.pressure !== undefined) {
56
+ const p = deps.pressure();
57
+ const from = pressure.add(p);
58
+ // Quiet on purpose: a telemetry event to read beside a stall, never a page, until its false-positive rate is known.
59
+ if (from !== null)
60
+ report('host-pressure', { level: p.level, from, why: p.why, since: p.since, reasons: p.reasons, psi: p.psi }, 'info');
61
+ }
53
62
  };
54
63
  const flush = () => {
55
64
  const start = windowStart;
@@ -73,6 +82,9 @@ export function capacitySampler(deps) {
73
82
  loopMaxMs: Math.round(loop.max / 1e6),
74
83
  };
75
84
  context[uncountedField] = uncounted;
85
+ const hostPressure = pressure.take();
86
+ if (hostPressure !== null)
87
+ context.hostPressure = hostPressure;
76
88
  Object.assign(context, deps.counts?.());
77
89
  report('capacity', context);
78
90
  peaks = {};
@@ -0,0 +1,38 @@
1
+ /** fleet-manager's line: a file whose `at` is older than this means it could not look. */
2
+ export declare const PRESSURE_STALE_MS = 60000;
3
+ export type PressureLevel = 'ok' | 'warn' | 'unknown';
4
+ export interface HostPressure {
5
+ level: PressureLevel;
6
+ /** Why the level is `unknown`; null otherwise. */
7
+ why: string | null;
8
+ since: string | null;
9
+ reasons: string[];
10
+ /** The PSI each of fleet-manager's lines is drawn on, as it last sampled them; null when unread. */
11
+ psi: {
12
+ hostIoFull: number;
13
+ hostMemSome: number;
14
+ prodIoSome: number;
15
+ prodMemSome: number;
16
+ } | null;
17
+ }
18
+ /** Where fleet-manager writes it for this user (`/run/user/<uid>/fleet`); `HADOKU_HOST_PRESSURE_FILE` overrides. */
19
+ export declare function hostPressureFile(env?: NodeJS.ProcessEnv): string;
20
+ export declare function readHostPressure(file: string, now: number): HostPressure;
21
+ /** One capacity window's readings: the worst level, how many samples each, and every reason seen. */
22
+ export declare class PressureWindow {
23
+ private counts;
24
+ private reasons;
25
+ private last;
26
+ /** A reading. Returns the level it changed from, or null when it did not change (the first reading changes from `ok`). */
27
+ add(p: HostPressure): PressureLevel | null;
28
+ /** The capacity event's `hostPressure`, then a fresh window; null when nothing was read. */
29
+ take(): {
30
+ worst: PressureLevel;
31
+ ok: number;
32
+ warn: number;
33
+ unknown: number;
34
+ reasons: string[];
35
+ now: PressureLevel;
36
+ why: string | null;
37
+ } | null;
38
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The host's own pressure, as fleet-manager reads it (its `src/host-pressure.ts`): every 2 s it
3
+ * samples the host's PSI and the server's cgroup's, and every 30 s and on each change writes
4
+ * `level` (`warn` once a line held for two samples), `reasons` and the sample to
5
+ * `host-pressure.json`. This module reads that file and never samples PSI itself, so there is one
6
+ * judge of "the host is under pressure" on the box.
7
+ *
8
+ * Anything this cannot vouch for is `unknown`, never `ok` nor `warn`: no file, a file older than
9
+ * `PRESSURE_STALE_MS` (its writer stopped), a torn one, or one where fleet-manager says it could not
10
+ * read a pressure source. The coordinator host's stalls (2026-11-27, 2026-11-28) stopped every claw's heartbeat at
11
+ * once; with this beside them in telemetry, a stall is named as the host's.
12
+ */
13
+ import { readFileSync } from 'node:fs';
14
+ /** fleet-manager's line: a file whose `at` is older than this means it could not look. */
15
+ export const PRESSURE_STALE_MS = 60_000;
16
+ /** Where fleet-manager writes it for this user (`/run/user/<uid>/fleet`); `HADOKU_HOST_PRESSURE_FILE` overrides. */
17
+ export function hostPressureFile(env = process.env) {
18
+ return env.HADOKU_HOST_PRESSURE_FILE ?? `/run/user/${process.getuid?.() ?? 0}/fleet/host-pressure.json`;
19
+ }
20
+ const unknown = (why) => ({ level: 'unknown', why, since: null, reasons: [], psi: null });
21
+ export function readHostPressure(file, now) {
22
+ let text;
23
+ try {
24
+ text = readFileSync(file, 'utf8');
25
+ }
26
+ catch {
27
+ return unknown('no file');
28
+ }
29
+ let w;
30
+ try {
31
+ w = JSON.parse(text);
32
+ }
33
+ catch {
34
+ return unknown('unreadable');
35
+ }
36
+ const at = Date.parse(String(w.at));
37
+ if (!Number.isFinite(at))
38
+ return unknown('unreadable');
39
+ if (now - at > PRESSURE_STALE_MS)
40
+ return unknown(`stale: written ${Math.round((now - at) / 1000)} s ago`);
41
+ if (Array.isArray(w.unreadable) && w.unreadable.length > 0)
42
+ return unknown(`fleet-manager could not read ${w.unreadable.map(String).join(', ')}`);
43
+ if (w.level !== 'ok' && w.level !== 'warn')
44
+ return unknown(`level ${String(w.level)}`);
45
+ const n = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
46
+ const s = w.sample;
47
+ return {
48
+ level: w.level,
49
+ why: null,
50
+ since: typeof w.since === 'string' ? w.since : null,
51
+ reasons: Array.isArray(w.reasons) ? w.reasons.map(String) : [],
52
+ psi: s === undefined
53
+ ? null
54
+ : { hostIoFull: n(s.host?.io?.full10), hostMemSome: n(s.host?.mem?.some10), prodIoSome: n(s.prod?.io?.some10), prodMemSome: n(s.prod?.mem?.some10) },
55
+ };
56
+ }
57
+ const RANK = { ok: 0, unknown: 1, warn: 2 };
58
+ /** One capacity window's readings: the worst level, how many samples each, and every reason seen. */
59
+ export class PressureWindow {
60
+ counts = { ok: 0, warn: 0, unknown: 0 };
61
+ reasons = new Set();
62
+ last = null;
63
+ /** A reading. Returns the level it changed from, or null when it did not change (the first reading changes from `ok`). */
64
+ add(p) {
65
+ this.counts[p.level] += 1;
66
+ for (const r of p.reasons)
67
+ this.reasons.add(r);
68
+ const from = this.last?.level ?? 'ok';
69
+ this.last = p;
70
+ return from === p.level ? null : from;
71
+ }
72
+ /** The capacity event's `hostPressure`, then a fresh window; null when nothing was read. */
73
+ take() {
74
+ const read = this.counts.ok + this.counts.warn + this.counts.unknown;
75
+ const last = this.last;
76
+ const out = read === 0 || last === null
77
+ ? null
78
+ : {
79
+ worst: Object.keys(this.counts).filter((l) => this.counts[l] > 0).sort((a, b) => RANK[b] - RANK[a])[0],
80
+ ...this.counts,
81
+ reasons: [...this.reasons],
82
+ now: last.level,
83
+ why: last.why,
84
+ };
85
+ this.counts = { ok: 0, warn: 0, unknown: 0 };
86
+ this.reasons = new Set();
87
+ return out;
88
+ }
89
+ }
@@ -1 +1,2 @@
1
1
  export { CAPACITY_WINDOW_MS, SAMPLE_MS, capacitySampler, type CapacityDeps, type CapacitySampler, type Gauges, } from './capacity.js';
2
+ export { PRESSURE_STALE_MS, hostPressureFile, readHostPressure, type HostPressure, type PressureLevel } from './host-pressure.js';
@@ -1 +1,2 @@
1
1
  export { CAPACITY_WINDOW_MS, SAMPLE_MS, capacitySampler, } from "./capacity.js";
2
+ export { PRESSURE_STALE_MS, hostPressureFile, readHostPressure } from "./host-pressure.js";
@@ -56,7 +56,7 @@ import { createServer } from 'node:http';
56
56
  import express from 'express';
57
57
  import { Server as SocketIOServer } from 'socket.io';
58
58
  import { callerIdOf, tierOf, userIdOf } from "../auth/index.js";
59
- import { capacitySampler } from "../capacity/index.js";
59
+ import { capacitySampler, hostPressureFile, readHostPressure } from "../capacity/index.js";
60
60
  import { createAccountErase, ERASE_PATH, MERGE_PATH } from "../erase/index.js";
61
61
  import { healthResponse, readCommit, serviceIdOf } from "../health/index.js";
62
62
  import { checkBundle, isEmbedEntry, stampOrigin } from "../http/index.js";
@@ -93,9 +93,11 @@ export async function createGameServer({ id, config, state, plugins }) {
93
93
  const io = new SocketIOServer(httpServer, { serveClient: false });
94
94
  const gauges = { sockets: () => io.engine.clientsCount };
95
95
  const countReaders = [];
96
+ const pressureFile = hostPressureFile();
96
97
  const capacity = capacitySampler({
97
98
  gauges,
98
99
  counts: () => Object.assign({}, ...countReaders.map((read) => read())),
100
+ pressure: () => readHostPressure(pressureFile, Date.now()),
99
101
  ...(config.uncounted === undefined ? {} : { uncountedPath: config.uncounted.path, uncountedField: config.uncounted.field }),
100
102
  });
101
103
  const quiet = config.uncounted?.path ?? (() => false);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/service-kernel",
3
- "version": "0.1.187",
4
- "gitHead": "47e77f0d4fa499952cdb2228afc75e7c7b9ffa9d",
3
+ "version": "0.1.188",
4
+ "gitHead": "1a2758d078da3deba59d105b7ee780fda3d8231e",
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, platform-wire and @wolffm/*.",
@@ -56,7 +56,7 @@
56
56
  }
57
57
  },
58
58
  "dependencies": {
59
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.154",
59
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.155",
60
60
  "express": "^5.1.0",
61
61
  "socket.io": "^4.8.3"
62
62
  },