@camstack/server 1.2.176 → 1.2.177

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,181 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DEFAULT_NPM_REGISTRY = void 0;
37
+ exports.readInstalledAddonPackages = readInstalledAddonPackages;
38
+ exports.buildAddonUpdateEntries = buildAddonUpdateEntries;
39
+ exports.resolvePublishedVersion = resolvePublishedVersion;
40
+ exports.buildAgentAddonUpdateReport = buildAgentAddonUpdateReport;
41
+ /**
42
+ * Agent-local addon ALIGNMENT report — "is this node behind?", answered
43
+ * WITHOUT the hub.
44
+ *
45
+ * ── Why this is read-only, and the update button is not here ──────────────
46
+ * Updating an addon on an agent is hub-driven and CANNOT be initiated here:
47
+ * the hub packs the version IT resolved and pushes the tarball over
48
+ * `$agent.deploy` (`api/core/cap-providers.ts` `updatePackage`, agent branch).
49
+ * There is no agent→hub trigger for that — the `addons` capability is
50
+ * `mount: 'server-provided'`, i.e. it exists only inside the hub's tRPC
51
+ * router and is never published as a Moleculer cap service, so an agent's
52
+ * broker cannot reach it; and CLAUDE.md forbids minting a Moleculer action
53
+ * for business logic to bridge the gap.
54
+ *
55
+ * Pulling the published tarball locally instead would be a SECOND install
56
+ * channel resolving a DIFFERENT artifact: the hub routinely ships builds via
57
+ * `camstack deploy` that were never published, so a node that self-pulled
58
+ * npm-latest would run bytes the hub never sent and still report itself
59
+ * updated. That is precisely the divergence the hub-push path exists to
60
+ * prevent.
61
+ *
62
+ * So this module answers the question the isolated operator actually has —
63
+ * *which of my addons are behind the published release?* — and the UI names
64
+ * where the action lives. A read that cannot mislead beats a button that
65
+ * cannot work.
66
+ */
67
+ const fs = __importStar(require("node:fs"));
68
+ const path = __importStar(require("node:path"));
69
+ const index_js_1 = require("../server-root/index.js");
70
+ const addon_scan_js_1 = require("./addon-scan.js");
71
+ /** Default public registry, matching `AddonInstaller.downloadNpmTarball`. */
72
+ exports.DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
73
+ /** Read `<dir>/package.json`'s `name` + `version`, tolerating a broken file. */
74
+ function readPackageIdentity(dir) {
75
+ try {
76
+ const parsed = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));
77
+ if (typeof parsed.name !== 'string' || parsed.name.length === 0)
78
+ return null;
79
+ return {
80
+ packageName: parsed.name,
81
+ installedVersion: typeof parsed.version === 'string' ? parsed.version : null,
82
+ };
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ }
88
+ /**
89
+ * Every addon package installed under `addonsDir`, keyed by its npm PACKAGE
90
+ * name (not the addon declaration id — the two differ for scoped packages and
91
+ * only the package name can be looked up in a registry).
92
+ *
93
+ * `@camstack/system` is deliberately INCLUDED: on an agent the addon-root copy
94
+ * is the only copy of the builtin infra (D87), so it is exactly the package an
95
+ * operator needs to see the version of when a node is misaligned.
96
+ */
97
+ function readInstalledAddonPackages(addonsDir) {
98
+ const found = [];
99
+ for (const dir of (0, addon_scan_js_1.resolveAddonPackageDirs)(addonsDir)) {
100
+ const identity = readPackageIdentity(dir);
101
+ if (identity !== null)
102
+ found.push(identity);
103
+ }
104
+ return found.sort((a, b) => a.packageName.localeCompare(b.packageName));
105
+ }
106
+ /**
107
+ * Pure join of the on-disk roster with the published versions.
108
+ *
109
+ * `updateAvailable` requires BOTH versions to be known and the published one
110
+ * to be strictly newer. An unknown published version is never "up to date"
111
+ * and never "behind" — it is unknown, and carries its error into the row.
112
+ */
113
+ function buildAddonUpdateEntries(installed, published) {
114
+ return installed.map((pkg) => {
115
+ const latest = published.get(pkg.packageName);
116
+ const latestVersion = latest?.latestVersion ?? null;
117
+ const updateAvailable = latestVersion !== null &&
118
+ pkg.installedVersion !== null &&
119
+ (0, index_js_1.compareSemver)(latestVersion, pkg.installedVersion) > 0;
120
+ return {
121
+ packageName: pkg.packageName,
122
+ installedVersion: pkg.installedVersion,
123
+ latestVersion,
124
+ updateAvailable,
125
+ error: latest?.error ?? null,
126
+ };
127
+ });
128
+ }
129
+ /**
130
+ * Resolve `dist-tags.latest` for one package over the registry's HTTPS API —
131
+ * the same door `AddonInstaller.downloadNpmTarball` uses, so a host with no
132
+ * `npm` on PATH (a packaged desktop agent) still gets an answer.
133
+ *
134
+ * Never throws: a failure becomes `{ latestVersion: null, error }` so one
135
+ * unreachable package cannot blank the whole report.
136
+ */
137
+ async function resolvePublishedVersion(packageName, registryUrl, fetchFn) {
138
+ const base = registryUrl.replace(/\/+$/, '');
139
+ const url = `${base}/${encodeURIComponent(packageName).replace(/^%40/, '@')}`;
140
+ try {
141
+ const res = await fetchFn(url);
142
+ if (!res.ok)
143
+ return { latestVersion: null, error: `registry GET → ${res.status}` };
144
+ const body = (await res.json());
145
+ const latest = body['dist-tags']?.['latest'];
146
+ if (typeof latest !== 'string' || latest.length === 0) {
147
+ return { latestVersion: null, error: 'registry returned no dist-tags.latest' };
148
+ }
149
+ return { latestVersion: latest, error: null };
150
+ }
151
+ catch (err) {
152
+ return { latestVersion: null, error: err instanceof Error ? err.message : String(err) };
153
+ }
154
+ }
155
+ /**
156
+ * Build the full report. The report-wide `error` is set only when EVERY
157
+ * package failed to resolve — that is the "registry unreachable" signal, and
158
+ * distinguishing it from a single 404 is what stops the UI claiming a node is
159
+ * aligned when it simply could not ask.
160
+ */
161
+ async function buildAgentAddonUpdateReport(input) {
162
+ const now = input.now ?? Date.now;
163
+ const registryUrl = input.registryUrl ?? exports.DEFAULT_NPM_REGISTRY;
164
+ const installed = readInstalledAddonPackages(input.addonsDir);
165
+ const published = new Map();
166
+ const resolved = await Promise.all(installed.map(async (pkg) => ({
167
+ packageName: pkg.packageName,
168
+ result: await resolvePublishedVersion(pkg.packageName, registryUrl, input.fetchFn),
169
+ })));
170
+ for (const r of resolved)
171
+ published.set(r.packageName, r.result);
172
+ const entries = buildAddonUpdateEntries(installed, published);
173
+ const allFailed = entries.length > 0 && entries.every((e) => e.latestVersion === null);
174
+ const firstError = entries.find((e) => e.error !== null)?.error ?? 'registry unreachable';
175
+ return {
176
+ entries,
177
+ checkedAtMs: now(),
178
+ error: allFailed ? `Could not reach ${registryUrl}: ${firstError}` : null,
179
+ hubReachable: input.isHubReachable(),
180
+ };
181
+ }
@@ -54,6 +54,7 @@ const fs = __importStar(require("node:fs"));
54
54
  const path = __importStar(require("node:path"));
