@camstack/server 1.2.176 → 1.2.178

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,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
+ }
@@ -48,13 +48,13 @@ const client_1 = require("@trpc/client");
48
48
  const addon_call_gateway_js_1 = require("./addon-call-gateway.js");
49
49
  const addon_row_manifest_1 = require("./addon-row-manifest");
50
50
  const addon_settings_provider_js_1 = require("./addon-settings-provider.js");
51
+ const device_meta_mirror_js_1 = require("./device-meta-mirror.js");
51
52
  const integration_visibility_js_1 = require("./integration-visibility.js");
52
53
  const package_dir_utils_1 = require("./package-dir-utils");
53
54
  const prune_misplaced_addons_js_1 = require("./prune-misplaced-addons.js");
54
55
  const require_cache_js_1 = require("./require-cache.js");
55
56
  const runner_convergence_1 = require("./runner-convergence");
56
57
  const runner_spawn_fanout_js_1 = require("./runner-spawn-fanout.js");
57
- const single_flight_refresh_js_1 = require("./single-flight-refresh.js");
58
58
  /**
59
59
  * Decide whether an in-memory addon entry should be evicted because it is no
60
60
  * longer on disk (the uninstall path in `loadNewAddons`).
@@ -309,6 +309,14 @@ class AddonRegistryService {
309
309
  this.streamProbe = streamProbe;
310
310
  this.logger = this.loggingService.createLogger('AddonRegistry');
311
311
  this.addonLoader = new system_1.AddonLoader(this.loggingService.createLogger('AddonLoader'));
312
+ this.deviceMirror = new device_meta_mirror_js_1.DeviceMetaMirror(async (deviceIds) => this.getBrokerApi().deviceManager.listAll.query({
313
+ projection: 'slim',
314
+ ...(deviceIds === null ? {} : { deviceIds: [...deviceIds] }),
315
+ }), {
316
+ parentDeviceId: (deviceId) => this.deviceRegistry.getById(deviceId)?.parentDeviceId ?? null,
317
+ type: (deviceId) => this.deviceRegistry.getById(deviceId)?.type ?? null,
318
+ location: (deviceId) => this.deviceRegistry.getById(deviceId)?.location ?? null,
319
+ }, this.logger);
312
320
  // Kernel-level addon health monitor — drives the 5-min boot grace
313
321
  // window + aggressive auto-retry loop (60s/120s/300s, never gives
314
322
  // up). Failures and recoveries are recorded by the load + init
@@ -1130,56 +1138,22 @@ class AddonRegistryService {
1130
1138
  // fleet — forked devices included. This is a hub-process, SYNCHRONOUSLY
1131
1139
  // readable mirror of that parentage, refreshed OFF the request path on every
1132
1140
  // device-meta lifecycle event — never a per-call DB query.
1133
- deviceParentMirror = new Map();
1134
- /**
1135
- * Hub-process mirror of each device's persisted `type` + `location`, warmed
1136
- * from the same `listAll({projection:'slim'})` sweep as the parent mirror.
1137
- * Backs the v3 scope-model `types` / `locations` selectors: the enforcement
1138
- * matcher resolves a selector against a device's type/location synchronously,
1139
- * off the request path (D49). Empty for a device the hub has never heard of.
1140
- */
1141
- deviceMetaMirror = new Map();
1142
- /** Parent of a device: the persisted mirror first (covers forked devices),
1143
- * falling back to the live hub registry (covers a hub-local device before the
1144
- * first mirror warm). null when top-level or unknown. */
1145
- parentOfDevice(deviceId) {
1146
- const mirrored = this.deviceParentMirror.get(deviceId);
1147
- if (mirrored !== undefined)
1148
- return mirrored;
1149
- return this.deviceRegistry.getById(deviceId)?.parentDeviceId ?? null;
1150
- }
1141
+ //
1142
+ // The mirror itself, and the rule that decides how much of the fleet one
1143
+ // event may re-read, live in `device-meta-mirror.ts` — with the 4 904-call /
1144
+ // 4 987 368-row boot census that made the rule necessary.
1145
+ deviceMirror;
1151
1146
  /** Persisted `DeviceType` string of a device, or null when unknown. Mirror
1152
1147
  * first (covers forked devices), then the live hub registry. */
1153
- getPersistedType = (deviceId) => {
1154
- const mirrored = this.deviceMetaMirror.get(deviceId);
1155
- if (mirrored !== undefined)
1156
- return mirrored.type;
1157
- return this.deviceRegistry.getById(deviceId)?.type ?? null;
1158
- };
1148
+ getPersistedType = (deviceId) => this.deviceMirror.typeOf(deviceId);
1159
1149
  /** Persisted operator `location` label of a device, or null when unset/unknown. */
1160
- getPersistedLocation = (deviceId) => {
1161
- const mirrored = this.deviceMetaMirror.get(deviceId);
1162
- if (mirrored !== undefined)
1163
- return mirrored.location;
1164
- return this.deviceRegistry.getById(deviceId)?.location ?? null;
1165
- };
1150
+ getPersistedLocation = (deviceId) => this.deviceMirror.locationOf(deviceId);
1166
1151
  /**
1167
1152
  * The whole persisted fleet, slim — id + type + location + parentDeviceId.
1168
1153
  * Fuels the FLEET-wide selector expansion (response projection + `auth.me`
1169
1154
  * counts). Read synchronously off the mirror, never a per-call DB query.
1170
1155
  */
