@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.
@@ -20,14 +20,27 @@
20
20
  * a rule against it. Each field decides for itself: absent → keep, `null` →
21
21
  * clear, value → set.
22
22
  *
23
- * ## Hierarchy: cluster → node, most specific wins
23
+ * ## Hierarchy: cluster → node → component, most specific wins
24
24
  *
25
- * A node's own level wins over the cluster's; with neither set the hub emits
26
- * at {@link DEFAULT_LOG_LEVEL}. Both `effective` AND `explicit` are returned,
27
- * because collapsing them is the defect: an operator who clears an override
28
- * believing they are clearing an inherited value has no way back. The
29
- * `component` layer is declared in the schema and not resolvable yet — it is a
30
- * later slice of the same plan.
25
+ * A node's own level wins over the cluster's, and a COMPONENT — a declared log
26
+ * channel such as `stream-broker.webrtc` — wins over both. With none set the
27
+ * hub emits at {@link DEFAULT_LOG_LEVEL}. Both `effective` AND `explicit` are
28
+ * returned, because collapsing them is the defect: an operator who clears an
29
+ * override believing they are clearing an inherited value has no way back.
30
+ *
31
+ * A component level is CLUSTER-WIDE. There is no per-node component map and
32
+ * there must not be one: a channel means the same thing wherever the addon
33
+ * that declared it runs, and a second per-node copy would be the knob that
34
+ * disagrees with the first (D62).
35
+ *
36
+ * ## Channels are DECLARED by addons; only the VALUE lives here
37
+ *
38
+ * Which channels exist is knowledge only the owning addon has, and it arrives
39
+ * through the `log-channels` capability ({@link LogChannelPlane}). A central
40
+ * list maintained by hand rots at the first addition, invisibly. What this
41
+ * document owns is which channel is armed, for which cameras, until when —
42
+ * and that stays singular, because two authorities over one value is the
43
+ * defect the plan behind this file exists to remove.
31
44
  *
32
45
  * ## The hot path reads the MIRROR, and a failed read changes nothing
33
46
  *
@@ -48,11 +61,16 @@
48
61
  * over the window (D245).
49
62
  */
50
63
  Object.defineProperty(exports, "__esModule", { value: true });
51
- exports.LoggingSettingsService = exports.HUB_NODE_ID = exports.LOGGING_SETTINGS_KEY = void 0;
64
+ exports.LoggingSettingsService = exports.MAX_CHANNEL_WINDOW_MS = exports.EMPTY_LOG_CHANNEL_PLANE = exports.HUB_NODE_ID = exports.LOGGING_SETTINGS_KEY = void 0;
65
+ exports.buildLogChannelPlane = buildLogChannelPlane;
52
66
  exports.toLoggingSettingsRecord = toLoggingSettingsRecord;
53
67
  exports.resolveLevel = resolveLevel;
54
68
  exports.describeLayers = describeLayers;
55
69
  exports.mergeLevel = mergeLevel;
70
+ exports.validateChannelPatch = validateChannelPatch;
71
+ exports.mergeChannelWindows = mergeChannelWindows;
72
+ exports.liveChannelWindows = liveChannelWindows;
73
+ exports.describeChannelWindows = describeChannelWindows;
56
74
  const types_1 = require("@camstack/types");
57
75
  const system_1 = require("@camstack/system");
58
76
  /** The `system-settings` row this module owns. */
@@ -61,6 +79,63 @@ const SYSTEM_SETTINGS_COLLECTION = 'system-settings';
61
79
  /** The node a hub speaks for when a caller does not name one. */
62
80
  exports.HUB_NODE_ID = 'hub';
63
81
  const LOG_LEVELS = ['debug', 'info', 'warn', 'error'];
