@camstack/server 1.2.175 → 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,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
@@ -66,10 +66,16 @@ const server_upload_1 = require("./api/server-upload");
66
66
  const sse_no_compression_js_1 = require("./api/sse-no-compression.js");
67
67
  const precompressed_asset_js_1 = require("./api/static/precompressed-asset.js");
68
68
  const spa_static_1 = require("./api/static/spa-static");
69
+ const cap_providers_1 = require("./api/core/cap-providers");
70
+ const logging_settings_1 = require("./api/core/logging-settings");
71
+ const request_census_settings_1 = require("./api/core/request-census-settings");
69
72
  const core_cap_bridge_1 = require("./api/trpc/core-cap-bridge");
73
+ const http_request_census_hook_1 = require("./api/trpc/http-request-census-hook");
74
+ const http_request_census_singleton_1 = require("./api/trpc/http-request-census.singleton");
70
75
  const trpc_context_1 = require("./api/trpc/trpc.context");
71
76
  const trpc_router_1 = require("./api/trpc/trpc.router");
72
77
  const trpc_error_principal_1 = require("./api/trpc/trpc-error-principal");
78
+ const ws_request_census_1 = require("./api/trpc/ws-request-census");
73
79
  const addon_route_jwt_gate_js_1 = require("./auth/addon-route-jwt-gate.js");
74
80
  const session_cookie_js_1 = require("./auth/session-cookie.js");
75
81
  const boot_config_1 = require("./boot/boot-config");
@@ -487,6 +493,12 @@ async function bootstrap() {
487
493
  catch (err) {
488
494
  console.warn('[bootstrap] device-name cache seed skipped:', err instanceof Error ? err.message : err);
489
495
  }
496
+ // The process-wide HTTP request census. Disarmed here and for the rest of
497
+ // this boot unless `restore()` (below, just before `listen`) finds a window
498
+ // an operator armed earlier. The logger is attached now so a restored census
499
+ // has somewhere to report before the first request arrives.
500
+ const httpRequestCensus = (0, http_request_census_singleton_1.getHttpRequestCensus)();
501
+ httpRequestCensus.setLogger(loggingService.createLogger('tRPC'));
490
502
  try {
491
503
  const authService = app.get(auth_service_1.AuthService);
492
504
  // Normally already built and bridged onto the mesh in `beforeAddonBoot`
@@ -506,11 +518,19 @@ async function bootstrap() {
506
518
  prefix: '/trpc',
507
519
  trpcOptions: {
508
520
  router: appRouter,
509
- createContext: ({ req }) => (0, trpc_context_1.createTrpcContext)(req, authService, addonRegistry, shareTokenService,
510
- // A bearer refused for NOT being an API credential never reaches a
511
- // procedure, so `onError` below never sees it — the refusal would
512
- // be silent without this. Same reason `gateAddonJwt` logs (D103).
513
- app.get(logging_service_1.LoggingService).createLogger('tRPC')),
521
+ createContext: async ({ req }) => {
522
+ const trpcCtx = await (0, trpc_context_1.createTrpcContext)(req, authService, addonRegistry, shareTokenService,
523
+ // A bearer refused for NOT being an API credential never reaches a
524
+ // procedure, so `onError` below never sees it — the refusal would
525
+ // be silent without this. Same reason `gateAddonJwt` logs (D103).
526
+ app.get(logging_service_1.LoggingService).createLogger('tRPC'));
527
+ // WHO called, counted here because this is the first point at which
528
+ // a principal exists AND the only one tRPC runs exactly once per
529
+ // HTTP request (batched or not). Disarmed this is a boolean read and
530
+ // a return — see `http-request-census-hook.ts`.
531
+ (0, http_request_census_hook_1.recordTrpcHttpRequest)(httpRequestCensus, req, trpcCtx.user);
532
+ return trpcCtx;
533
+ },
514
534
  onError: ({ path: trpcPath, error, ctx, }) => {
515
535
  const trpcLogger = app.get(logging_service_1.LoggingService).createLogger('tRPC');
516
536
  trpcLogger.warn('tRPC error', {
@@ -1068,10 +1088,28 @@ async function bootstrap() {
1068
1088
  concurrencyLimit: 10,
1069
1089
  },
1070
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
+ });
1071
1102
  (0, ws_1.applyWSSHandler)({
1072
1103
  wss,
1073
1104
  router: appRouter,
1074
- createContext: (opts) => (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;
1112
+ },
1075
1113
  onError: ({ path: trpcPath, error, ctx, }) => {
1076
1114
  const trpcLogger = app.get(logging_service_1.LoggingService).createLogger('tRPC:ws');
1077
1115
  trpcLogger.warn('tRPC error', {
@@ -1303,6 +1341,34 @@ async function bootstrap() {
1303
1341
  console.error('[bootstrap] Failed to set up viewer UI static serving:', err);
1304
1342
  }
1305
1343
  };
1344
+ // Establish the logging mirror and re-arm any diagnostic window that was
1345
+ // armed BEFORE this boot.
1346
+ //
1347
+ // Deliberately here, immediately before `listen`: the tRPC plugin is
1348
+ // registered long before this point but the socket is not open yet, so the
1349
+ // census is already counting when the first client reconnects — which is
1350
+ // the entire window the boot storm lives in. Awaited (one KV read) rather
1351
+ // than fired and forgotten, because "it will probably finish in time" is not
1352
+ // a property a measurement can rest on. It must never be the reason a hub
1353
+ // fails to boot, hence the catch — and a restore that fails leaves the
1354
+ // mirror at its default rather than inventing a level (D49).
1355
+ try {
1356
+ const settingsStore = (0, cap_providers_1.buildSettingsStoreGateway)(capabilityRegistry);
1357
+ const loggingLogger = loggingService.createLogger('logging-settings');
1358
+ await new logging_settings_1.LoggingSettingsService({
1359
+ store: settingsStore,
1360
+ gate: (0, system_1.getLoggingGate)(),
1361
+ requestCensus: new request_census_settings_1.RequestCensusService({
1362
+ census: httpRequestCensus,
1363
+ store: settingsStore,
1364
+ logger: loggingLogger,
1365
+ }),
1366
+ logger: loggingLogger,
1367
+ }).restore();
1368
+ }
1369
+ catch (censusErr) {
1370
+ console.warn('[bootstrap] logging settings restore skipped:', censusErr instanceof Error ? censusErr.message : censusErr);
1371
+ }
1306
1372
  try {
1307
1373
  const listenHost = (0, system_1.allFamiliesListenHost)(host).host;
1308
1374
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/server",
3
- "version": "1.2.175",
3
+ "version": "1.2.177",
4
4
  "private": false,
5
5
  "files": [
6
6
  "dist",