1171
- getPersistedDeviceList = () => {
1172
- const out = [];
1173
- for (const [id, m] of this.deviceMetaMirror) {
1174
- out.push({
1175
- id,
1176
- type: m.type,
1177
- location: m.location,
1178
- parentDeviceId: this.deviceParentMirror.get(id) ?? null,
1179
- });
1180
- }
1181
- return out;
1182
- };
1156
+ getPersistedDeviceList = () => this.deviceMirror.list();
1183
1157
  /**
1184
1158
  * Ancestor chain (parent, grandparent, …) of a device, bounded to 8 hops
1185
1159
  * (defence-in-depth against a corrupt registry cycle). Synchronous — it is
@@ -1187,81 +1161,31 @@ class AddonRegistryService {
1187
1161
  * a FORKED camera covers its accessory children. Empty for a top-level device
1188
1162
  * or one the hub has never heard of.
1189
1163
  */
1190
- getPersistedAncestors = (deviceId) => {
1191
- const out = [];
1192
- let current = deviceId;
1193
- for (let hop = 0; hop < 8; hop++) {
1194
- const parent = this.parentOfDevice(current);
1195
- if (parent == null || parent === current)
1196
- break;
1197
- out.push(parent);
1198
- current = parent;
1199
- }
1200
- return out;
1201
- };
1202
- /** One full-fleet rebuild in flight, at most one queued behind it. Every
1203
- * event below asks for the SAME total rebuild, so running it once per event
1204
- * was ~1 000 rebuilds of a 974-row mirror on a boot — each one a 625 KB read
1205
- * and parse on hub-main's event loop. No timer: the first event still
1206
- * refreshes immediately, because this mirror backs scope enforcement.
1207
- * See `single-flight-refresh.ts`. */
1208
- deviceMirrorGate = (0, single_flight_refresh_js_1.createSingleFlightRefresh)(() => this.refreshDeviceParentMirror());
1209
- /** Subscribe the mirror to every device-meta lifecycle event, and warm it once
1210
- * the addon set (device-manager included) is up. */
1164
+ getPersistedAncestors = (deviceId) => this.deviceMirror.ancestorsOf(deviceId);
1165
+ /**
1166
+ * Subscribe the mirror to every device-meta lifecycle event, and warm it once
1167
+ * the addon set (device-manager included) is up.
1168
+ *
1169
+ * The device events ask for a SCOPED refresh — the one device they name, or
1170
+ * nothing at all when they name a field the mirror does not hold.
1171
+ * `SystemAddonsReady` is the only fleet-wide read, and it is also the D8
1172
+ * reconcile: whatever a dropped event would have left stale, the warm
1173
+ * repairs.
1174
+ */
1211
1175
  wireDeviceParentMirror() {
1212
- const refresh = () => {
1213
- void this.deviceMirrorGate.request();
1214
- };
1215
1176
  for (const category of [
1216
1177
  types_1.EventCategory.DeviceMetaChanged,
1217
1178
  types_1.EventCategory.DeviceRegistered,
1218
1179
  types_1.EventCategory.DeviceUnregistered,
1219
1180
  types_1.EventCategory.DeviceProvisioned,
1220
- types_1.EventCategory.SystemAddonsReady,
1221
1181
  ]) {
1222
- this.eventBusService.subscribe({ category }, refresh);
1223
- }
1224
- }
1225
- /** Rebuild the parent mirror from the device-manager's persisted fleet
1226
- * (`listAll`, slim projection — no config blob). Off the request path; a
1227
- * failed read KEEPS the previous mirror (D49 — a read that fails changes
1228
- * nothing, and must never look like an unbind that destroys inheritance). */
1229
- async refreshDeviceParentMirror() {
1230
- try {
1231
- const api = this.getBrokerApi();
1232
- const rows = await api.deviceManager.listAll.query({ projection: 'slim' });
1233
- if (!Array.isArray(rows))
1234
- return;
1235
- const nextParents = new Map();
1236
- const nextMeta = new Map();
1237
- for (const row of rows) {
1238
- if (row === null || typeof row !== 'object')
1239
- continue;
1240
- const id = Reflect.get(row, 'id');
1241
- if (typeof id !== 'number')
1242
- continue;
1243
- const parent = Reflect.get(row, 'parentDeviceId');
1244
- if (typeof parent === 'number')
1245
- nextParents.set(id, parent);
1246
- const type = Reflect.get(row, 'type');
1247
- const location = Reflect.get(row, 'location');
1248
- nextMeta.set(id, {
1249
- type: typeof type === 'string' ? type : '',
1250
- location: typeof location === 'string' ? location : null,
1251
- });
1252
- }
1253
- this.deviceParentMirror.clear();
1254
- for (const [k, v] of nextParents)
1255
- this.deviceParentMirror.set(k, v);
1256
- this.deviceMetaMirror.clear();
1257
- for (const [k, v] of nextMeta)
1258
- this.deviceMetaMirror.set(k, v);
1259
- }
1260
- catch (err) {
1261
- this.logger.debug('device-parent mirror refresh failed — keeping previous', {
1262
- meta: { error: (0, types_1.errMsg)(err) },
1182
+ this.eventBusService.subscribe({ category }, (event) => {
1183
+ this.deviceMirror.onDeviceEvent(event.data);
1263
1184
  });
1264
1185
  }
1186
+ this.eventBusService.subscribe({ category: types_1.EventCategory.SystemAddonsReady }, () => {
1187
+ void this.deviceMirror.refreshAll();
1188
+ });
1265
1189
  }
1266
1190
  /** Load persisted collection disabled-lists from settings-store into the registry */
1267
1191
  loadCollectionPreferences() {