82
+ /** A plane that reaches nothing. The shape of a hub with no addon booted yet. */
83
+ exports.EMPTY_LOG_CHANNEL_PLANE = {
84
+ declarations: async () => [],
85
+ apply: async () => { },
86
+ };
87
+ /**
88
+ * The plane over the hub's `CapabilityRegistry`.
89
+ *
90
+ * Every `log-channels` provider is either in-process or an RPC proxy the
91
+ * registry already built for a forked runner or an agent
92
+ * (`moleculer.service.ts` registers one method-per-method), so this reaches
93
+ * the gates over transport that already exists — no new UDS message, no second
94
+ * registry (D3).
95
+ *
96
+ * One provider failing must not silence the others: each is awaited on its
97
+ * own, a failure is reported to `onProviderError` (a branch that drops work
98
+ * logs it), and the remaining providers still get the value.
99
+ */
100
+ function buildLogChannelPlane(source, onProviderError) {
101
+ return {
102
+ declarations: async () => {
103
+ const seen = new Map();
104
+ for (const [addonId, provider] of source.entries()) {
105
+ try {
106
+ for (const descriptor of await provider.list()) {
107
+ // First declaration wins. A duplicate name across addons is a
108
+ // collision the guard refuses at CI time; at runtime the honest
109
+ // move is to keep one rather than show the operator two rows that
110
+ // arm the same gate.
111
+ if (!seen.has(descriptor.name))
112
+ seen.set(descriptor.name, descriptor);
113
+ }
114
+ }
115
+ catch (err) {
116
+ onProviderError?.(addonId, 'list', (0, types_1.errMsg)(err));
117
+ }
118
+ }
119
+ return [...seen.values()].sort((a, b) => a.name.localeCompare(b.name));
120
+ },
121
+ apply: async (windows) => {
122
+ for (const [addonId, provider] of source.entries()) {
123
+ try {
124
+ await provider.apply({ windows });
125
+ }
126
+ catch (err) {
127
+ onProviderError?.(addonId, 'apply', (0, types_1.errMsg)(err));
128
+ }
129
+ }
130
+ },
131
+ };
132
+ }
133
+ /**
134
+ * Ceiling on a channel window, and the same value as `CENSUS_MAX_WINDOW_MS`
135
+ * for the same reason: a diagnostic you can leave on becomes a tax nobody
136
+ * remembers enabling.
137
+ */
138
+ exports.MAX_CHANNEL_WINDOW_MS = 30 * 60_000;
64
139
  class LoggingSettingsService {
65
140
  store;
66
141
  gate;
@@ -68,6 +143,7 @@ class LoggingSettingsService {
68
143
  localNodeId;
69
144
  logger;
70
145
  now;
146
+ channels;
71
147
  constructor(deps) {
72
148
  this.store = deps.store;
73
149
  this.gate = deps.gate;
@@ -75,6 +151,7 @@ class LoggingSettingsService {
75
151
  this.localNodeId = deps.localNodeId ?? exports.HUB_NODE_ID;
76
152
  this.logger = deps.logger;
77
153
  this.now = deps.now ?? Date.now;
154
+ this.channels = deps.channels ?? exports.EMPTY_LOG_CHANNEL_PLANE;
78
155
  }
79
156
  /**
80
157
  * The document as it stands, resolved for `nodeId` (absent = the cluster).
@@ -83,9 +160,9 @@ class LoggingSettingsService {
83
160
  * and, crucially, does not touch the mirror. What the operator sees is
84
161
  * honestly labelled as un-persisted; what the hub does is unchanged.
85
162
  */
86
- async get(scopeNodeId) {
163
+ async get(scopeNodeId, scopeComponent) {
87
164
  const record = await this.read();
88
- return this.describe(record, scopeNodeId ?? null);
165
+ return this.describe(record, scopeNodeId ?? null, scopeComponent ?? null);
89
166
  }
90
167
  /**
91
168
  * Apply a patch. Fields absent from it are untouched.
@@ -95,29 +172,55 @@ class LoggingSettingsService {
95
172
  * must still give the operator a live measurement, and must say so rather
96
173
  * than reporting a durable arm that is not durable.
97
174
  */
98
- async set(patch, scopeNodeId) {
175
+ async set(patch, scopeNodeId, scopeComponent) {
99
176
  await this.applyDiagnostics(patch);
100
177
  const scope = scopeNodeId ?? null;
178
+ const component = scopeComponent ?? null;
101
179
  const stored = await this.read();
102
180
  const levelChanged = patch.level !== undefined;
103
- let persistedLevel = true;
181
+ const channelsChanged = patch.channels !== undefined;
182
+ let persisted = true;
183
+ let next = stored ?? {};
104
184
  if (levelChanged) {
105
- const next = mergeLevel(stored ?? {}, scope, patch.level ?? null, this.now());
106
- persistedLevel = await this.write(next);
185
+ next = mergeLevel(next, scope, component, patch.level ?? null, this.now());
186
+ }
187
+ if (channelsChanged) {
188
+ // Validated BEFORE anything is written: a patch that names an
189
+ // undeclared channel, or narrows a channel whose lines carry no
190
+ // `tags: { deviceId }`, is REFUSED whole. Applying the valid half would
191
+ // leave the operator believing the refused half took, which is the
192
+ // partial-arm defect wearing a different hat.
193
+ const declared = await this.channels.declarations();
194
+ const rejected = validateChannelPatch(patch.channels ?? [], declared);
195
+ if (rejected.length > 0) {
196
+ this.logger?.warn('log channel patch refused - nothing was armed or disarmed', {
197
+ meta: { reasons: rejected },
198
+ });
199
+ throw new Error(`log channel patch refused: ${rejected.join('; ')}`);
200
+ }
201
+ next = mergeChannelWindows(next, patch.channels ?? [], this.now());
202
+ }
203
+ if (levelChanged || channelsChanged) {
204
+ persisted = await this.write(next);
107
205
  // The mirror moves only from a value this call actually produced.
108
206
  this.refreshMirror(next);
207
+ // The gates live in other processes; the document has to reach them or
208
+ // it configures nothing (D62).
209
+ await this.pushChannels(next);
109
210
  this.logger?.info('logging settings written', {
110
211
  meta: {
111
- scope: scope === null ? 'cluster' : 'node',
212
+ scope: component !== null ? 'component' : scope === null ? 'cluster' : 'node',
112
213
  nodeId: scope,
113
- level: patch.level ?? null,
114
- persisted: persistedLevel,
214
+ component,
215
+ level: levelChanged ? (patch.level ?? null) : undefined,
216
+ channels: (patch.channels ?? []).map((c) => `${c.channel}:${c.armMs}`),
217
+ persisted,
115
218
  },
116
219
  });
117
- const state = await this.describe(next, scope);
118
- return { ...state, persisted: state.persisted && persistedLevel };
220
+ const state = await this.describe(next, scope, component);
221
+ return { ...state, persisted: state.persisted && persisted };
119
222
  }
120
- return this.describe(stored, scope);
223
+ return this.describe(stored, scope, component);
121
224
  }
122
225
  /**
123
226
  * Re-establish the mirror and re-arm any diagnostic window that outlived the
@@ -130,8 +233,13 @@ class LoggingSettingsService {
130
233
  */
131
234
  async restore() {
132
235
  const record = await this.read();
133
- if (record !== null)
236
+ if (record !== null) {
134
237
  this.refreshMirror(record);
238
+ // The REMAINDER of a window survives the restart; an expired one is
239
+ // dropped by `liveChannelWindows` rather than re-armed, so a forgotten
240
+ // diagnostic cannot become immortal across reboots.
241
+ await this.pushChannels(record);
242
+ }
135
243
  await this.requestCensus.restore();
136
244
  }
137
245
  // ── internals ─────────────────────────────────────────────────────
@@ -149,16 +257,57 @@ class LoggingSettingsService {
149
257
  });
150
258
  }
151
259
  }
152
- async describe(record, scopeNodeId) {
153
- const resolved = resolveLevel(record ?? {}, scopeNodeId);
260
+ /**
261
+ * Push the live windows to every declared gate.
262
+ *
263
+ * A failure here is logged and swallowed: the document is written and the
264
+ * operator is told what it says, and a runner that could not be reached
265
+ * simply keeps the mirror it has. Throwing would turn one unreachable addon
266
+ * into a failed write for the whole cluster.
267
+ */
268
+ async pushChannels(record) {
269
+ try {
270
+ await this.channels.apply(liveChannelWindows(record, this.now()));
271
+ }
272
+ catch (err) {
273
+ this.logger?.warn('log channel windows written but NOT pushed to every gate', {
274
+ meta: { error: (0, types_1.errMsg)(err) },
275
+ });
276
+ }
277
+ }
278
+ async describe(record, scopeNodeId, scopeComponent) {
279
+ const resolved = resolveLevel(record ?? {}, scopeNodeId, scopeComponent);
154
280
  return {
155
281
  scopeNodeId,
282
+ scopeComponent,
156
283
  effective: { level: resolved.level, levelSource: resolved.source },
157
- explicit: { layers: describeLayers(record ?? {}, scopeNodeId) },
284
+ explicit: { layers: describeLayers(record ?? {}, scopeNodeId, scopeComponent) },
158
285
  activeWindows: await this.describeWindows(),
286
+ channels: await this.declaredChannels(),
287
+ activeChannels: describeChannelWindows(record ?? {}, this.now()),
159
288
  persisted: record !== null,
160
289
  };
161
290
  }
291
+ /**
292
+ * The declarations, assembled per read.
293
+ *
294
+ * Not cached and not stored: a channel added by a redeployed addon has to
295
+ * appear without anybody editing a list, and a channel whose addon is gone
296
+ * has to stop being offered. A read that throws yields the EMPTY list and
297
+ * says so — "unknown" is the truth about a set of addons nobody reached, and
298
+ * it changes no armed window (D49/D224).
299
+ */
300
+ async declaredChannels() {
301
+ try {
302
+ return await this.channels.declarations();
303
+ }
304
+ catch (err) {
305
+ this.logger?.warn('log channel declarations unreadable - reporting none', {
306
+ meta: { error: (0, types_1.errMsg)(err) },
307
+ });
308
+ return [];
309
+ }
310
+ }
162
311
  /**
163
312
  * The armed windows, with their deadline.
164
313
  *
@@ -226,21 +375,36 @@ function toLoggingSettingsRecord(value) {
226
375
  return {};
227
376
  const clusterLevel = asLogLevel(Reflect.get(value, 'clusterLevel'));
228
377
  const nodeLevels = asNodeLevels(Reflect.get(value, 'nodeLevels'));
378
+ const componentLevels = asNodeLevels(Reflect.get(value, 'componentLevels'));
379
+ const channelWindows = asChannelWindows(Reflect.get(value, 'channelWindows'));
229
380
  const updatedAt = Reflect.get(value, 'updatedAt');
230
381
  return {
231
382
  ...(clusterLevel !== null ? { clusterLevel } : {}),
232
383
  ...(nodeLevels !== null ? { nodeLevels } : {}),
384
+ ...(componentLevels !== null ? { componentLevels } : {}),
385
+ ...(channelWindows !== null ? { channelWindows } : {}),
233
386
  ...(typeof updatedAt === 'number' && Number.isFinite(updatedAt) ? { updatedAt } : {}),
234
387
  };
235
388
  }
236
389
  /**
237
- * cluster → node, most specific wins.
390
+ * cluster → node → component, most specific wins.
238
391
  *
239
392
  * `nodeId === null` resolves the CLUSTER layer, which by definition cannot
240
393
  * inherit a node value — reading the document at cluster scope must never show
241
394
  * one node's override as if it were everybody's.
395
+ *
396
+ * `component` is the most specific layer and it is CLUSTER-WIDE: a channel
397
+ * means the same thing wherever the addon that declared it runs, and a
398
+ * per-node copy of it would be a second knob that disagrees with the first
399
+ * (D62). It sits above `node` because it is narrower in the dimension the
400
+ * operator actually reasons in — "everything on this node except make
401
+ * `stream-broker.webrtc` louder" is the request; "this node's level, but only
402
+ * where it is not a channel" is not a request anybody makes.
242
403
  */
243
- function resolveLevel(record, nodeId) {
404
+ function resolveLevel(record, nodeId, component = null) {
405
+ const componentLevel = component === null ? undefined : record.componentLevels?.[component];
406
+ if (componentLevel !== undefined)
407
+ return { level: componentLevel, source: 'component' };
244
408
  const nodeLevel = nodeId === null ? undefined : record.nodeLevels?.[nodeId];
245
409
  if (nodeLevel !== undefined)
246
410
  return { level: nodeLevel, source: 'node' };
@@ -252,15 +416,27 @@ function resolveLevel(record, nodeId) {
252
416
  * The layers as they stand, general → specific. `level: null` means the layer
253
417
  * carries no explicit value and inherits.
254
418
  */
255
- function describeLayers(record, nodeId) {
256
- const cluster = {
257
- scope: 'cluster',
258
- nodeId: null,
259
- level: record.clusterLevel ?? null,
260
- };
261
- if (nodeId === null)
262
- return [cluster];
263
- return [cluster, { scope: 'node', nodeId, level: record.nodeLevels?.[nodeId] ?? null }];
419
+ function describeLayers(record, nodeId, component = null) {
420
+ const layers = [
421
+ { scope: 'cluster', nodeId: null, component: null, level: record.clusterLevel ?? null },
422
+ ];
423
+ if (nodeId !== null) {
424
+ layers.push({
425
+ scope: 'node',
426
+ nodeId,
427
+ component: null,
428
+ level: record.nodeLevels?.[nodeId] ?? null,
429
+ });
430
+ }
431
+ if (component !== null) {
432
+ layers.push({
433
+ scope: 'component',
434
+ nodeId: null,
435
+ component,
436
+ level: record.componentLevels?.[component] ?? null,
437
+ });
438
+ }
439
+ return layers;
264
440
  }
265
441
  /**
266
442
  * Merge a level into the record at one scope.
@@ -268,8 +444,20 @@ function describeLayers(record, nodeId) {
268
444
  * `next === null` CLEARS that scope so it inherits again; a value sets it.
269
445
  * Everything else in the record is carried through untouched — including a
270
446
  * per-node map the caller never mentioned.
447
+ *
448
+ * A named `component` wins the addressing: a caller that supplies both is
449
+ * addressing the component layer, because a component level is cluster-wide
450
+ * and the node selector has no meaning there.
271
451
  */
272
- function mergeLevel(record, nodeId, next, updatedAt) {
452
+ function mergeLevel(record, nodeId, component, next, updatedAt) {
453
+ if (component !== null) {
454
+ const { [component]: _clearedComponent, ...otherComponents } = record.componentLevels ?? {};
455
+ const componentLevels = {
456
+ ...otherComponents,
457
+ ...(next !== null ? { [component]: next } : {}),
458
+ };
459
+ return { ...record, componentLevels, updatedAt };
460
+ }
273
461
  if (nodeId === null) {
274
462
  const { clusterLevel: _dropped, ...rest } = record;
275
463
  return { ...rest, ...(next !== null ? { clusterLevel: next } : {}), updatedAt };
@@ -285,6 +473,114 @@ function mergeLevel(record, nodeId, next, updatedAt) {
285
473
  updatedAt,
286
474
  };
287
475
  }
476
+ // ── channel windows ─────────────────────────────────────────────────
477
+ /**
478
+ * Why a patch is refused, in the operator's words. Empty = accepted.
479
+ *
480
+ * Two refusals, and the second is the point of the whole per-camera design:
481
+ *
482
+ * - an UNDECLARED channel. Silently accepting one would let a typo look like
483
+ * a working arm forever — the `CAMSTACK_FLEET_READ_CENSUS_MS=true` failure,
484
+ * which cost a whole boot before anyone noticed nothing was being measured.
485
+ * - `deviceIds` on a channel declared `perDevice: false`. That channel's
486
+ * lines carry no `tags: { deviceId }`, so the narrowing would produce a
487
+ * filter matching nothing. Widening it silently to "every camera" would be
488
+ * worse: the operator would believe per-camera filtering works there, and
489
+ * conclude from the first unrelated line that the wrong camera is at fault.
490
+ */
491
+ function validateChannelPatch(patches, declared) {
492
+ const byName = new Map(declared.map((d) => [d.name, d]));
493
+ const reasons = [];
494
+ for (const patch of patches) {
495
+ const descriptor = byName.get(patch.channel);
496
+ if (descriptor === undefined) {
497
+ const known = [...byName.keys()].sort().slice(0, 8).join(', ');
498
+ reasons.push(`"${patch.channel}" is not declared by any addon on this cluster` +
499
+ (known.length > 0 ? ` (declared: ${known})` : ''));
500
+ continue;
501
+ }
502
+ const ids = patch.deviceIds;
503
+ if (ids !== undefined && ids !== null && ids.length > 0 && !descriptor.perDevice) {
504
+ reasons.push(`"${patch.channel}" is declared perDevice: false — its lines carry no ` +
505
+ 'tags.deviceId, so narrowing it to a camera would match nothing');
506
+ }
507
+ }
508
+ return reasons;
509
+ }
510
+ /**
511
+ * Apply channel patches to the record. `armMs: 0` disarms; a positive value
512
+ * arms until `now + min(armMs, MAX_CHANNEL_WINDOW_MS)`.
513
+ *
514
+ * Only the channels NAMED are touched — a channel absent from the patch keeps
515
+ * whatever window it had, so the Levels page and the Diagnostics page cannot
516
+ * disarm each other's work.
517
+ */
518
+ function mergeChannelWindows(record, patches, nowMs) {
519
+ const windows = { ...record.channelWindows };
520
+ for (const patch of patches) {
521
+ if (patch.armMs <= 0) {
522
+ delete windows[patch.channel];
523
+ continue;
524
+ }
525
+ const ids = patch.deviceIds;
526
+ windows[patch.channel] = {
527
+ armedUntilMs: nowMs + Math.min(patch.armMs, exports.MAX_CHANNEL_WINDOW_MS),
528
+ deviceIds: ids === undefined || ids === null || ids.length === 0 ? null : [...ids],
529
+ };
530
+ }
531
+ return { ...record, channelWindows: windows, updatedAt: nowMs };
532
+ }
533
+ /**
534
+ * The windows still running at `nowMs`, in the shape the gates take.
535
+ *
536
+ * An expired window is DROPPED rather than pushed: this is what stops a
537
+ * restore from re-arming a diagnostic somebody forgot months ago, which is the
538
+ * one failure a deadline exists to prevent.
539
+ */
540
+ function liveChannelWindows(record, nowMs) {
541
+ const out = [];
542
+ for (const [channel, window] of Object.entries(record.channelWindows ?? {})) {
543
+ if (window.armedUntilMs <= nowMs)
544
+ continue;
545
+ out.push({ channel, armedUntilMs: window.armedUntilMs, deviceIds: window.deviceIds });
546
+ }
547
+ return out.sort((a, b) => a.channel.localeCompare(b.channel));
548
+ }
549
+ /** The windows as the page shows them: deadline plus time left, never a flag. */
550
+ function describeChannelWindows(record, nowMs) {
551
+ const out = [];
552
+ for (const [channel, window] of Object.entries(record.channelWindows ?? {})) {
553
+ const armed = window.armedUntilMs > nowMs;
554
+ out.push({
555
+ channel,
556
+ armed,
557
+ armedUntilMs: armed ? window.armedUntilMs : 0,
558
+ remainingMs: armed ? window.armedUntilMs - nowMs : 0,
559
+ deviceIds: armed ? window.deviceIds : null,
560
+ });
561
+ }
562
+ return out.sort((a, b) => a.channel.localeCompare(b.channel));
563
+ }
564
+ function asChannelWindows(value) {
565
+ if (typeof value !== 'object' || value === null)
566
+ return null;
567
+ const out = {};
568
+ for (const [key, raw] of Object.entries(value)) {
569
+ if (typeof raw !== 'object' || raw === null)
570
+ continue;
571
+ const armedUntilMs = Reflect.get(raw, 'armedUntilMs');
572
+ if (typeof armedUntilMs !== 'number' || !Number.isFinite(armedUntilMs))
573
+ continue;
574
+ out[key] = { armedUntilMs, deviceIds: asDeviceIds(Reflect.get(raw, 'deviceIds')) };
575
+ }
576
+ return out;
577
+ }
578
+ function asDeviceIds(value) {
579
+ if (!Array.isArray(value))
580
+ return null;
581
+ const ids = value.filter((id) => typeof id === 'number' && Number.isInteger(id));
582
+ return ids.length > 0 ? ids : null;
583
+ }
288
584
  function asLogLevel(value) {
289
585
  return typeof value === 'string' && isLogLevel(value) ? value : null;
290
586
  }
@@ -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
  }