@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,304 @@
1
+ "use strict";
2
+ /**
3
+ * The logging settings DOCUMENT — one authority over log levels and armed
4
+ * diagnostics, read and written whole through `system.getLoggingSettings` /
5
+ * `system.setLoggingSettings`.
6
+ *
7
+ * ## Why one document and not one method per knob
8
+ *
9
+ * The audit in `docs/design/plans/2026-08-26-logging-per-componente.md` found
10
+ * the level spread over five knobs in three settings panels, two kernel config
11
+ * keys and an env var that never reached an addon. Adding a cap method per
12
+ * knob would have reproduced that on the API. So: adding a logging setting
13
+ * means adding a FIELD to `LoggingSettingsPatchSchema`, never a method.
14
+ *
15
+ * ## The patch merges
16
+ *
17
+ * A field absent from the patch is left exactly as it was. The record is never
18
+ * rebuilt as `{ ...stored, ...patch }` — that spelling turns "absent" into
19
+ * "erased" the moment someone adds a nested object, and this repo already has
20
+ * a rule against it. Each field decides for itself: absent → keep, `null` →
21
+ * clear, value → set.
22
+ *
23
+ * ## Hierarchy: cluster → node, most specific wins
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.
31
+ *
32
+ * ## The hot path reads the MIRROR, and a failed read changes nothing
33
+ *
34
+ * This service is the durable authority. {@link LoggingGate} is the mirror the
35
+ * log path reads, refreshed here — on a write and once at boot — and NEVER
36
+ * from a value that was not actually read. A store read that throws returns
37
+ * `null` from {@link LoggingSettingsService.read} and every caller treats that
38
+ * as "unknown", not as "cleared": the mirror keeps its floor and an armed
39
+ * diagnostic stays armed (D49). A doorbell in this repo rang 0/3 because one
40
+ * bad read looked exactly like a real "off".
41
+ *
42
+ * ## Diagnostics carry a deadline, never a boolean
43
+ *
44
+ * `request-census` is armed through this document and nowhere else. The window
45
+ * mechanics — the persisted deadline, the clamp, the boot restore of the
46
+ * REMAINDER — stay in {@link RequestCensusService}, which owns them (ADR-0244);
47
+ * this service is its only caller, so there is exactly one write authority
48
+ * over the window (D245).
49
+ */
50
+ Object.defineProperty(exports, "__esModule", { value: true });
51
+ exports.LoggingSettingsService = exports.HUB_NODE_ID = exports.LOGGING_SETTINGS_KEY = void 0;
52
+ exports.toLoggingSettingsRecord = toLoggingSettingsRecord;
53
+ exports.resolveLevel = resolveLevel;
54
+ exports.describeLayers = describeLayers;
55
+ exports.mergeLevel = mergeLevel;
56
+ const types_1 = require("@camstack/types");
57
+ const system_1 = require("@camstack/system");
58
+ /** The `system-settings` row this module owns. */
59
+ exports.LOGGING_SETTINGS_KEY = 'logging-settings';
60
+ const SYSTEM_SETTINGS_COLLECTION = 'system-settings';
61
+ /** The node a hub speaks for when a caller does not name one. */
62
+ exports.HUB_NODE_ID = 'hub';
63
+ const LOG_LEVELS = ['debug', 'info', 'warn', 'error'];
64
+ class LoggingSettingsService {
65
+ store;
66
+ gate;
67
+ requestCensus;
68
+ localNodeId;
69
+ logger;
70
+ now;
71
+ constructor(deps) {
72
+ this.store = deps.store;
73
+ this.gate = deps.gate;
74
+ this.requestCensus = deps.requestCensus;
75
+ this.localNodeId = deps.localNodeId ?? exports.HUB_NODE_ID;
76
+ this.logger = deps.logger;
77
+ this.now = deps.now ?? Date.now;
78
+ }
79
+ /**
80
+ * The document as it stands, resolved for `nodeId` (absent = the cluster).
81
+ *
82
+ * A read that fails yields `persisted: false` and the DEFAULT hierarchy —
83
+ * and, crucially, does not touch the mirror. What the operator sees is
84
+ * honestly labelled as un-persisted; what the hub does is unchanged.
85
+ */
86
+ async get(scopeNodeId) {
87
+ const record = await this.read();
88
+ return this.describe(record, scopeNodeId ?? null);
89
+ }
90
+ /**
91
+ * Apply a patch. Fields absent from it are untouched.
92
+ *
93
+ * The diagnostics are armed FIRST and the level row written after, for the
94
+ * same reason ADR-0244 arms before it writes: a settings store that is down
95
+ * must still give the operator a live measurement, and must say so rather
96
+ * than reporting a durable arm that is not durable.
97
+ */
98
+ async set(patch, scopeNodeId) {
99
+ await this.applyDiagnostics(patch);
100
+ const scope = scopeNodeId ?? null;
101
+ const stored = await this.read();
102
+ const levelChanged = patch.level !== undefined;
103
+ let persistedLevel = true;
104
+ if (levelChanged) {
105
+ const next = mergeLevel(stored ?? {}, scope, patch.level ?? null, this.now());
106
+ persistedLevel = await this.write(next);
107
+ // The mirror moves only from a value this call actually produced.
108
+ this.refreshMirror(next);
109
+ this.logger?.info('logging settings written', {
110
+ meta: {
111
+ scope: scope === null ? 'cluster' : 'node',
112
+ nodeId: scope,
113
+ level: patch.level ?? null,
114
+ persisted: persistedLevel,
115
+ },
116
+ });
117
+ const state = await this.describe(next, scope);
118
+ return { ...state, persisted: state.persisted && persistedLevel };
119
+ }
120
+ return this.describe(stored, scope);
121
+ }
122
+ /**
123
+ * Re-establish the mirror and re-arm any diagnostic window that outlived the
124
+ * last shutdown. Called once at boot, before the socket opens.
125
+ *
126
+ * A read that fails leaves the mirror at its default and says so. It never
127
+ * writes: a restore that refreshed a deadline would make a forgotten
128
+ * diagnostic immortal across restarts, which is the one failure a deadline
129
+ * exists to prevent.
130
+ */
131
+ async restore() {
132
+ const record = await this.read();
133
+ if (record !== null)
134
+ this.refreshMirror(record);
135
+ await this.requestCensus.restore();
136
+ }
137
+ // ── internals ─────────────────────────────────────────────────────
138
+ /** Push the LOCAL node's effective level into the hot-path mirror. */
139
+ refreshMirror(record) {
140
+ this.gate.setDestinationFloor(resolveLevel(record, this.localNodeId).level);
141
+ }
142
+ async applyDiagnostics(patch) {
143
+ for (const window of patch.diagnostics ?? []) {
144
+ if (window.id !== 'request-census')
145
+ continue;
146
+ await this.requestCensus.set({
147
+ armMs: window.armMs,
148
+ ...(window.reportEveryMs !== undefined ? { reportEveryMs: window.reportEveryMs } : {}),
149
+ });
150
+ }
151
+ }
152
+ async describe(record, scopeNodeId) {
153
+ const resolved = resolveLevel(record ?? {}, scopeNodeId);
154
+ return {
155
+ scopeNodeId,
156
+ effective: { level: resolved.level, levelSource: resolved.source },
157
+ explicit: { layers: describeLayers(record ?? {}, scopeNodeId) },
158
+ activeWindows: await this.describeWindows(),
159
+ persisted: record !== null,
160
+ };
161
+ }
162
+ /**
163
+ * The armed windows, with their deadline.
164
+ *
165
+ * Read from the LIVE diagnostic, never from the stored row: a window armed
166
+ * before a restart that was never restored must not look armed. `persisted`
167
+ * is the census's own comparison of the stored deadline against the running
168
+ * one — asking it rather than re-deriving it is what keeps the two from
169
+ * drifting.
170
+ */
171
+ async describeWindows() {
172
+ const census = await this.requestCensus.status();
173
+ const remainingMs = census.armed ? Math.max(0, census.armedUntilMs - this.now()) : 0;
174
+ return [
175
+ {
176
+ id: 'request-census',
177
+ armed: census.armed,
178
+ armedUntilMs: census.armedUntilMs,
179
+ remainingMs,
180
+ persisted: census.persisted,
181
+ },
182
+ ];
183
+ }
184
+ /**
185
+ * The stored row, or `null` when it is absent OR unreadable.
186
+ *
187
+ * The two collapse on purpose at this level — every caller treats `null` as
188
+ * "do not touch anything" — and the difference is in the log, because a
189
+ * branch that drops work silently reads as "never happened".
190
+ */
191
+ async read() {
192
+ try {
193
+ const raw = await this.store.get({
194
+ collection: SYSTEM_SETTINGS_COLLECTION,
195
+ key: exports.LOGGING_SETTINGS_KEY,
196
+ });
197
+ return toLoggingSettingsRecord(raw);
198
+ }
199
+ catch (err) {
200
+ this.logger?.warn('logging settings read failed - mirror left untouched', {
201
+ meta: { error: (0, types_1.errMsg)(err) },
202
+ });
203
+ return null;
204
+ }
205
+ }
206
+ async write(record) {
207
+ try {
208
+ await this.store.set({
209
+ collection: SYSTEM_SETTINGS_COLLECTION,
210
+ key: exports.LOGGING_SETTINGS_KEY,
211
+ value: record,
212
+ });
213
+ return true;
214
+ }
215
+ catch (err) {
216
+ this.logger?.warn('logging settings applied in memory but NOT persisted - they will not survive a restart', { meta: { error: (0, types_1.errMsg)(err) } });
217
+ return false;
218
+ }
219
+ }
220
+ }
221
+ exports.LoggingSettingsService = LoggingSettingsService;
222
+ // ── pure helpers ────────────────────────────────────────────────────
223
+ /** Structural read of the stored row. Anything unrecognised reads as absent. */
224
+ function toLoggingSettingsRecord(value) {
225
+ if (typeof value !== 'object' || value === null)
226
+ return {};
227
+ const clusterLevel = asLogLevel(Reflect.get(value, 'clusterLevel'));
228
+ const nodeLevels = asNodeLevels(Reflect.get(value, 'nodeLevels'));
229
+ const updatedAt = Reflect.get(value, 'updatedAt');
230
+ return {
231
+ ...(clusterLevel !== null ? { clusterLevel } : {}),
232
+ ...(nodeLevels !== null ? { nodeLevels } : {}),
233
+ ...(typeof updatedAt === 'number' && Number.isFinite(updatedAt) ? { updatedAt } : {}),
234
+ };
235
+ }
236
+ /**
237
+ * cluster → node, most specific wins.
238
+ *
239
+ * `nodeId === null` resolves the CLUSTER layer, which by definition cannot
240
+ * inherit a node value — reading the document at cluster scope must never show
241
+ * one node's override as if it were everybody's.
242
+ */
243
+ function resolveLevel(record, nodeId) {
244
+ const nodeLevel = nodeId === null ? undefined : record.nodeLevels?.[nodeId];
245
+ if (nodeLevel !== undefined)
246
+ return { level: nodeLevel, source: 'node' };
247
+ if (record.clusterLevel !== undefined)
248
+ return { level: record.clusterLevel, source: 'cluster' };
249
+ return { level: system_1.DEFAULT_LOG_LEVEL, source: 'default' };
250
+ }
251
+ /**
252
+ * The layers as they stand, general → specific. `level: null` means the layer
253
+ * carries no explicit value and inherits.
254
+ */
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 }];
264
+ }
265
+ /**
266
+ * Merge a level into the record at one scope.
267
+ *
268
+ * `next === null` CLEARS that scope so it inherits again; a value sets it.
269
+ * Everything else in the record is carried through untouched — including a
270
+ * per-node map the caller never mentioned.
271
+ */
272
+ function mergeLevel(record, nodeId, next, updatedAt) {
273
+ if (nodeId === null) {
274
+ const { clusterLevel: _dropped, ...rest } = record;
275
+ return { ...rest, ...(next !== null ? { clusterLevel: next } : {}), updatedAt };
276
+ }
277
+ const { [nodeId]: _cleared, ...otherNodes } = record.nodeLevels ?? {};
278
+ const nodeLevels = {
279
+ ...otherNodes,
280
+ ...(next !== null ? { [nodeId]: next } : {}),
281
+ };
282
+ return {
283
+ ...record,
284
+ ...(Object.keys(nodeLevels).length > 0 ? { nodeLevels } : { nodeLevels: {} }),
285
+ updatedAt,
286
+ };
287
+ }
288
+ function asLogLevel(value) {
289
+ return typeof value === 'string' && isLogLevel(value) ? value : null;
290
+ }
291
+ function isLogLevel(value) {
292
+ return LOG_LEVELS.includes(value);
293
+ }
294
+ function asNodeLevels(value) {
295
+ if (typeof value !== 'object' || value === null)
296
+ return null;
297
+ const out = {};
298
+ for (const [key, raw] of Object.entries(value)) {
299
+ const level = asLogLevel(raw);
300
+ if (level !== null)
301
+ out[key] = level;
302
+ }
303
+ return out;
304
+ }
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ /**
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.
9
+ *
10
+ * ## Why the arm deadline is persisted
11
+ *
12
+ * `FleetReadCensus` arms from `CAMSTACK_FLEET_READ_CENSUS_MS` at construction
13
+ * because "the storm is at BOOT - by the time a process is up enough to
14
+ * receive an action, the window being investigated has closed". That reasoning
15
+ * is right and its conclusion is not: an env var needs a container recreation
16
+ * to change, cannot be switched off, and the operator has asked for no more of
17
+ * them.
18
+ *
19
+ * A persisted DEADLINE satisfies both halves. The operator arms a window
20
+ * through `system.setLoggingSettings`, restarts the hub, and the window is still
21
+ * running when the clients reconnect - `restore()` re-arms the REMAINDER at
22
+ * boot, before `app.listen`, so not one HTTP request is missed. Switching it
23
+ * off is another call and takes effect immediately. And because what is stored
24
+ * is a deadline rather than a flag, a census somebody forgot expires on its
25
+ * own instead of taxing every request until the next release.
26
+ *
27
+ * ## Never longer than was asked for
28
+ *
29
+ * What is written is `census.armedUntilMs` - the deadline AFTER the census
30
+ * clamped the requested window. A restore therefore cannot extend a window
31
+ * past the clamp, and the two numbers cannot drift, because there is only one.
32
+ *
33
+ * ## `persisted` is read, never remembered
34
+ *
35
+ * The provider is rebuilt per request, so there is nowhere to keep "the last
36
+ * write worked". `status()` re-reads the row and compares it with the live
37
+ * census instead. That is one KV read on an operator gesture, and unlike a
38
+ * cached flag it cannot claim a window survives a restart when the write that
39
+ * would have made it survive failed.
40
+ */
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.RequestCensusService = exports.REQUEST_CENSUS_KEY = void 0;
43
+ exports.toRecord = toRecord;
44
+ const types_1 = require("@camstack/types");
45
+ const http_request_census_js_1 = require("../trpc/http-request-census.js");
46
+ /** The `system-settings` row this module owns. */
47
+ exports.REQUEST_CENSUS_KEY = 'http-request-census';
48
+ const SYSTEM_SETTINGS_COLLECTION = 'system-settings';
49
+ /**
50
+ * Arm / disarm / read the census, keeping the persisted deadline in step.
51
+ */
52
+ class RequestCensusService {
53
+ census;
54
+ store;
55
+ logger;
56
+ now;
57
+ constructor(deps) {
58
+ this.census = deps.census;
59
+ this.store = deps.store;
60
+ this.logger = deps.logger;
61
+ this.now = deps.now ?? Date.now;
62
+ }
63
+ /** The window as it stands, plus whether it would survive a restart. */
64
+ async status() {
65
+ const record = await this.read();
66
+ return { ...this.census.snapshot(), persisted: this.matchesStored(record) };
67
+ }
68
+ /**
69
+ * `armMs: 0` disarms; anything positive arms for that long (clamped).
70
+ *
71
+ * The census is armed BEFORE the write, so a settings-store that is down
72
+ * still gives the operator a live measurement - it just says so, both in the
73
+ * response (`persisted: false`) and in the log. Silently reporting a durable
74
+ * arm that is not durable is how a whole boot window gets measured, lost to
75
+ * a restart, and blamed on the instrument.
76
+ */
77
+ async set(input) {
78
+ const reportEveryMs = input.reportEveryMs ?? http_request_census_js_1.DEFAULT_REPORT_EVERY_MS;
79
+ if (input.armMs <= 0)
80
+ this.census.disarm('operator-disarmed');
81
+ else
82
+ this.census.arm(input.armMs, reportEveryMs);
83
+ const record = {
84
+ armedUntilMs: this.census.armedUntilMs,
85
+ reportEveryMs,
86
+ updatedAt: this.now(),
87
+ };
88
+ const persisted = await this.write(record);
89
+ this.logger?.info('transport census switched', {
90
+ meta: {
91
+ armed: this.census.armed,
92
+ armedUntilMs: this.census.armedUntilMs,
93
+ reportEveryMs,
94
+ persisted,
95
+ },
96
+ });
97
+ return { ...this.census.snapshot(), persisted };
98
+ }
99
+ /**
100
+ * Re-arm the remainder of a window that was armed before this boot.
101
+ *
102
+ * Called once, before `app.listen`, so the census is already counting when
103
+ * the first client reconnects. Never re-writes the row: a restore that
104
+ * refreshed the deadline would make a forgotten census immortal across
105
+ * restarts, which is the one failure mode a deadline exists to prevent.
106
+ */
107
+ async restore() {
108
+ const record = await this.read();
109
+ const until = record?.armedUntilMs;
110
+ if (typeof until !== 'number' || !Number.isFinite(until) || until <= 0)
111
+ return false;
112
+ const remainingMs = until - this.now();
113
+ if (remainingMs <= 0) {
114
+ this.logger?.info('transport census not restored - window already expired', {
115
+ meta: { armedUntilMs: until },
116
+ });
117
+ return false;
118
+ }
119
+ this.census.arm(remainingMs, record?.reportEveryMs ?? http_request_census_js_1.DEFAULT_REPORT_EVERY_MS);
120
+ this.logger?.info('transport census restored from system-settings', {
121
+ meta: { remainingMs, armedUntilMs: this.census.armedUntilMs },
122
+ });
123
+ return true;
124
+ }
125
+ /** True when the stored deadline is the one the live census is running. */
126
+ matchesStored(record) {
127
+ const stored = record?.armedUntilMs ?? 0;
128
+ return stored === this.census.armedUntilMs;
129
+ }
130
+ async read() {
131
+ try {
132
+ const raw = await this.store.get({
133
+ collection: SYSTEM_SETTINGS_COLLECTION,
134
+ key: exports.REQUEST_CENSUS_KEY,
135
+ });
136
+ return toRecord(raw);
137
+ }
138
+ catch (err) {
139
+ // A read that fails is not a disarm: it changes nothing about the live
140
+ // census. It is logged because a branch that drops work silently reads
141
+ // as "never happened".
142
+ this.logger?.warn('transport census settings read failed', {
143
+ meta: { error: (0, types_1.errMsg)(err) },
144
+ });
145
+ return null;
146
+ }
147
+ }
148
+ async write(record) {
149
+ try {
150
+ await this.store.set({
151
+ collection: SYSTEM_SETTINGS_COLLECTION,
152
+ key: exports.REQUEST_CENSUS_KEY,
153
+ value: record,
154
+ });
155
+ return true;
156
+ }
157
+ catch (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) } });
159
+ return false;
160
+ }
161
+ }
162
+ }
163
+ exports.RequestCensusService = RequestCensusService;
164
+ /** Structural read of the stored row. Anything unrecognised reads as absent. */
165
+ function toRecord(value) {
166
+ if (typeof value !== 'object' || value === null)
167
+ return null;
168
+ const armedUntilMs = Reflect.get(value, 'armedUntilMs');
169
+ const reportEveryMs = Reflect.get(value, 'reportEveryMs');
170
+ const updatedAt = Reflect.get(value, 'updatedAt');
171
+ return {
172
+ ...(typeof armedUntilMs === 'number' && Number.isFinite(armedUntilMs) ? { armedUntilMs } : {}),
173
+ ...(typeof reportEveryMs === 'number' && Number.isFinite(reportEveryMs)
174
+ ? { reportEveryMs }
175
+ : {}),
176
+ ...(typeof updatedAt === 'number' && Number.isFinite(updatedAt) ? { updatedAt } : {}),
177
+ };
178
+ }
@@ -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
  }
