@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.
@@ -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;