@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,634 @@
1
+ "use strict";
2
+ /**
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.
57
+ *
58
+ * ## The number this exists to explain
59
+ *
60
+ * `FleetReadCensus` (`packages/system/src/builtins/device-manager/fleet-read-census.ts`)
61
+ * measured `deviceManager.listAll` at **4 960 calls in a two-minute boot
62
+ * window**, ~1 017 rows each. It attributes the ADDONS correctly (~64 calls in
63
+ * total, carried as data over the cap channel) and says **nothing** about the
64
+ * other 4 900 - by construction: it lives in the row store and can only read
65
+ * the local JS stack, and for a call that arrived over the wire every frame
66
+ * above it is the same generic dispatcher regardless of who called.
67
+ *
68
+ * The HTTP layer is the one place that still holds the caller's identity:
69
+ * source IP, `User-Agent`, and the principal the bearer resolved to. So this
70
+ * census counts there.
71
+ *
72
+ * Two client-side fixes (admin-ui `GlobalSearch`, embed `EmbedGridPage`) moved
73
+ * the number from 4 888 to 4 960 - i.e. not at all. Guessing the next most
74
+ * plausible caller is exactly what this repo has already got wrong twice at
75
+ * half a day each. An attribution is a measurement or it is a guess.
76
+ *
77
+ * ## Reading the NEGATIVE - an excluded plane is a result
78
+ *
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".
84
+ *
85
+ * A census that collected nothing still reports. Silence after an arm is
86
+ * indistinguishable from a census that never armed.
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
+ *
96
+ * ## Cost when disarmed
97
+ *
98
+ * {@link HttpRequestCensus.armed} is a plain boolean FIELD, not a clock
99
+ * comparison. Every caller checks it first and returns - no `Date.now()`, no
100
+ * string, no allocation. This sits on the hub's tRPC entry path at ~41
101
+ * requests/second; a diagnostic that costs something while switched off is a
102
+ * tax nobody remembers enabling.
103
+ *
104
+ * The window therefore closes on a TIMER rather than on a clock read taken per
105
+ * request. Stale timers are neutralised by a generation counter instead of
106
+ * being cleared, so no timer handle has to be stored or typed.
107
+ */
108
+ Object.defineProperty(exports, "__esModule", { value: true });
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;
111
+ exports.shortenUserAgent = shortenUserAgent;
112
+ exports.parseTrpcProcedures = parseTrpcProcedures;
113
+ /** Route prefix the tRPC plugin is registered under (`main.ts`). */
114
+ exports.TRPC_URL_PREFIX = '/trpc/';
115
+ /**
116
+ * Longest window the census may be armed for.
117
+ *
118
+ * Thirty minutes rather than the ten `FleetReadCensus` allows, because the
119
+ * measurement this instrument exists for spans a RESTART: the operator arms
120
+ * it, restarts the hub, and the boot storm has to land inside the window that
121
+ * was already running. Ten minutes is not enough room for a container
122
+ * recreation plus a cold boot.
123
+ */
124
+ exports.MAX_WINDOW_MS = 30 * 60_000;
125
+ /** Shortest useful window. Anything below this cannot contain a boot. */
126
+ exports.MIN_WINDOW_MS = 1_000;
127
+ /** Default cadence of the aggregated report line. */
128
+ exports.DEFAULT_REPORT_EVERY_MS = 30_000;
129
+ /**
130
+ * Floor on the report cadence.
131
+ *
132
+ * The report is ONE aggregated line. At the measured rate a per-request line
133
+ * would be 41 lines a second, which is itself an incident - and a cadence an
134
+ * operator could set to 100 ms would reproduce that with an aggregate.
135
+ */
136
+ exports.MIN_REPORT_EVERY_MS = 5_000;
137
+ /**
138
+ * Bound on distinct `(procedure, ua, ip, principal)` groups held in memory.
139
+ *
140
+ * IPs and user-agents are attacker-influenced: a client rotating either would
141
+ * otherwise grow the map without limit inside an armed window. Overflow is
142
+ * COUNTED, never dropped silently - the totals stay exact, which is what the
143
+ * negative proof rests on.
144
+ */
145
+ exports.MAX_GROUPS = 500;
146
+ /**
147
+ * Bound on distinct procedure names. The router's procedure set is closed and
148
+ * far below this; the bound exists so a garbage path cannot grow the map.
149
+ * Names beyond it fold into {@link PROCEDURE_OVERFLOW} rather than vanishing.
150
+ */
151
+ exports.MAX_PROCEDURES = 500;
152
+ /** User-agent prefix kept in a group key. Full UA strings are long and their
153
+ * tail is build metadata that splits one client into many rows. */
154
+ exports.USER_AGENT_MAX_CHARS = 80;
155
+ /** Bound on procedures counted from one batched URL. tRPC's own `maxBatchSize`
156
+ * guards the router; this guards the census against a URL that never reaches
157
+ * a procedure at all. */
158
+ exports.MAX_BATCH_PROCEDURES = 200;
159
+ /** Synthetic name for batch entries beyond {@link MAX_BATCH_PROCEDURES}. */
160
+ exports.BATCH_OVERFLOW_PROCEDURE = '(batch-overflow)';
161
+ /** Synthetic name for procedures beyond {@link MAX_PROCEDURES}. */
162
+ exports.PROCEDURE_OVERFLOW = '(procedure-overflow)';
163
+ /** Placeholder used when a request carries no such signal. Never blank: an
164
+ * empty field reads as a logging defect rather than as an absent header. */
165
+ exports.UNKNOWN = 'unknown';
166
+ /** Group-key field separator. A character that cannot appear in a tRPC
167
+ * procedure path, so two different tuples can never collide into one row. */
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
+ }
186
+ function defaultSchedule(fn, ms) {
187
+ // `unref` so an armed census never holds the process open at shutdown.
188
+ setTimeout(fn, ms).unref();
189
+ }
190
+ /**
191
+ * Truncate a user-agent to a comparable prefix.
192
+ *
193
+ * Exported because the truncation is part of the group KEY: a spec that builds
194
+ * an expected key by hand must use the same rule, or it pins the wrong thing.
195
+ */
196
+ function shortenUserAgent(ua) {
197
+ if (ua === null)
198
+ return exports.UNKNOWN;
199
+ const trimmed = ua.trim();
200
+ if (trimmed.length === 0)
201
+ return exports.UNKNOWN;
202
+ if (trimmed.length <= exports.USER_AGENT_MAX_CHARS)
203
+ return trimmed;
204
+ return `${trimmed.slice(0, exports.USER_AGENT_MAX_CHARS)}~`;
205
+ }
206
+ /**
207
+ * The procedures one tRPC HTTP request invokes.
208
+ *
209
+ * ## Why this is not `url.split(',')`
210
+ *
211
+ * tRPC splits the path on `,` **only when `batch=1`**, and only for the JSON
212
+ * content-type handler; `multipart/form-data` and `application/octet-stream`
213
+ * are always single-call, and a non-batched path containing a comma is ONE
214
+ * procedure name. Counting a batch as one call undercounts by the batch factor
215
+ * - in exactly the direction that would clear an innocent transport - and
216
+ * splitting a non-batch path overcounts. Both rules are mirrored here
217
+ * deliberately from `@trpc/server`'s `jsonContentTypeHandler.parse`, and both
218
+ * are pinned by spec.
219
+ *
220
+ * Returns `[]` for a URL that is not under the tRPC prefix, and for the bare
221
+ * prefix with no path.
222
+ */
223
+ function parseTrpcProcedures(url, contentType) {
224
+ const queryAt = url.indexOf('?');
225
+ const pathname = queryAt === -1 ? url : url.slice(0, queryAt);
226
+ const query = queryAt === -1 ? '' : url.slice(queryAt + 1);
227
+ if (!pathname.startsWith(exports.TRPC_URL_PREFIX))
228
+ return [];
229
+ // The plugin route is `/trpc/:path` - one segment. Anything after a further
230
+ // `/` is not part of the procedure path.
231
+ const rest = pathname.slice(exports.TRPC_URL_PREFIX.length);
232
+ const slashAt = rest.indexOf('/');
233
+ const rawPath = slashAt === -1 ? rest : rest.slice(0, slashAt);
234
+ if (rawPath.length === 0)
235
+ return [];
236
+ const decoded = decodePathSafely(rawPath);
237
+ if (!isBatchCall(query, contentType)) {
238
+ const single = decoded.trim();
239
+ return single.length === 0 ? [] : [single];
240
+ }
241
+ const out = [];
242
+ let overflowed = false;
243
+ for (const part of decoded.split(',')) {
244
+ const name = part.trim();
245
+ if (name.length === 0)
246
+ continue;
247
+ if (out.length >= exports.MAX_BATCH_PROCEDURES) {
248
+ overflowed = true;
249
+ continue;
250
+ }
251
+ out.push(name);
252
+ }
253
+ if (overflowed)
254
+ out.push(exports.BATCH_OVERFLOW_PROCEDURE);
255
+ return out;
256
+ }
257
+ /** `decodeURIComponent` throws on a malformed escape. A garbage path is still
258
+ * a request that arrived, so it is counted under its raw text rather than
259
+ * dropped - a dropped request is a hole in the total the negative rests on. */
260
+ function decodePathSafely(raw) {
261
+ try {
262
+ return decodeURIComponent(raw);
263
+ }
264
+ catch {
265
+ return raw;
266
+ }
267
+ }
268
+ /**
269
+ * `batch=1` in the query string, and a content-type that can batch.
270
+ *
271
+ * The two non-JSON handlers hard-code `isBatchCall: false` regardless of the
272
+ * query string, so honouring `batch=1` for them would split a procedure name
273
+ * that legitimately contains a comma.
274
+ */
275
+ function isBatchCall(query, contentType) {
276
+ if (!hasBatchFlag(query))
277
+ return false;
278
+ if (typeof contentType !== 'string')
279
+ return true;
280
+ const lower = contentType.toLowerCase();
281
+ if (lower.startsWith('multipart/form-data'))
282
+ return false;
283
+ if (lower.startsWith('application/octet-stream'))
284
+ return false;
285
+ return true;
286
+ }
287
+ function hasBatchFlag(query) {
288
+ if (query.length === 0)
289
+ return false;
290
+ for (const pair of query.split('&')) {
291
+ if (pair === 'batch=1')
292
+ return true;
293
+ }
294
+ return false;
295
+ }
296
+ /**
297
+ * Armed-window counter for tRPC requests arriving over HTTP.
298
+ *
299
+ * Disarmed it is one boolean read at every call site and nothing else.
300
+ */
301
+ class HttpRequestCensus {
302
+ now;
303
+ schedule;
304
+ /** The ONLY thing a disarmed request path reads. */
305
+ isArmed = false;
306
+ /** Stamps every scheduled tick. A tick whose stamp is stale belongs to a
307
+ * window that was re-armed or disarmed, and does nothing. */
308
+ generation = 0;
309
+ armedAt = 0;
310
+ closedAt = 0;
311
+ currentWindowMs = 0;
312
+ currentReportEveryMs = exports.DEFAULT_REPORT_EVERY_MS;
313
+ httpRequests = 0;
314
+ batchedRequests = 0;
315
+ procedureCalls = 0;
316
+ wsConnections = 0;
317
+ wsMessages = 0;
318
+ subscriptions = 0;
319
+ subscriptionStops = 0;
320
+ unattributedCalls = 0;
321
+ planeCalls = zeroPlaneCounts();
322
+ byProcedure = new Map();
323
+ byGroup = new Map();
324
+ logger = null;
325
+ constructor(options = {}) {
326
+ this.now = options.now ?? Date.now;
327
+ this.schedule = options.schedule ?? defaultSchedule;
328
+ }
329
+ /** The report sink. Absent until boot wires it; a census with no logger
330
+ * still counts and still answers `snapshot()`. */
331
+ setLogger(logger) {
332
+ this.logger = logger;
333
+ }
334
+ get armed() {
335
+ return this.isArmed;
336
+ }
337
+ /** Epoch ms the current window closes at. 0 when disarmed. */
338
+ get armedUntilMs() {
339
+ return this.isArmed ? this.armedAt + this.currentWindowMs : 0;
340
+ }
341
+ /**
342
+ * Arm for `windowMs`, clamped to [{@link MIN_WINDOW_MS}, {@link MAX_WINDOW_MS}].
343
+ *
344
+ * Re-arming CLEARS the counts and restarts the window: two overlapping
345
+ * measurements in one table is a table nobody can divide by a duration.
346
+ */
347
+ arm(windowMs, reportEveryMs = exports.DEFAULT_REPORT_EVERY_MS) {
348
+ const clampedWindow = clamp(windowMs, exports.MIN_WINDOW_MS, exports.MAX_WINDOW_MS);
349
+ const clampedReport = clamp(reportEveryMs, exports.MIN_REPORT_EVERY_MS, clampedWindow);
350
+ this.reset();
351
+ this.generation += 1;
352
+ this.isArmed = true;
353
+ this.armedAt = this.now();
354
+ this.closedAt = 0;
355
+ this.currentWindowMs = clampedWindow;
356
+ this.currentReportEveryMs = clampedReport;
357
+ this.scheduleTick(this.generation);
358
+ }
359
+ /**
360
+ * Close the window now and emit the final report.
361
+ *
362
+ * The counts SURVIVE - a window may be read as many times as the operator
363
+ * likes after it closed, and re-arming in order to read would throw away
364
+ * exactly the numbers being asked for.
365
+ */
366
+ disarm(reason) {
367
+ if (!this.isArmed)
368
+ return;
369
+ this.isArmed = false;
370
+ this.closedAt = this.now();
371
+ this.generation += 1;
372
+ this.report(reason);
373
+ }
374
+ /**
375
+ * Count one HTTP request.
376
+ *
377
+ * Callers check {@link armed} FIRST so nothing is built for a disarmed
378
+ * census; the guard is repeated here so a request already in flight when the
379
+ * window closed cannot land in a window it does not belong to.
380
+ */
381
+ observeHttpRequest(observation) {
382
+ if (!this.isArmed)
383
+ return;
384
+ if (observation.procedures.length === 0)
385
+ return;
386
+ this.httpRequests += 1;
387
+ if (observation.procedures.length > 1)
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;
403
+ const userAgent = shortenUserAgent(observation.userAgent);
404
+ const ip = observation.ip ?? exports.UNKNOWN;
405
+ const { plane, kind, principal } = observation;
406
+ for (const procedure of observation.procedures) {
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);
415
+ const group = this.byGroup.get(key);
416
+ if (group !== undefined) {
417
+ if (kind === 'subscription')
418
+ group.subscriptions += 1;
419
+ else
420
+ group.calls += 1;
421
+ continue;
422
+ }
423
+ if (this.byGroup.size >= exports.MAX_GROUPS) {
424
+ this.unattributedCalls += 1;
425
+ continue;
426
+ }
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
+ });
436
+ }
437
+ }
438
+ /**
439
+ * Count one tRPC WebSocket connection opening.
440
+ *
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.
444
+ */
445
+ observeWsConnection() {
446
+ if (!this.isArmed)
447
+ return;
448
+ this.wsConnections += 1;
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
+ }
468
+ /** Everything the window measured, busiest first. */
469
+ snapshot(limit = exports.MAX_GROUPS) {
470
+ const elapsedMs = this.elapsedMs();
471
+ const perMin = (calls) => elapsedMs === 0 ? 0 : Math.round((calls * 60_000) / elapsedMs);
472
+ const procedures = [...this.byProcedure.entries()]
473
+ .map(([procedure, count]) => ({
474
+ procedure,
475
+ calls: count.calls,
476
+ planes: freezePlaneCounts(count.planes),
477
+ subscriptions: count.subscriptions,
478
+ perMin: perMin(count.calls),
479
+ }))
480
+ .toSorted((a, b) => b.calls - a.calls);
481
+ const groups = [...this.byGroup.values()]
482
+ .map((group) => ({
483
+ plane: group.plane,
484
+ procedure: group.procedure,
485
+ userAgent: group.userAgent,
486
+ ip: group.ip,
487
+ principal: group.principal,
488
+ calls: group.calls,
489
+ subscriptions: group.subscriptions,
490
+ perMin: perMin(group.calls),
491
+ }))
492
+ .toSorted((a, b) => b.calls + b.subscriptions - (a.calls + a.subscriptions));
493
+ return {
494
+ armed: this.isArmed,
495
+ elapsedMs,
496
+ windowMs: this.currentWindowMs,
497
+ armedUntilMs: this.armedUntilMs,
498
+ httpRequests: this.httpRequests,
499
+ batchedRequests: this.batchedRequests,
500
+ procedureCalls: this.procedureCalls,
501
+ planes: freezePlaneCounts(this.planeCalls),
502
+ planesExplainTotal: sumPlaneCounts(this.planeCalls) === this.procedureCalls,
503
+ wsConnections: this.wsConnections,
504
+ wsMessages: this.wsMessages,
505
+ subscriptions: this.subscriptions,
506
+ subscriptionStops: this.subscriptionStops,
507
+ distinctGroups: this.byGroup.size,
508
+ unattributedCalls: this.unattributedCalls,
509
+ procedures: procedures.slice(0, limit),
510
+ groups: groups.slice(0, limit),
511
+ };
512
+ }
513
+ /**
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.
520
+ *
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.
525
+ */
526
+ report(phase) {
527
+ const logger = this.logger;
528
+ if (logger === null)
529
+ return;
530
+ const snap = this.snapshot();
531
+ logger.info('transport census', {
532
+ meta: {
533
+ phase,
534
+ armed: snap.armed,
535
+ elapsedMs: snap.elapsedMs,
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,
544
+ httpRequests: snap.httpRequests,
545
+ batchedRequests: snap.batchedRequests,
546
+ wsConnections: snap.wsConnections,
547
+ wsMessages: snap.wsMessages,
548
+ distinctGroups: snap.distinctGroups,
549
+ unattributedCalls: snap.unattributedCalls,
550
+ procedures: snap.procedures.slice(0, REPORTED_PROCEDURES),
551
+ top: snap.groups.slice(0, REPORTED_GROUPS).map((group) => ({
552
+ plane: group.plane,
553
+ procedure: group.procedure,
554
+ ua: group.userAgent,
555
+ ip: group.ip,
556
+ principal: group.principal,
557
+ calls: group.calls,
558
+ subscriptions: group.subscriptions,
559
+ perMin: group.perMin,
560
+ })),
561
+ },
562
+ });
563
+ }
564
+ countProcedure(procedure, plane, kind) {
565
+ const existing = this.byProcedure.get(procedure);
566
+ if (existing !== undefined) {
567
+ bumpCount(existing, plane, kind);
568
+ return;
569
+ }
570
+ if (this.byProcedure.size >= exports.MAX_PROCEDURES) {
571
+ const overflow = this.byProcedure.get(exports.PROCEDURE_OVERFLOW) ?? newCount();
572
+ bumpCount(overflow, plane, kind);
573
+ this.byProcedure.set(exports.PROCEDURE_OVERFLOW, overflow);
574
+ return;
575
+ }
576
+ const fresh = newCount();
577
+ bumpCount(fresh, plane, kind);
578
+ this.byProcedure.set(procedure, fresh);
579
+ }
580
+ elapsedMs() {
581
+ if (this.armedAt === 0)
582
+ return 0;
583
+ const end = this.isArmed ? this.now() : this.closedAt;
584
+ return Math.max(0, end - this.armedAt);
585
+ }
586
+ reset() {
587
+ this.byProcedure.clear();
588
+ this.byGroup.clear();
589
+ this.httpRequests = 0;
590
+ this.batchedRequests = 0;
591
+ this.procedureCalls = 0;
592
+ this.wsConnections = 0;
593
+ this.wsMessages = 0;
594
+ this.subscriptions = 0;
595
+ this.subscriptionStops = 0;
596
+ this.unattributedCalls = 0;
597
+ this.planeCalls = zeroPlaneCounts();
598
+ }
599
+ scheduleTick(generation) {
600
+ this.schedule(() => {
601
+ if (generation !== this.generation || !this.isArmed)
602
+ return;
603
+ if (this.now() - this.armedAt >= this.currentWindowMs) {
604
+ this.disarm('window-closed');
605
+ return;
606
+ }
607
+ this.report('interval');
608
+ this.scheduleTick(generation);
609
+ }, this.currentReportEveryMs);
610
+ }
611
+ }
612
+ exports.HttpRequestCensus = HttpRequestCensus;
613
+ /** Per-procedure rows carried on one report line. The router's procedure set
614
+ * is small; this is a guard against a garbage path, not a real cut. */
615
+ const REPORTED_PROCEDURES = 40;
616
+ /** Caller groups carried on one report line. Enough to name a culprit,
617
+ * bounded so one line stays a line. */
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
+ }
630
+ function clamp(value, min, max) {
631
+ if (!Number.isFinite(value))
632
+ return min;
633
+ return Math.min(Math.max(value, min), max);
634
+ }
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ /**
3
+ * Process-wide holder for the HTTP request census.
4
+ *
5
+ * Two call sites that never meet need the SAME instance: `main.ts` counts into
6
+ * it from the tRPC context factory and the WS handler, and the `system` cap
7
+ * provider - which `trpc.router.ts` rebuilds PER REQUEST - arms and reads it.
8
+ * A census built inside that per-request factory would count one request and
9
+ * be collected, which is the shape of an instrument that reports zero forever.
10
+ *
11
+ * Same idiom as `lifecycle-runner.singleton.ts`, minus the init step: this one
12
+ * has no dependencies, so the first reader creates it disarmed.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.getHttpRequestCensus = getHttpRequestCensus;
16
+ exports.__resetHttpRequestCensusForTests = __resetHttpRequestCensusForTests;
17
+ const http_request_census_js_1 = require("./http-request-census.js");
18
+ let instance = null;
19
+ /** The process-wide census. Created disarmed on first use. */
20
+ function getHttpRequestCensus() {
21
+ instance ??= new http_request_census_js_1.HttpRequestCensus();
22
+ return instance;
23
+ }
24
+ /** Test-only: drop the instance so a spec starts from a disarmed census. */
25
+ function __resetHttpRequestCensusForTests() {
26
+ instance = null;
27
+ }