@@ -9126,6 +9126,31 @@ function createCapRouter_system(getProvider, createRemoteProxy) {
9126
9126
  const p = resolveProvider('system', input?.nodeId, () => getProvider(ctx), createRemoteProxy);
9127
9127
  return p.detectSiteLocation();
9128
9128
  }),
9129
+ getRequestCensus: trpc_middleware_js_1.adminProcedure
9130
+ .input(zod_1.z.object({ nodeId: zod_1.z.string().optional() }).optional())
9131
+ .output(types_109.systemCapability.methods.getRequestCensus.output)
9132
+ .query(async ({ input, ctx }) => {
9133
+ const p = resolveProvider('system', input?.nodeId, () => getProvider(ctx), createRemoteProxy);
9134
+ return p.getRequestCensus();
9135
+ }),
9136
+ getLoggingSettings: trpc_middleware_js_1.adminProcedure
9137
+ .input(types_109.systemCapability.methods.getLoggingSettings.input.loose())
9138
+ .output(types_109.systemCapability.methods.getLoggingSettings.output)
9139
+ .query(async ({ input, ctx }) => {
9140
+ const { nodeId, ...methodInput } = input;
9141
+ const p = resolveProvider('system', nodeId, () => getProvider(ctx), createRemoteProxy);
9142
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
9143
+ return p.getLoggingSettings(methodInput);
9144
+ }),
9145
+ setLoggingSettings: trpc_middleware_js_1.adminProcedure
9146
+ .input(types_109.systemCapability.methods.setLoggingSettings.input.loose())
9147
+ .output(types_109.systemCapability.methods.setLoggingSettings.output)
9148
+ .mutation(async ({ input, ctx }) => {
9149
+ const { nodeId, ...methodInput } = input;
9150
+ const p = resolveProvider('system', nodeId, () => getProvider(ctx), createRemoteProxy);
9151
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
9152
+ return p.setLoggingSettings(methodInput);
9153
+ }),
9129
9154
  });