55
55
  const fastify_1 = __importDefault(require("fastify"));
56
56
  const agent_http_auth_js_1 = require("./agent-http-auth.js");
57
+ const agent_update_routes_js_1 = require("./agent-update-routes.js");
57
58
  const derive_hub_url_js_1 = require("./derive-hub-url.js");
58
59
  Object.defineProperty(exports, "pickIpv4", { enumerable: true, get: function () { return derive_hub_url_js_1.pickIpv4; } });
59
60
  /** Dotted-numeric version compare; `null` sorts lowest. */
@@ -404,6 +405,10 @@ async function createAgentHttpServer(getBroker, config) {
404
405
  });
405
406
  return { success: true, message: 'Agent reconnecting...' };
406
407
  });
408
+ // -- Updates (framework local; addon roster read-only) --------------
409
+ // Registered AFTER the onRequest hook above, so every path it mounts is
410
+ // gated by the same loopback-or-bearer rule as the rest of `/api/`.
411
+ (0, agent_update_routes_js_1.registerAgentUpdateRoutes)(app, config.updateControls ?? {});
407
412
  // -- Discovered nodes -----------------------------------------------
408
413
  app.get('/api/agent/discovered-nodes', async () => {
409
414
  const b = getBroker();
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ADDON_UPDATE_UNAVAILABLE_REASON = exports.SERVER_UPDATE_UNAVAILABLE_REASON = exports.APPLY_ALREADY_RUNNING_MESSAGE = void 0;
4
+ exports.createAgentServerUpdateControls = createAgentServerUpdateControls;
5
+ exports.registerAgentUpdateRoutes = registerAgentUpdateRoutes;
6
+ /** The message a second concurrent apply gets. Exported so the test names it once. */
7
+ exports.APPLY_ALREADY_RUNNING_MESSAGE = 'Refused: an update is already in flight on this node.';
8
+ /**
9
+ * Bind the routes' controls to a real update engine.
10
+ *
11
+ * The two remembered cells (`lastCheckError`, `lastApply`) mirror the engine's
12
+ * own `checkCache`: an outcome an operator never sees is an outcome that did
13
+ * not happen, and both of these arrive on a different tick from the poll that
14
+ * has to render them.
15
+ */
16
+ function createAgentServerUpdateControls(engine, onError) {
17
+ let lastCheckError = null;
18
+ let lastApply = null;
19
+ let applyInFlight = false;
20
+ return {
21
+ getView: async () => ({
22
+ status: await engine.getServerPackageStatus(),
23
+ lastCheckError,
24
+ lastApply,
25
+ applyInFlight,
26
+ }),
27
+ check: async () => {
28
+ const result = await engine.checkServerUpdate();
29
+ lastCheckError = result.error;
30
+ return result;
31
+ },
32
+ applyLatest: () => {
33
+ if (applyInFlight) {
34
+ return { started: false, message: exports.APPLY_ALREADY_RUNNING_MESSAGE };
35
+ }
36
+ applyInFlight = true;
37
+ lastApply = null;
38
+ void engine
39
+ .applyServerUpdate({})
40
+ .then((result) => {
41
+ lastApply = result;
42
+ if (!result.accepted)
43
+ onError?.(result.message);
44
+ })
45
+ .catch((err) => {
46
+ const message = err instanceof Error ? err.message : String(err);
47
+ lastApply = {
48
+ accepted: false,
49
+ targetVersion: null,
50
+ restarting: false,
51
+ message: `Update failed: ${message}`,
52
+ };
53
+ onError?.(message);
54
+ })
55
+ .finally(() => {
56
+ applyInFlight = false;
57
+ });
58
+ return { started: true, message: null };
59
+ },
60
+ };
61
+ }
62
+ // ---------------------------------------------------------------------------
63
+ // Routes
64
+ // ---------------------------------------------------------------------------
65
+ /** Why the framework card renders empty when nothing was wired. */
66
+ exports.SERVER_UPDATE_UNAVAILABLE_REASON = 'Framework updates are not available on this agent build.';
67
+ /** Why the addon report renders empty when nothing was wired. */
68
+ exports.ADDON_UPDATE_UNAVAILABLE_REASON = 'The addon roster is not available on this agent build.';
69
+ /**
70
+ * Mount the update routes on an already-built agent HTTP server. Called from
71
+ * `createAgentHttpServer` AFTER the auth hook, so every path here inherits it.
72
+ */
73
+ function registerAgentUpdateRoutes(app, controls) {
74
+ const server = controls.server;
75
+ const addons = controls.addons;
76
+ app.get('/api/agent/server-update', async () => {
77
+ if (server === undefined) {
78
+ return { available: false, reason: exports.SERVER_UPDATE_UNAVAILABLE_REASON };
79
+ }
80
+ return { available: true, ...(await server.getView()) };
81
+ });
82
+ app.post('/api/agent/server-update/check', async (_req, reply) => {
83
+ if (server === undefined) {
84
+ return reply.status(503).send({ error: exports.SERVER_UPDATE_UNAVAILABLE_REASON });
85
+ }
86
+ return server.check();
87
+ });
88
+ // No request body is read: the target is always registry `latest`.
89
+ app.post('/api/agent/server-update/apply', async (_req, reply) => {
90
+ if (server === undefined) {
91
+ return reply.status(503).send({ error: exports.SERVER_UPDATE_UNAVAILABLE_REASON });
92
+ }
93
+ return server.applyLatest();
94
+ });
95
+ app.get('/api/agent/addon-updates', async () => {
96
+ if (addons === undefined) {
97
+ return { available: false, reason: exports.ADDON_UPDATE_UNAVAILABLE_REASON };
98
+ }
99
+ return { available: true, ...(await addons.getReport()) };
100
+ });
101
+ }
@@ -47,6 +47,8 @@ const agent_config_js_1 = require("./agent-config.js");
47
47
  const agent_group_runner_js_1 = require("./agent-group-runner.js");
48
48
  const agent_http_js_1 = require("./agent-http.js");
49
49
  const agent_service_js_1 = require("./agent-service.js");
50
+ const agent_addon_updates_js_1 = require("./agent-addon-updates.js");
51
+ const agent_update_routes_js_1 = require("./agent-update-routes.js");
50
52
  const agent_update_service_js_1 = require("./agent-update-service.js");
51
53
  const derive_hub_url_js_1 = require("./derive-hub-url.js");
52
54
  const infra_boot_guard_js_1 = require("./infra-boot-guard.js");
@@ -697,6 +699,29 @@ async function startAgent(configPath) {
697
699
  // Started early (before addon boot) so the status page is reachable
698
700
  // even while addons are still loading.
699
701
  const getBrokerFn = (() => broker);
702
+ // ── Update controls for the agent UI ──────────────────────────────
703
+ // Framework: the LOCAL `AgentUpdateService` — `npm view` + `npm install`
704
+ // straight from the registry, no hub in the path, so an isolated node can
705
+ // repair its own version. Addons: report only (the install is a hub push;
706
+ // see `agent-addon-updates.ts`).
707
+ const updateControls = {
708
+ server: (0, agent_update_routes_js_1.createAgentServerUpdateControls)(agentUpdateService, (message) => {
709
+ // A refused/failed update that logs nothing reads as "never happened".
710
+ consoleLogger.warn(`framework update not applied: ${message}`, {
711
+ tags: { nodeId: config.nodeId },
712
+ });
713
+ }),
714
+ addons: {
715
+ getReport: () => (0, agent_addon_updates_js_1.buildAgentAddonUpdateReport)({
716
+ addonsDir: config.addonsDir,
717
+ ...(process.env['CAMSTACK_NPM_REGISTRY'] !== undefined
718
+ ? { registryUrl: process.env['CAMSTACK_NPM_REGISTRY'] }
719
+ : {}),
720
+ fetchFn: (url) => fetch(url),
721
+ isHubReachable: () => getHubConnectionState() === 'connected',
722
+ }),
723
+ },
724
+ };
700
725
  void (0, agent_http_js_1.startAgentHttpServer)(getBrokerFn, {
701
726
  port: config.statusPort ?? 4444,
702
727
  nodeId: config.nodeId,
@@ -704,6 +729,7 @@ async function startAgent(configPath) {
704
729
  configPath: config.configPath,
705
730
  onReconnect: reconnect,
706
731
  getHubConnectionState,
732
+ updateControls,
707
733
  });
708
734
  // ── Phase 1: Load core infrastructure addons (in-process) ──
709
735
  // storage + settings + metrics + hub-forwarder (log destination)
@@ -1,6 +1,11 @@
1
1
  "use strict";
2
2
  /**
3
- * The switch for the HTTP request census - a SYSTEM SETTING, not an env var.
3
+ * The switch for the TRANSPORT census - a SYSTEM SETTING, not an env var.
4
+ *
5
+ * The census it arms counts three planes (`http`, `ws`, `mesh`); this module
6
+ * still owns the row named `http-request-census` because renaming a persisted
7
+ * key to improve a noun is how a diagnostic silently stops restoring across
8
+ * the release that renamed it. The key is an identifier, not a description.
4
9
  *
5
10
  * ## Why the arm deadline is persisted
6
11
  *
@@ -81,7 +86,7 @@ class RequestCensusService {
81
86
  updatedAt: this.now(),
82
87
  };
83
88
  const persisted = await this.write(record);
84
- this.logger?.info('http request census switched', {
89
+ this.logger?.info('transport census switched', {
85
90
  meta: {
86
91
  armed: this.census.armed,
87
92
  armedUntilMs: this.census.armedUntilMs,
@@ -106,13 +111,13 @@ class RequestCensusService {
106
111
  return false;
107
112
  const remainingMs = until - this.now();
108
113
  if (remainingMs <= 0) {
109
- this.logger?.info('http request census not restored - window already expired', {
114
+ this.logger?.info('transport census not restored - window already expired', {
110
115
  meta: { armedUntilMs: until },
111
116
  });
112
117
  return false;
113
118
  }
114
119
  this.census.arm(remainingMs, record?.reportEveryMs ?? http_request_census_js_1.DEFAULT_REPORT_EVERY_MS);
115
- this.logger?.info('http request census restored from system-settings', {
120
+ this.logger?.info('transport census restored from system-settings', {
116
121
  meta: { remainingMs, armedUntilMs: this.census.armedUntilMs },
117
122
  });
118
123
  return true;
@@ -134,7 +139,7 @@ class RequestCensusService {
134
139
  // A read that fails is not a disarm: it changes nothing about the live
135
140
  // census. It is logged because a branch that drops work silently reads
136
141
  // as "never happened".
137
- this.logger?.warn('http request census settings read failed', {
142
+ this.logger?.warn('transport census settings read failed', {
138
143
  meta: { error: (0, types_1.errMsg)(err) },
139
144
  });
140
145
  return null;
@@ -150,7 +155,7 @@ class RequestCensusService {
150
155
  return true;
151
156
  }
152
157
  catch (err) {
153
- this.logger?.warn('http request census armed in memory but NOT persisted - it will not survive a restart', { meta: { error: (0, types_1.errMsg)(err) } });
158
+ this.logger?.warn('transport census armed in memory but NOT persisted - it will not survive a restart', { meta: { error: (0, types_1.errMsg)(err) } });
154
159
  return false;
155
160
  }
156
161
  }
@@ -1,10 +1,30 @@
1
1
  "use strict";
2
+ /**
3
+ * Core-capability mesh bridge.
4
+ *
5
+ * The hub's CORE routers — hand-written single-impl routers plus the
6
+ * handful of service-backed cap routers — are mounted only as the hub's
7
+ * tRPC `appRouter`. No addon registers a provider for them, so
8
+ * `addon-service-factory` never publishes a Moleculer service exposing
9
+ * their actions. A forked addon calling `ctx.api.<coreCap>.<method>`
10
+ * therefore falls through `localProviderLink` into `brokerTransportLink`,
11
+ * whose load-balanced discovery wait has no deadline — the call hangs
12
+ * forever (this was the `export-alexa` `redetectHubUrl` hang).
13
+ *
14
+ * `buildCoreCapService` walks the appRouter, picks the core namespaces,
15
+ * and wraps each query/mutation as a `$core-caps.<kebab-cap>.<method>`
16
+ * Moleculer action invoked through a trusted-mesh tRPC caller. With the
17
+ * service mounted on the hub node, `brokerTransportLink` resolves and
18
+ * routes the call exactly like any addon-provided cap.
19
+ */
2
20
  Object.defineProperty(exports, "__esModule", { value: true });
3
21
  exports.isCoreServiceCapName = isCoreServiceCapName;
22
+ exports.describeMeshOrigin = describeMeshOrigin;
4
23
  exports.buildCoreCapService = buildCoreCapService;
5
24
  const system_1 = require("@camstack/system");
6
- const trpc_middleware_js_1 = require("./trpc.middleware.js");
25
+ const http_request_census_singleton_js_1 = require("./http-request-census.singleton.js");
7
26
  const trpc_context_js_1 = require("./trpc.context.js");
27
+ const trpc_middleware_js_1 = require("./trpc.middleware.js");
8
28
  /**
9
29
  * appRouter namespaces that back the CORE API surface and must be
10
30
  * reachable cross-process. This is the core-router list from
@@ -90,6 +110,41 @@ function collectProcedures(record, prefix, out) {
90
110
  }
91
111
  }
92
112
  }
113
+ /**
114
+ * The MESH plane of the transport census.
115
+ *
116
+ * A `$core-caps` action is a `createCaller` invocation: it touches no socket,
117
+ * builds no request, and was therefore invisible to any transport instrument by
118
+ * construction. This is the whole in-process plane — `createDirectCaller`
119
+ * exists in `addon-api-factory.ts` but no production call site builds one, so
120
+ * wrapping here counts every mesh entry into the hub router.
121
+ *
122
+ * Disarmed it is one boolean read: `observe` returns before it looks at
123
+ * anything, and the `principal` string is built INSIDE the guard.
124
+ */
125
+ function countMeshCall(census, path, origin) {
126
+ if (!census.armed)
127
+ return;
128
+ census.observe({
129
+ plane: 'mesh',
130
+ kind: 'call',
131
+ procedures: [path],
132
+ // A mesh call has no socket and no user-agent. Both render as the named
133
+ // unknown rather than as a blank, which would read as a logging defect.
134
+ userAgent: null,
135
+ ip: null,
136
+ principal: describeMeshOrigin(origin),
137
+ });
138
+ }
139
+ /**
140
+ * `mesh:<node> via <action>` — the closest thing an in-process call has to a
141
+ * principal. Never a token: there is none, the mesh context is trusted by
142
+ * construction (`createMeshTrpcContext`).
143
+ */
144
+ function describeMeshOrigin(origin) {
145
+ const node = origin.nodeId ?? 'unknown';
146
+ return origin.caller === null ? `mesh:${node}` : `mesh:${node} via ${origin.caller}`;
147
+ }
93
148
  /**
94
149
  * Navigate the decorated caller record (a recursive proxy) to the
95
150
  * procedure function at `path`. Every node on the proxy is callable,
@@ -112,7 +167,7 @@ function resolveInvoker(caller, path) {
112
167
  * exposed; subscriptions are skipped (the broker transport is
113
168
  * request/reply only).
114
169
  */
115
- function buildCoreCapService(appRouter) {
170
+ function buildCoreCapService(appRouter, census = (0, http_request_census_singleton_js_1.getHttpRequestCensus)()) {
116
171
  const meshCaller = (0, trpc_middleware_js_1.createCallerFactory)(appRouter)((0, trpc_context_js_1.createMeshTrpcContext)());
117
172
  const discovered = [];
118
173
  collectProcedures(appRouter._def.procedures, '', discovered);
@@ -130,7 +185,13 @@ function buildCoreCapService(appRouter) {
130
185
  if (invoke === null)
131
186
  continue;
132
187
  const method = path.slice(dot + 1);
133
- actions.push({ actionName: `${toKebab(namespace)}.${method}`, invoke });
188
+ actions.push({
189
+ actionName: `${toKebab(namespace)}.${method}`,
190
+ invoke: (input, origin) => {
191
+ countMeshCall(census, path, origin);
192
+ return invoke(input);
193
+ },
194
+ });
134
195
  }
135
196
  return (0, system_1.createCoreCapService)({ actions });
136
197
  }
@@ -1,6 +1,59 @@
1
1
  "use strict";
2
2
  /**
3
- * WHO is calling the hub over HTTP - measured at the transport, never inferred.
3
+ * WHO is calling the hub, and OVER WHICH PLANE - measured at the transport,
4
+ * never inferred.
5
+ *
6
+ * ## Three planes, and a named bucket for the fourth case
7
+ *
8
+ * The file is still called `http-request-census` and the persisted row is still
9
+ * `http-request-census`, because renaming a settings key to improve a noun is
10
+ * how a diagnostic silently stops restoring across the release that renamed it.
11
+ * The INSTRUMENT is a transport census: every call it counts carries exactly
12
+ * one {@link TransportPlane}, and the report line says `transport census`.
13
+ *
14
+ * - `http` — the Fastify tRPC plugin, hooked at the context factory
15
+ * (`http-request-census-hook.ts`), which tRPC runs once per HTTP request.
16
+ * - `ws` — `applyWSSHandler`, hooked at the client MESSAGE
17
+ * (`ws-request-census.ts`), because the WS adapter builds one context per
18
+ * CONNECTION and a per-connection hook fires once every 37 connections
19
+ * instead of once every call. This was the blind spot: `main.ts` states the
20
+ * viewer talks over `wsLink` EXCLUSIVELY, and names `deviceManager.listAll`
21
+ * while doing so.
22
+ * - `mesh` — the in-process `$core-caps` bridge (`core-cap-bridge.ts`), a
23
+ * `createCaller` that never touches a socket and so was invisible to any
24
+ * transport instrument by construction.
25
+ * - `unknown` — counted, plane undecidable. No hook produces it today, and its
26
+ * `0` is the claim that every plane the hub has can name itself. It exists
27
+ * so that a call is never lost and never silently absent;
28
+ * `planesExplainTotal` is the check.
29
+ *
30
+ * ## What this counts, and what the FLEET census counts - read them together
31
+ *
32
+ * These two instruments overlap and must not be added up:
33
+ *
34
+ * - This one counts ENTRIES INTO THE HUB'S tRPC ROUTER, one row per
35
+ * operation, attributed to a plane and a caller.
36
+ * - `FleetReadCensus`
37
+ * (`packages/system/src/builtins/device-manager/fleet-read-census.ts`)
38
+ * counts READS OF THE DEVICE ROW STORE, wherever they came from,
39
+ * attributed to a JS call site - or, for a call that arrived over the cap
40
+ * channel, to `addon:<id>` carried as data.
41
+ *
42
+ * A single viewer `deviceManager.listAll` is ONE row here (plane `ws`) and ONE
43
+ * row there (a stack site). Summing them double-counts it. The reconciliation
44
+ * that is meaningful runs the other way:
45
+ *
46
+ * fleet.totalCalls - Σ fleet.rows[site startsWith 'addon:'].calls
47
+ * == this.procedures['deviceManager.listAll'].calls
48
+ *
49
+ * i.e. store reads that did NOT arrive over the cap channel should be exactly
50
+ * the router entries this census saw, over the SAME window. When it does not
51
+ * balance, a plane is missing from this instrument - which is a result. The
52
+ * two windows are armed separately (this one from the logging document, the
53
+ * fleet one from `CAMSTACK_FLEET_READ_CENSUS_MS`), so the comparison is only
54
+ * valid when both were armed across the same boot; nothing here joins them
55
+ * automatically, because a join across two differently-armed windows would
56
+ * produce a confident wrong number.
4
57
  *
5
58
  * ## The number this exists to explain
6
59
  *
@@ -21,24 +74,25 @@
21
74
  * plausible caller is exactly what this repo has already got wrong twice at
22
75
  * half a day each. An attribution is a measurement or it is a guess.
23
76
  *
24
- * ## Reading the NEGATIVE - the result this is most likely to produce
77
+ * ## Reading the NEGATIVE - an excluded plane is a result
25
78
  *
26
- * `snapshot().procedures[]` is the TOTAL per procedure over the window,
27
- * independent of how many caller groups it is split across. That total is the
28
- * whole point: if `deviceManager.listAll` reads a few dozen HTTP calls while
29
- * the fleet census reads ~4 960 over the same boot, **the callers are not HTTP
30
- * clients** and the search moves to the other two planes that reach the same
31
- * router - the tRPC WebSocket (`applyWSSHandler` in `main.ts`; the viewer talks
32
- * over `wsLink` EXCLUSIVELY) and the in-process mesh bridge (`createCaller`,
33
- * which never touches HTTP at all). Excluding a plane is worth as much as
34
- * naming a caller, and it is only worth anything if the exclusion is legible:
35
- * hence `wsConnections`, counted on the same object, so one log line says
36
- * "8 HTTP calls, 37 WebSocket connections opened" instead of leaving the
37
- * reader to wonder whether the instrument was even running.
79
+ * `snapshot().procedures[]` is the TOTAL per procedure over the window, split
80
+ * by plane. Excluding a plane is worth as much as naming a caller, and it is
81
+ * only worth anything if the exclusion is legible - so every plane is reported
82
+ * even at `0`. An absent key reads as "not instrumented"; a `0` reads as
83
+ * "instrumented, and it was not this one".
38
84
  *
39
85
  * A census that collected nothing still reports. Silence after an arm is
40
86
  * indistinguishable from a census that never armed.
41
87
  *
88
+ * ## A subscription is not a query
89
+ *
90
+ * Subscription starts are counted APART from calls and never enter
91
+ * `procedureCalls`. One `live.events` stream opened at boot and held for six
92
+ * hours is one operation; folding it in would let a quiet plane wear the
93
+ * costume of a storm - the exact misreading this whole instrument exists to
94
+ * prevent.
95
+ *
42
96
  * ## Cost when disarmed
43
97
  *
44
98
  * {@link HttpRequestCensus.armed} is a plain boolean FIELD, not a clock
@@ -53,6 +107,7 @@
53
107
  */
54
108
  Object.defineProperty(exports, "__esModule", { value: true });
55
109
  exports.HttpRequestCensus = exports.UNKNOWN = exports.PROCEDURE_OVERFLOW = exports.BATCH_OVERFLOW_PROCEDURE = exports.MAX_BATCH_PROCEDURES = exports.USER_AGENT_MAX_CHARS = exports.MAX_PROCEDURES = exports.MAX_GROUPS = exports.MIN_REPORT_EVERY_MS = exports.DEFAULT_REPORT_EVERY_MS = exports.MIN_WINDOW_MS = exports.MAX_WINDOW_MS = exports.TRPC_URL_PREFIX = void 0;
110
+ exports.zeroPlaneCounts = zeroPlaneCounts;
56
111
  exports.shortenUserAgent = shortenUserAgent;
57
112
  exports.parseTrpcProcedures = parseTrpcProcedures;
58
113
  /** Route prefix the tRPC plugin is registered under (`main.ts`). */
@@ -111,6 +166,23 @@ exports.UNKNOWN = 'unknown';
111
166
  /** Group-key field separator. A character that cannot appear in a tRPC
112
167
  * procedure path, so two different tuples can never collide into one row. */
113
168
  const KEY_SEPARATOR = ' | ';
169
+ /**
170
+ * A zeroed counter for every plane.
171
+ *
172
+ * Exhaustive by TYPE, not by discipline: adding a value to the wire enum makes
173
+ * this literal fail to compile until it is given a counter. That is what keeps
174
+ * "a plane is never silently absent" from being a comment nobody enforces.
175
+ */
176
+ function zeroPlaneCounts() {
177
+ return { http: 0, ws: 0, mesh: 0, unknown: 0 };
178
+ }
179
+ /** Frozen view of a mutable plane counter, for the wire. */
180
+ function freezePlaneCounts(counts) {
181
+ return { http: counts.http, ws: counts.ws, mesh: counts.mesh, unknown: counts.unknown };
182
+ }
183
+ function sumPlaneCounts(counts) {
184
+ return counts.http + counts.ws + counts.mesh + counts.unknown;
185
+ }
114
186
  function defaultSchedule(fn, ms) {
115
187
  // `unref` so an armed census never holds the process open at shutdown.
116
188
  setTimeout(fn, ms).unref();
@@ -242,7 +314,11 @@ class HttpRequestCensus {
242
314
  batchedRequests = 0;
243
315
  procedureCalls = 0;
244
316
  wsConnections = 0;
317
+ wsMessages = 0;
318
+ subscriptions = 0;
319
+ subscriptionStops = 0;
245
320
  unattributedCalls = 0;
321
+ planeCalls = zeroPlaneCounts();
246
322
  byProcedure = new Map();
247
323
  byGroup = new Map();
248
324
  logger = null;
@@ -310,38 +386,85 @@ class HttpRequestCensus {
310
386
  this.httpRequests += 1;
311
387
  if (observation.procedures.length > 1)
312
388
  this.batchedRequests += 1;
389
+ this.observe({ ...observation, plane: 'http', kind: 'call' });
390
+ }
391
+ /**
392
+ * Count operations on ANY plane.
393
+ *
394
+ * The plane is data rather than a method name so that a plane added later
395
+ * cannot quietly reuse the HTTP bookkeeping (`httpRequests`,
396
+ * `batchedRequests`), which counts REQUESTS and means nothing off HTTP.
397
+ */
398
+ observe(observation) {
399
+ if (!this.isArmed)
400
+ return;
401
+ if (observation.procedures.length === 0)
402
+ return;
313
403
  const userAgent = shortenUserAgent(observation.userAgent);
314
404
  const ip = observation.ip ?? exports.UNKNOWN;
315
- const principal = observation.principal;
405
+ const { plane, kind, principal } = observation;
316
406
  for (const procedure of observation.procedures) {
317
- this.procedureCalls += 1;
318
- this.countProcedure(procedure);
319
- const key = [procedure, userAgent, ip, principal].join(KEY_SEPARATOR);
407
+ if (kind === 'subscription')
408
+ this.subscriptions += 1;
409
+ else {
410
+ this.procedureCalls += 1;
411
+ this.planeCalls[plane] += 1;
412
+ }
413
+ this.countProcedure(procedure, plane, kind);
414
+ const key = [plane, procedure, userAgent, ip, principal].join(KEY_SEPARATOR);
320
415
  const group = this.byGroup.get(key);
321
416
  if (group !== undefined) {
322
- group.calls += 1;
417
+ if (kind === 'subscription')
418
+ group.subscriptions += 1;
419
+ else
420
+ group.calls += 1;
323
421
  continue;
324
422
  }
325
423
  if (this.byGroup.size >= exports.MAX_GROUPS) {
326
424
  this.unattributedCalls += 1;
327
425
  continue;
328
426
  }
329
- this.byGroup.set(key, { procedure, userAgent, ip, principal, calls: 1 });
427
+ this.byGroup.set(key, {
428
+ plane,
429
+ procedure,
430
+ userAgent,
431
+ ip,
432
+ principal,
433
+ calls: kind === 'subscription' ? 0 : 1,
434
+ subscriptions: kind === 'subscription' ? 1 : 0,
435
+ });
330
436
  }
331
437
  }
332
438
  /**
333
439
  * Count one tRPC WebSocket connection opening.
334
440
  *
335
- * Deliberately NOT a call count: the WS adapter resolves one context per
336
- * connection, and per-message procedure names never reach this layer. It is
337
- * here so a near-zero HTTP total can be read as "the traffic went somewhere
338
- * else" rather than as "the instrument was off".
441
+ * NOT a call count - the WS adapter resolves one context per connection.
442
+ * Kept alongside the per-operation `ws` plane because "37 connections, 0
443
+ * calls" and "0 connections, 0 calls" are different answers.
339
444
  */
340
445
  observeWsConnection() {
341
446
  if (!this.isArmed)
342
447
  return;
343
448
  this.wsConnections += 1;
344
449
  }
450
+ /** Count one client frame the WS plane inspected, operation or not. */
451
+ observeWsMessage() {
452
+ if (!this.isArmed)
453
+ return;
454
+ this.wsMessages += 1;
455
+ }
456
+ /**
457
+ * Count `subscription.stop` frames.
458
+ *
459
+ * Stops carry no procedure path on the wire (tRPC's stop message is `{ id }`
460
+ * and nothing else), so they are a scalar rather than a group row - inventing
461
+ * a path for them would put a name on the line that the client never sent.
462
+ */
463
+ observeSubscriptionStop(count = 1) {
464
+ if (!this.isArmed)
465
+ return;
466
+ this.subscriptionStops += count;
467
+ }
345
468
  /** Everything the window measured, busiest first. */
346
469
  snapshot(limit = exports.MAX_GROUPS) {
347
470
  const elapsedMs = this.elapsedMs();
@@ -350,19 +473,23 @@ class HttpRequestCensus {
350
473
  .map(([procedure, count]) => ({
351
474
  procedure,
352
475
  calls: count.calls,
476
+ planes: freezePlaneCounts(count.planes),
477
+ subscriptions: count.subscriptions,
353
478
  perMin: perMin(count.calls),
354
479
  }))
355
480
  .toSorted((a, b) => b.calls - a.calls);
356
481
  const groups = [...this.byGroup.values()]
357
482
  .map((group) => ({
483
+ plane: group.plane,
358
484
  procedure: group.procedure,
359
485
  userAgent: group.userAgent,
360
486
  ip: group.ip,
361
487
  principal: group.principal,
362
488
  calls: group.calls,
489
+ subscriptions: group.subscriptions,
363
490
  perMin: perMin(group.calls),
364
491
  }))
365
- .toSorted((a, b) => b.calls - a.calls);
492
+ .toSorted((a, b) => b.calls + b.subscriptions - (a.calls + a.subscriptions));
366
493
  return {
367
494
  armed: this.isArmed,
368
495
  elapsedMs,
@@ -371,7 +498,12 @@ class HttpRequestCensus {
371
498
  httpRequests: this.httpRequests,
372
499
  batchedRequests: this.batchedRequests,
373
500
  procedureCalls: this.procedureCalls,
501
+ planes: freezePlaneCounts(this.planeCalls),
502
+ planesExplainTotal: sumPlaneCounts(this.planeCalls) === this.procedureCalls,
374
503
  wsConnections: this.wsConnections,
504
+ wsMessages: this.wsMessages,
505
+ subscriptions: this.subscriptions,
506
+ subscriptionStops: this.subscriptionStops,
375
507
  distinctGroups: this.byGroup.size,
376
508
  unattributedCalls: this.unattributedCalls,
377
509
  procedures: procedures.slice(0, limit),
@@ -379,55 +511,71 @@ class HttpRequestCensus {
379
511
  };
380
512
  }
381
513
  /**
382
- * Emit ONE aggregated line.
514
+ * Emit ONE aggregated line - the line that answers the question.
515
+ *
516
+ * Field order is the reading order: `planes` first (which transport), then
517
+ * `planesExplainTotal` (is any call unaccounted for), then `procedures`
518
+ * (which procedure, split by plane), then `top` (which caller). `top` is the
519
+ * part that may be cut; the first three never are.
383
520
  *
384
- * `procedures` comes first because that block is what answers "was it HTTP
385
- * at all". `top` is the classification, and it is the part that may be cut.
521
+ * The message is `transport census` rather than `http request census`
522
+ * because the line now carries three planes. Grepping Loki for the old text
523
+ * would find only pre-2026-08-27 windows, which is the honest outcome: those
524
+ * windows really did measure one plane.
386
525
  */
387
526
  report(phase) {
388
527
  const logger = this.logger;
389
528
  if (logger === null)
390
529
  return;
391
530
  const snap = this.snapshot();
392
- logger.info('http request census', {
531
+ logger.info('transport census', {
393
532
  meta: {
394
533
  phase,
395
534
  armed: snap.armed,
396
535
  elapsedMs: snap.elapsedMs,
397
536
  windowMs: snap.windowMs,
537
+ planes: snap.planes,
538
+ procedureCalls: snap.procedureCalls,
539
+ // The acceptance criterion, ON the line: false means a call was
540
+ // counted on no plane, i.e. this instrument is missing one.
541
+ planesExplainTotal: snap.planesExplainTotal,
542
+ subscriptions: snap.subscriptions,
543
+ subscriptionStops: snap.subscriptionStops,
398
544
  httpRequests: snap.httpRequests,
399
545
  batchedRequests: snap.batchedRequests,
400
- procedureCalls: snap.procedureCalls,
401
546
  wsConnections: snap.wsConnections,
547
+ wsMessages: snap.wsMessages,
402
548
  distinctGroups: snap.distinctGroups,
403
549
  unattributedCalls: snap.unattributedCalls,
404
550
  procedures: snap.procedures.slice(0, REPORTED_PROCEDURES),
405
551
  top: snap.groups.slice(0, REPORTED_GROUPS).map((group) => ({
552
+ plane: group.plane,
406
553
  procedure: group.procedure,
407
554
  ua: group.userAgent,
408
555
  ip: group.ip,
409
556
  principal: group.principal,
410
557
  calls: group.calls,
558
+ subscriptions: group.subscriptions,
411
559
  perMin: group.perMin,
412
560
  })),
413
561
  },
414
562
  });
415
563
  }
416
- countProcedure(procedure) {
564
+ countProcedure(procedure, plane, kind) {
417
565
  const existing = this.byProcedure.get(procedure);
418
566
  if (existing !== undefined) {
419
- existing.calls += 1;
567
+ bumpCount(existing, plane, kind);
420
568
  return;
421
569
  }
422
570
  if (this.byProcedure.size >= exports.MAX_PROCEDURES) {
423
- const overflow = this.byProcedure.get(exports.PROCEDURE_OVERFLOW);
424
- if (overflow === undefined)
425
- this.byProcedure.set(exports.PROCEDURE_OVERFLOW, { calls: 1 });
426
- else
427
- overflow.calls += 1;
571
+ const overflow = this.byProcedure.get(exports.PROCEDURE_OVERFLOW) ?? newCount();
572
+ bumpCount(overflow, plane, kind);
573
+ this.byProcedure.set(exports.PROCEDURE_OVERFLOW, overflow);
428
574
  return;
429
575
  }
430
- this.byProcedure.set(procedure, { calls: 1 });
576
+ const fresh = newCount();
577
+ bumpCount(fresh, plane, kind);
578
+ this.byProcedure.set(procedure, fresh);
431
579
  }
432
580
  elapsedMs() {
433
581
  if (this.armedAt === 0)
@@ -442,7 +590,11 @@ class HttpRequestCensus {
442
590
  this.batchedRequests = 0;
443
591
  this.procedureCalls = 0;
444
592
  this.wsConnections = 0;
593
+ this.wsMessages = 0;
594
+ this.subscriptions = 0;
595
+ this.subscriptionStops = 0;
445
596
  this.unattributedCalls = 0;
597
+ this.planeCalls = zeroPlaneCounts();
446
598
  }
447
599
  scheduleTick(generation) {
448
600
  this.schedule(() => {
@@ -464,6 +616,17 @@ const REPORTED_PROCEDURES = 40;
464
616
  /** Caller groups carried on one report line. Enough to name a culprit,
465
617
  * bounded so one line stays a line. */
466
618
  const REPORTED_GROUPS = 25;
619
+ function newCount() {
620
+ return { calls: 0, subscriptions: 0, planes: zeroPlaneCounts() };
621
+ }
622
+ function bumpCount(count, plane, kind) {
623
+ if (kind === 'subscription') {
624
+ count.subscriptions += 1;
625
+ return;
626
+ }
627
+ count.calls += 1;
628
+ count.planes[plane] += 1;
629
+ }
467
630
  function clamp(value, min, max) {
468
631
  if (!Number.isFinite(value))
469
632
  return min;
@@ -0,0 +1,300 @@
1
+ "use strict";
2
+ /**
3
+ * The WebSocket plane of the transport census — hooked PER OPERATION.
4
+ *
5
+ * ## Why the hook is on the client MESSAGE and not on `createContext`
6
+ *
7
+ * `recordTrpcHttpRequest` hangs off the tRPC context factory because on HTTP
8
+ * that factory runs exactly once per request. On the WebSocket it does not:
9
+ * `applyWSSHandler` builds ONE context per CONNECTION and reuses it for every
10
+ * message the socket ever sends. A census wired there fires once every 37
11
+ * connections instead of once every call — which is precisely how a plane
12
+ * carrying thousands of `deviceManager.listAll` calls reported `wsConnections:
13
+ * 37` and nothing else.
14
+ *
15
+ * tRPC's WS adapter exposes no per-operation seam: `onError` fires only on
16
+ * failures, and `getWSConnectionHandler` keeps `handleRequest` private. The
17
+ * only place an operation is observable from outside is the frame that carried
18
+ * it. So this module registers its OWN `message` listener on the same socket
19
+ * and reads the same wire format the adapter reads, mirroring its rules:
20
+ *
21
+ * - `PING` / `PONG` are keepalive text frames the adapter answers before
22
+ * parsing anything. They are not operations.
23
+ * - A frame may be an ARRAY of messages (`wsLink` batches). Counting a batch
24
+ * as one call undercounts by the batch factor — the direction that clears
25
+ * an innocent transport.
26
+ * - `method` is one of `query`, `mutation`, `subscription`,
27
+ * `subscription.stop`. Anything else — `connectionParams`, or a method a
28
+ * later tRPC adds — is NOT an operation and must not be counted as one.
29
+ *
30
+ * ## Cost when disarmed
31
+ *
32
+ * `census.armed` is the FIRST statement of the message listener: no
33
+ * `toString()`, no `JSON.parse`, no allocation, no clock read. The listener
34
+ * itself is registered unconditionally because the window can open mid-
35
+ * connection, and a socket opened before the arm would otherwise be invisible
36
+ * for its whole life. What a disarmed hub pays is therefore one boolean read
37
+ * per frame plus one small session object per CONNECTION — not per call.
38
+ *
39
+ * ## Identity is the CONNECTION's, derived once
40
+ *
41
+ * A WS frame carries no credential; the bearer arrived once, in the connection
42
+ * params, and `createWsTrpcContext` resolved it. So the principal is derived
43
+ * ONCE with `describeTrpcPrincipal` — the same renderer the tRPC error log
44
+ * uses, a username and a credential KIND, never a token and never a header —
45
+ * and reused for every operation on that socket.
46
+ *
47
+ * That resolution is asynchronous, and the client's first query can land
48
+ * before it completes. Those operations are therefore HELD, and released under
49
+ * the real principal the moment {@link identifyWsCensusSession} runs. A socket
50
+ * that closes without ever being identified releases them under
51
+ * {@link UNKNOWN} instead: a call this instrument saw is never dropped for
52
+ * want of a name.
53
+ */
54
+ Object.defineProperty(exports, "__esModule", { value: true });
55
+ exports.WsCensusSession = exports.MAX_PENDING_WS_OPERATIONS = exports.WS_PATHLESS_PROCEDURE = void 0;
56
+ exports.parseTrpcWsFrame = parseTrpcWsFrame;
57
+ exports.attachWsCensusSession = attachWsCensusSession;
58
+ exports.identifyWsCensusSession = identifyWsCensusSession;
59
+ const client_ip_js_1 = require("./client-ip.js");
60
+ const http_request_census_js_1 = require("./http-request-census.js");
61
+ /** Keepalive frames the tRPC adapter answers before parsing. Not operations. */
62
+ const KEEPALIVE_FRAMES = new Set(['PING', 'PONG']);
63
+ /**
64
+ * Synthetic name for an operation frame that named a `method` but no `path`.
65
+ *
66
+ * tRPC rejects such a frame, but it still ARRIVED, and a census that drops it
67
+ * has a hole in the total the plane comparison rests on.
68
+ */
69
+ exports.WS_PATHLESS_PROCEDURE = '(ws-no-path)';
70
+ /**
71
+ * Operations held for a connection whose principal has not resolved yet.
72
+ *
73
+ * A client cannot get thousands of queries in before its own connection params
74
+ * are processed; this bound exists so a hostile socket cannot grow the buffer
75
+ * without limit. Past it, operations are counted immediately under
76
+ * {@link UNKNOWN} rather than dropped.
77
+ */
78
+ exports.MAX_PENDING_WS_OPERATIONS = 128;
79
+ const NO_OPERATIONS = { calls: [], subscriptions: [], stops: 0 };
80
+ /**
81
+ * Read the operations out of one raw client frame.
82
+ *
83
+ * Exported and pure so the wire rules are pinned by spec rather than trusted:
84
+ * every one of them is a place where the count could be wrong in the direction
85
+ * that exonerates this plane.
86
+ */
87
+ function parseTrpcWsFrame(raw) {
88
+ const text = raw.trim();
89
+ if (text.length === 0)
90
+ return NO_OPERATIONS;
91
+ if (KEEPALIVE_FRAMES.has(text))
92
+ return NO_OPERATIONS;
93
+ const parsed = parseJsonSafely(text);
94
+ if (parsed === null)
95
+ return NO_OPERATIONS;
96
+ const messages = Array.isArray(parsed) ? parsed : [parsed];
97
+ const calls = [];
98
+ const subscriptions = [];
99
+ let stops = 0;
100
+ let overflowed = false;
101
+ for (const message of messages) {
102
+ if (typeof message !== 'object' || message === null)
103
+ continue;
104
+ const method = Reflect.get(message, 'method');
105
+ if (method === 'subscription.stop') {
106
+ stops += 1;
107
+ continue;
108
+ }
109
+ if (method !== 'query' && method !== 'mutation' && method !== 'subscription')
110
+ continue;
111
+ if (calls.length + subscriptions.length >= http_request_census_js_1.MAX_BATCH_PROCEDURES) {
112
+ overflowed = true;
113
+ continue;
114
+ }
115
+ const path = readPath(Reflect.get(message, 'params'));
116
+ if (method === 'subscription')
117
+ subscriptions.push(path);
118
+ else
119
+ calls.push(path);
120
+ }
121
+ if (overflowed)
122
+ calls.push(http_request_census_js_1.BATCH_OVERFLOW_PROCEDURE);
123
+ return { calls, subscriptions, stops };
124
+ }
125
+ function parseJsonSafely(text) {
126
+ try {
127
+ return JSON.parse(text);
128
+ }
129
+ catch {
130
+ // A frame tRPC itself will refuse with PARSE_ERROR. It invoked no
131
+ // procedure, so it belongs to no plane's call count.
132
+ return null;
133
+ }
134
+ }
135
+ function readPath(params) {
136
+ if (typeof params !== 'object' || params === null)
137
+ return exports.WS_PATHLESS_PROCEDURE;
138
+ const path = Reflect.get(params, 'path');
139
+ return typeof path === 'string' && path.length > 0 ? path : exports.WS_PATHLESS_PROCEDURE;
140
+ }
141
+ /** One connection's census state: its identity, and anything held for it. */
142
+ class WsCensusSession {
143
+ census;
144
+ userAgent;
145
+ ip;
146
+ /** `null` until `createWsTrpcContext` resolved the bearer. */
147
+ principal = null;
148
+ pending = [];
149
+ closed = false;
150
+ constructor(census, req) {
151
+ this.census = census;
152
+ this.userAgent = (0, client_ip_js_1.extractUserAgent)(req);
153
+ this.ip = (0, client_ip_js_1.extractClientIp)(req);
154
+ }
155
+ /**
156
+ * Count one raw client frame.
157
+ *
158
+ * The armed check is the FIRST statement. If it ever moves below a field
159
+ * access, the hostile-frame spec fails instead of the hub paying for a
160
+ * diagnostic nobody switched on.
161
+ */
162
+ observeMessage(data) {
163
+ if (!this.census.armed)
164
+ return;
165
+ this.census.observeWsMessage();
166
+ const text = frameText(data);
167
+ if (text === null)
168
+ return;
169
+ const operations = parseTrpcWsFrame(text);
170
+ if (operations.stops > 0)
171
+ this.census.observeSubscriptionStop(operations.stops);
172
+ if (operations.calls.length === 0 && operations.subscriptions.length === 0)
173
+ return;
174
+ if (this.principal !== null) {
175
+ this.flushFrame(operations, this.principal);
176
+ return;
177
+ }
178
+ if (this.pending.length >= exports.MAX_PENDING_WS_OPERATIONS) {
179
+ // Never dropped — attributed to the named bucket instead.
180
+ this.flushFrame(operations, http_request_census_js_1.UNKNOWN);
181
+ return;
182
+ }
183
+ this.pending.push(operations);
184
+ }
185
+ /** Name the connection, once, and release everything held for it. */
186
+ identify(principal) {
187
+ if (this.principal !== null || this.closed)
188
+ return;
189
+ this.principal = principal;
190
+ this.drain(principal);
191
+ }
192
+ /** The socket went away. Anything still unnamed is released as {@link UNKNOWN}. */
193
+ close() {
194
+ if (this.closed)
195
+ return;
196
+ this.closed = true;
197
+ this.drain(this.principal ?? http_request_census_js_1.UNKNOWN);
198
+ }
199
+ drain(principal) {
200
+ if (this.pending.length === 0)
201
+ return;
202
+ const held = this.pending;
203
+ this.pending = [];
204
+ for (const frame of held)
205
+ this.flushFrame(frame, principal);
206
+ }
207
+ flushFrame(operations, principal) {
208
+ if (operations.calls.length > 0) {
209
+ this.census.observe({
210
+ plane: 'ws',
211
+ kind: 'call',
212
+ procedures: operations.calls,
213
+ userAgent: this.userAgent,
214
+ ip: this.ip,
215
+ principal,
216
+ });
217
+ }
218
+ if (operations.subscriptions.length > 0) {
219
+ this.census.observe({
220
+ plane: 'ws',
221
+ kind: 'subscription',
222
+ procedures: operations.subscriptions,
223
+ userAgent: this.userAgent,
224
+ ip: this.ip,
225
+ principal,
226
+ });
227
+ }
228
+ }
229
+ }
230
+ exports.WsCensusSession = WsCensusSession;
231
+ /**
232
+ * Sessions by socket.
233
+ *
234
+ * A `WeakMap` rather than a registry: the census must never be the reason a
235
+ * closed socket stays reachable. `identifyWsCensusSession` is a no-op for a
236
+ * socket that was never attached, which is what makes the WS context factory
237
+ * safe to call unconditionally.
238
+ */
239
+ const sessions = new WeakMap();
240
+ /**
241
+ * Start counting one tRPC WebSocket connection, per operation.
242
+ *
243
+ * Registered from `main.ts` on the same `wss` `applyWSSHandler` is given. Both
244
+ * listeners see every frame; ours only counts.
245
+ */
246
+ function attachWsCensusSession(census, client, req, logger) {
247
+ census.observeWsConnection();
248
+ const session = new WsCensusSession(census, req);
249
+ sessions.set(client, session);
250
+ // A throw inside a `ws` message listener is an UNCAUGHT EXCEPTION, not a
251
+ // failed request: nothing above it catches. A diagnostic must never be able
252
+ // to take the hub down, so this socket's counting stops at the first throw
253
+ // and SAYS SO once — a branch that drops work silently reads as "never
254
+ // happened", and once-per-socket is what keeps the confession from becoming
255
+ // the flood it is confessing about.
256
+ let broken = false;
257
+ client.on('message', (data) => {
258
+ if (broken)
259
+ return;
260
+ try {
261
+ session.observeMessage(data);
262
+ }
263
+ catch (err) {
264
+ broken = true;
265
+ logger?.warn('transport census: ws frames no longer counted on this socket', {
266
+ meta: { error: err instanceof Error ? err.message : String(err) },
267
+ });
268
+ }
269
+ });
270
+ client.once('close', () => {
271
+ session.close();
272
+ });
273
+ return session;
274
+ }
275
+ /**
276
+ * Name a connection's principal, once, from the WS context factory.
277
+ *
278
+ * Called with the output of `describeTrpcPrincipal` — never a token, never a
279
+ * header. Silently does nothing when the socket was never attached, so a test
280
+ * harness or a future adapter that builds a context without a census session
281
+ * does not have to know this exists.
282
+ */
283
+ function identifyWsCensusSession(client, principal) {
284
+ sessions.get(client)?.identify(principal);
285
+ }
286
+ /** Decode a `ws` frame payload to text. Returns `null` for a shape that cannot
287
+ * be text — such a frame carried no tRPC operation either. */
288
+ function frameText(data) {
289
+ if (typeof data === 'string')
290
+ return data;
291
+ if (Buffer.isBuffer(data))
292
+ return data.toString('utf8');
293
+ if (data instanceof ArrayBuffer)
294
+ return Buffer.from(data).toString('utf8');
295
+ if (Array.isArray(data)) {
296
+ const chunks = data.filter((chunk) => Buffer.isBuffer(chunk));
297
+ return chunks.length === 0 ? null : Buffer.concat(chunks).toString('utf8');
298
+ }
299
+ return null;
300
+ }
package/dist/main.js CHANGED
@@ -75,6 +75,7 @@ const http_request_census_singleton_1 = require("./api/trpc/http-request-census.
75
75
  const trpc_context_1 = require("./api/trpc/trpc.context");
76
76
  const trpc_router_1 = require("./api/trpc/trpc.router");
77
77
  const trpc_error_principal_1 = require("./api/trpc/trpc-error-principal");
78
+ const ws_request_census_1 = require("./api/trpc/ws-request-census");
78
79
  const addon_route_jwt_gate_js_1 = require("./auth/addon-route-jwt-gate.js");
79
80
  const session_cookie_js_1 = require("./auth/session-cookie.js");
80
81
  const boot_config_1 = require("./boot/boot-config");
@@ -1087,16 +1088,27 @@ async function bootstrap() {
1087
1088
  concurrencyLimit: 10,
1088
1089
  },
1089
1090
  });
1091
+ // The WS plane of the transport census, hooked PER OPERATION.
1092
+ //
1093
+ // It cannot hang off `createContext` below: that factory runs once per
1094
+ // CONNECTION and is reused for every frame the socket ever sends, so a
1095
+ // census wired there fires once every 37 connections instead of once every
1096
+ // call. The frame is the only place an operation is observable from
1097
+ // outside the adapter — see `ws-request-census.ts`. Registered before
1098
+ // `applyWSSHandler` so no socket can be accepted without a session.
1099
+ wss.on('connection', (client, req) => {
1100
+ (0, ws_request_census_1.attachWsCensusSession)(httpRequestCensus, client, req, app.get(logging_service_1.LoggingService).createLogger('tRPC:ws'));
1101
+ });
1090
1102
  (0, ws_1.applyWSSHandler)({
1091
1103
  wss,
1092
1104
  router: appRouter,
1093
- createContext: (opts) => {
1094
- // One count per CONNECTION, not per call: the WS adapter builds one
1095
- // context per socket and per-message procedure names never reach this
1096
- // layer. It is here so a near-zero HTTP total reads as "the traffic
1097
- // went to the other plane" rather than as "the census was off".
1098
- httpRequestCensus.observeWsConnection();
1099
- return (0, trpc_context_1.createWsTrpcContext)(opts, authService, addonRegistry, shareTokenService, app.get(logging_service_1.LoggingService).createLogger('tRPC:ws'));
1105
+ createContext: async (opts) => {
1106
+ const wsCtx = await (0, trpc_context_1.createWsTrpcContext)(opts, authService, addonRegistry, shareTokenService, app.get(logging_service_1.LoggingService).createLogger('tRPC:ws'));
1107
+ // The connection's identity, derived ONCE and reused for every
1108
+ // operation on this socket. Frames that arrived while the bearer was
1109
+ // still resolving are held by the session and released here.
1110
+ (0, ws_request_census_1.identifyWsCensusSession)(opts.res, (0, trpc_error_principal_1.describeTrpcPrincipal)(wsCtx.user));
1111
+ return wsCtx;
1100
1112
  },
1101
1113
  onError: ({ path: trpcPath, error, ctx, }) => {
1102
1114
  const trpcLogger = app.get(logging_service_1.LoggingService).createLogger('tRPC:ws');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/server",
3
- "version": "1.2.176",
3
+ "version": "1.2.177",
4
4
  "private": false,
5
5
  "files": [
6
6
  "dist",