9130
9155
  }
9131
9156
  function createCapRouter_tamper(getProvider, createRemoteProxy) {
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ /**
3
+ * The seam that feeds {@link HttpRequestCensus} from a live tRPC request.
4
+ *
5
+ * ## Why this hangs off `createContext` and not `onRequest`
6
+ *
7
+ * `onRequest` sees every HTTP request the hub serves, but it does not know WHO
8
+ * sent it: the bearer has not been validated yet, so the only identity
9
+ * available there is the raw `Authorization` header - which must never be
10
+ * logged, copied or keyed on. The tRPC context factory is the FIRST place a
11
+ * principal exists, and `@trpc/server` calls it exactly ONCE per HTTP request
12
+ * (`resolveResponse` -> `ctxManager.create`), after the batch has been parsed
13
+ * and before any procedure resolves. So it is also the only place where one
14
+ * call = one request, batched or not.
15
+ *
16
+ * What it does not see: a request so malformed that `getRequestInfo` throws
17
+ * before a context is built. That request never invoked a procedure either, so
18
+ * it cannot be part of a procedure-call storm and its absence does not weaken
19
+ * the conclusion the totals support.
20
+ *
21
+ * ## Cost when disarmed
22
+ *
23
+ * The armed check is the FIRST statement, before the request is touched at
24
+ * all: no header read, no URL parse, no `Date.now()`, no allocation. The spec
25
+ * pins this with a request whose every property getter throws - if the guard
26
+ * ever moves below a field access, that test fails instead of the hub paying
27
+ * for a diagnostic nobody switched on.
28
+ */
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.recordTrpcHttpRequest = recordTrpcHttpRequest;
31
+ const client_ip_js_1 = require("./client-ip.js");
32
+ const http_request_census_js_1 = require("./http-request-census.js");
33
+ const trpc_error_principal_js_1 = require("./trpc-error-principal.js");
34
+ /**
35
+ * Count one tRPC HTTP request against `census`.
36
+ *
37
+ * `user` is the resolved principal or `null`; it is rendered by
38
+ * `describeTrpcPrincipal`, the same function the tRPC error log already uses -
39
+ * a username and a credential KIND, never a token and never a header.
40
+ */
41
+ function recordTrpcHttpRequest(census, req, user) {
42
+ if (!census.armed)
43
+ return;
44
+ if (req === undefined)
45
+ return;
46
+ const url = typeof req.url === 'string' ? req.url : '';
47
+ const procedures = (0, http_request_census_js_1.parseTrpcProcedures)(url, headerValue(req, 'content-type'));
48
+ if (procedures.length === 0)
49
+ return;
50
+ census.observeHttpRequest({
51
+ procedures,
52
+ userAgent: (0, client_ip_js_1.extractUserAgent)(req),
53
+ ip: (0, client_ip_js_1.extractClientIp)(req),
54
+ principal: (0, trpc_error_principal_js_1.describeTrpcPrincipal)(user),
55
+ });
56
+ }
57
+ /** First value of a possibly-repeated header, or `null`. */
58
+ function headerValue(req, name) {
59
+ const raw = req.headers[name];
60
+ const value = Array.isArray(raw) ? raw[0] : raw;
61
+ return typeof value === 'string' && value.length > 0 ? value : null;
62
+ }