@camstack/server 1.2.174 → 1.2.176
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.
- package/dist/api/core/cap-providers.js +42 -6
- package/dist/api/core/logging-settings.js +304 -0
- package/dist/api/core/request-census-settings.js +173 -0
- package/dist/api/trpc/generated-cap-routers.js +43 -0
- package/dist/api/trpc/http-request-census-hook.js +62 -0
- package/dist/api/trpc/http-request-census.js +471 -0
- package/dist/api/trpc/http-request-census.singleton.js +27 -0
- package/dist/main.js +60 -6
- package/package.json +1 -1
|
@@ -60,6 +60,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
60
60
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
61
61
|
exports.INTEGRATION_CAP_MARKERS = void 0;
|
|
62
62
|
exports.buildSystemProvider = buildSystemProvider;
|
|
63
|
+
exports.buildSettingsStoreGateway = buildSettingsStoreGateway;
|
|
63
64
|
exports.buildNetworkQualityProvider = buildNetworkQualityProvider;
|
|
64
65
|
exports.buildToastProvider = buildToastProvider;
|
|
65
66
|
exports.computeTopology = computeTopology;
|
|
@@ -77,14 +78,33 @@ const integration_id_backfill_1 = require("../../boot/integration-id-backfill");
|
|
|
77
78
|
const addon_package_service_js_1 = require("../../core/addon/addon-package.service.js");
|
|
78
79
|
const lifecycle_runner_singleton_js_1 = require("../../core/lifecycle/lifecycle-runner.singleton.js");
|
|
79
80
|
const agent_installed_packages_js_1 = require("../../core/updates/agent-installed-packages.js");
|
|
81
|
+
const http_request_census_singleton_js_1 = require("../trpc/http-request-census.singleton.js");
|
|
80
82
|
const collection_preference_js_1 = require("./collection-preference.js");
|
|
83
|
+
const logging_settings_js_1 = require("./logging-settings.js");
|
|
84
|
+
const request_census_settings_js_1 = require("./request-census-settings.js");
|
|
81
85
|
const site_location_js_1 = require("./site-location.js");
|
|
82
86
|
// ── system ──────────────────────────────────────────────────────────
|
|
83
87
|
function getRetention(registry) {
|
|
84
88
|
return (registry?.getSingleton('analysis-data-persistence')?.retention ?? null);
|
|
85
89
|
}
|
|
86
|
-
function buildSystemProvider(feature, registry, logger) {
|
|
90
|
+
function buildSystemProvider(feature, registry, logger, census = (0, http_request_census_singleton_js_1.getHttpRequestCensus)()) {
|
|
87
91
|
const siteLocation = buildSiteLocationService(registry, logger);
|
|
92
|
+
const store = buildSettingsStoreGateway(registry);
|
|
93
|
+
const requestCensus = new request_census_settings_js_1.RequestCensusService({
|
|
94
|
+
census,
|
|
95
|
+
store,
|
|
96
|
+
...(logger !== undefined ? { logger } : {}),
|
|
97
|
+
});
|
|
98
|
+
// ONE write authority over levels and diagnostic windows. `requestCensus` is
|
|
99
|
+
// reachable only through this service now — `system.setRequestCensus` was
|
|
100
|
+
// retired on 2026-08-27 precisely so two writes cannot disagree about the
|
|
101
|
+
// same window (D245).
|
|
102
|
+
const loggingSettings = new logging_settings_js_1.LoggingSettingsService({
|
|
103
|
+
store,
|
|
104
|
+
gate: (0, system_1.getLoggingGate)(),
|
|
105
|
+
requestCensus,
|
|
106
|
+
...(logger !== undefined ? { logger } : {}),
|
|
107
|
+
});
|
|
88
108
|
return {
|
|
89
109
|
info: async () => feature.getManifest(),
|
|
90
110
|
health: async () => ({ status: 'ok', uptime: process.uptime() }),
|
|
@@ -115,6 +135,9 @@ function buildSystemProvider(feature, registry, logger) {
|
|
|
115
135
|
getSiteLocation: async () => siteLocation.get(),
|
|
116
136
|
setSiteLocation: async (input) => siteLocation.set(input),
|
|
117
137
|
detectSiteLocation: async () => siteLocation.detect(),
|
|
138
|
+
getRequestCensus: async () => requestCensus.status(),
|
|
139
|
+
getLoggingSettings: async (input) => loggingSettings.get(input.scopeNodeId),
|
|
140
|
+
setLoggingSettings: async (input) => loggingSettings.set(input.patch, input.scopeNodeId),
|
|
118
141
|
};
|
|
119
142
|
}
|
|
120
143
|
/**
|
|
@@ -130,22 +153,35 @@ function buildSystemProvider(feature, registry, logger) {
|
|
|
130
153
|
* invent a location out of a missing dependency.
|
|
131
154
|
*/
|
|
132
155
|
function buildSiteLocationService(registry, logger) {
|
|
156
|
+
return new site_location_js_1.SiteLocationService({
|
|
157
|
+
store: buildSettingsStoreGateway(registry),
|
|
158
|
+
...(logger !== undefined ? { logger } : {}),
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The two settings-store calls a hub-side service needs, resolved LAZILY from
|
|
163
|
+
* the capability registry.
|
|
164
|
+
*
|
|
165
|
+
* Lazy because the cap boots after these providers are constructed, and there
|
|
166
|
+
* is NO `settings-store.*` Moleculer action to call instead (that path
|
|
167
|
+
* returned "Service 'settings-store.get' is not found" in production while the
|
|
168
|
+
* tests' fake gateway hid it). Without a registry the gateway fails closed:
|
|
169
|
+
* every call throws, so a caller cannot mistake a missing dependency for an
|
|
170
|
+
* empty row.
|
|
171
|
+
*/
|
|
172
|
+
function buildSettingsStoreGateway(registry) {
|
|
133
173
|
const resolve = () => {
|
|
134
174
|
const provider = registry?.getSingleton('settings-store') ?? null;
|
|
135
175
|
if (provider === null)
|
|
136
176
|
throw new Error('settings-store unavailable: cap not registered yet');
|
|
137
177
|
return provider;
|
|
138
178
|
};
|
|
139
|
-
|
|
179
|
+
return {
|
|
140
180
|
get: async (input) => resolve().get(input),
|
|
141
181
|
set: async (input) => {
|
|
142
182
|
await resolve().set(input);
|
|
143
183
|
},
|
|
144
184
|
};
|
|
145
|
-
return new site_location_js_1.SiteLocationService({
|
|
146
|
-
store,
|
|
147
|
-
...(logger !== undefined ? { logger } : {}),
|
|
148
|
-
});
|
|
149
185
|
}
|
|
150
186
|
// ── network-quality ─────────────────────────────────────────────────
|
|
151
187
|
function buildNetworkQualityProvider(nq) {
|
|
@@ -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,173 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* The switch for the HTTP request census - a SYSTEM SETTING, not an env var.
|
|
4
|
+
*
|
|
5
|
+
* ## Why the arm deadline is persisted
|
|
6
|
+
*
|
|
7
|
+
* `FleetReadCensus` arms from `CAMSTACK_FLEET_READ_CENSUS_MS` at construction
|
|
8
|
+
* because "the storm is at BOOT - by the time a process is up enough to
|
|
9
|
+
* receive an action, the window being investigated has closed". That reasoning
|
|
10
|
+
* is right and its conclusion is not: an env var needs a container recreation
|
|
11
|
+
* to change, cannot be switched off, and the operator has asked for no more of
|
|
12
|
+
* them.
|
|
13
|
+
*
|
|
14
|
+
* A persisted DEADLINE satisfies both halves. The operator arms a window
|
|
15
|
+
* through `system.setLoggingSettings`, restarts the hub, and the window is still
|
|
16
|
+
* running when the clients reconnect - `restore()` re-arms the REMAINDER at
|
|
17
|
+
* boot, before `app.listen`, so not one HTTP request is missed. Switching it
|
|
18
|
+
* off is another call and takes effect immediately. And because what is stored
|
|
19
|
+
* is a deadline rather than a flag, a census somebody forgot expires on its
|
|
20
|
+
* own instead of taxing every request until the next release.
|
|
21
|
+
*
|
|
22
|
+
* ## Never longer than was asked for
|
|
23
|
+
*
|
|
24
|
+
* What is written is `census.armedUntilMs` - the deadline AFTER the census
|
|
25
|
+
* clamped the requested window. A restore therefore cannot extend a window
|
|
26
|
+
* past the clamp, and the two numbers cannot drift, because there is only one.
|
|
27
|
+
*
|
|
28
|
+
* ## `persisted` is read, never remembered
|
|
29
|
+
*
|
|
30
|
+
* The provider is rebuilt per request, so there is nowhere to keep "the last
|
|
31
|
+
* write worked". `status()` re-reads the row and compares it with the live
|
|
32
|
+
* census instead. That is one KV read on an operator gesture, and unlike a
|
|
33
|
+
* cached flag it cannot claim a window survives a restart when the write that
|
|
34
|
+
* would have made it survive failed.
|
|
35
|
+
*/
|
|
36
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
37
|
+
exports.RequestCensusService = exports.REQUEST_CENSUS_KEY = void 0;
|
|
38
|
+
exports.toRecord = toRecord;
|
|
39
|
+
const types_1 = require("@camstack/types");
|
|
40
|
+
const http_request_census_js_1 = require("../trpc/http-request-census.js");
|
|
41
|
+
/** The `system-settings` row this module owns. */
|
|
42
|
+
exports.REQUEST_CENSUS_KEY = 'http-request-census';
|
|
43
|
+
const SYSTEM_SETTINGS_COLLECTION = 'system-settings';
|
|
44
|
+
/**
|
|
45
|
+
* Arm / disarm / read the census, keeping the persisted deadline in step.
|
|
46
|
+
*/
|
|
47
|
+
class RequestCensusService {
|
|
48
|
+
census;
|
|
49
|
+
store;
|
|
50
|
+
logger;
|
|
51
|
+
now;
|
|
52
|
+
constructor(deps) {
|
|
53
|
+
this.census = deps.census;
|
|
54
|
+
this.store = deps.store;
|
|
55
|
+
this.logger = deps.logger;
|
|
56
|
+
this.now = deps.now ?? Date.now;
|
|
57
|
+
}
|
|
58
|
+
/** The window as it stands, plus whether it would survive a restart. */
|
|
59
|
+
async status() {
|
|
60
|
+
const record = await this.read();
|
|
61
|
+
return { ...this.census.snapshot(), persisted: this.matchesStored(record) };
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* `armMs: 0` disarms; anything positive arms for that long (clamped).
|
|
65
|
+
*
|
|
66
|
+
* The census is armed BEFORE the write, so a settings-store that is down
|
|
67
|
+
* still gives the operator a live measurement - it just says so, both in the
|
|
68
|
+
* response (`persisted: false`) and in the log. Silently reporting a durable
|
|
69
|
+
* arm that is not durable is how a whole boot window gets measured, lost to
|
|
70
|
+
* a restart, and blamed on the instrument.
|
|
71
|
+
*/
|
|
72
|
+
async set(input) {
|
|
73
|
+
const reportEveryMs = input.reportEveryMs ?? http_request_census_js_1.DEFAULT_REPORT_EVERY_MS;
|
|
74
|
+
if (input.armMs <= 0)
|
|
75
|
+
this.census.disarm('operator-disarmed');
|
|
76
|
+
else
|
|
77
|
+
this.census.arm(input.armMs, reportEveryMs);
|
|
78
|
+
const record = {
|
|
79
|
+
armedUntilMs: this.census.armedUntilMs,
|
|
80
|
+
reportEveryMs,
|
|
81
|
+
updatedAt: this.now(),
|
|
82
|
+
};
|
|
83
|
+
const persisted = await this.write(record);
|
|
84
|
+
this.logger?.info('http request census switched', {
|
|
85
|
+
meta: {
|
|
86
|
+
armed: this.census.armed,
|
|
87
|
+
armedUntilMs: this.census.armedUntilMs,
|
|
88
|
+
reportEveryMs,
|
|
89
|
+
persisted,
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
return { ...this.census.snapshot(), persisted };
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Re-arm the remainder of a window that was armed before this boot.
|
|
96
|
+
*
|
|
97
|
+
* Called once, before `app.listen`, so the census is already counting when
|
|
98
|
+
* the first client reconnects. Never re-writes the row: a restore that
|
|
99
|
+
* refreshed the deadline would make a forgotten census immortal across
|
|
100
|
+
* restarts, which is the one failure mode a deadline exists to prevent.
|
|
101
|
+
*/
|
|
102
|
+
async restore() {
|
|
103
|
+
const record = await this.read();
|
|
104
|
+
const until = record?.armedUntilMs;
|
|
105
|
+
if (typeof until !== 'number' || !Number.isFinite(until) || until <= 0)
|
|
106
|
+
return false;
|
|
107
|
+
const remainingMs = until - this.now();
|
|
108
|
+
if (remainingMs <= 0) {
|
|
109
|
+
this.logger?.info('http request census not restored - window already expired', {
|
|
110
|
+
meta: { armedUntilMs: until },
|
|
111
|
+
});
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
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', {
|
|
116
|
+
meta: { remainingMs, armedUntilMs: this.census.armedUntilMs },
|
|
117
|
+
});
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
/** True when the stored deadline is the one the live census is running. */
|
|
121
|
+
matchesStored(record) {
|
|
122
|
+
const stored = record?.armedUntilMs ?? 0;
|
|
123
|
+
return stored === this.census.armedUntilMs;
|
|
124
|
+
}
|
|
125
|
+
async read() {
|
|
126
|
+
try {
|
|
127
|
+
const raw = await this.store.get({
|
|
128
|
+
collection: SYSTEM_SETTINGS_COLLECTION,
|
|
129
|
+
key: exports.REQUEST_CENSUS_KEY,
|
|
130
|
+
});
|
|
131
|
+
return toRecord(raw);
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
// A read that fails is not a disarm: it changes nothing about the live
|
|
135
|
+
// census. It is logged because a branch that drops work silently reads
|
|
136
|
+
// as "never happened".
|
|
137
|
+
this.logger?.warn('http request census settings read failed', {
|
|
138
|
+
meta: { error: (0, types_1.errMsg)(err) },
|
|
139
|
+
});
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
async write(record) {
|
|
144
|
+
try {
|
|
145
|
+
await this.store.set({
|
|
146
|
+
collection: SYSTEM_SETTINGS_COLLECTION,
|
|
147
|
+
key: exports.REQUEST_CENSUS_KEY,
|
|
148
|
+
value: record,
|
|
149
|
+
});
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
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) } });
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
exports.RequestCensusService = RequestCensusService;
|
|
159
|
+
/** Structural read of the stored row. Anything unrecognised reads as absent. */
|
|
160
|
+
function toRecord(value) {
|
|
161
|
+
if (typeof value !== 'object' || value === null)
|
|
162
|
+
return null;
|
|
163
|
+
const armedUntilMs = Reflect.get(value, 'armedUntilMs');
|
|
164
|
+
const reportEveryMs = Reflect.get(value, 'reportEveryMs');
|
|
165
|
+
const updatedAt = Reflect.get(value, 'updatedAt');
|
|
166
|
+
return {
|
|
167
|
+
...(typeof armedUntilMs === 'number' && Number.isFinite(armedUntilMs) ? { armedUntilMs } : {}),
|
|
168
|
+
...(typeof reportEveryMs === 'number' && Number.isFinite(reportEveryMs)
|
|
169
|
+
? { reportEveryMs }
|
|
170
|
+
: {}),
|
|
171
|
+
...(typeof updatedAt === 'number' && Number.isFinite(updatedAt) ? { updatedAt } : {}),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
@@ -5391,6 +5391,15 @@ function createCapRouter_notificationRules(getProvider, createRemoteProxy) {
|
|
|
5391
5391
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
|
|
5392
5392
|
return p.getHistory(methodInput);
|
|
5393
5393
|
}),
|
|
5394
|
+
resolveArtifactUrl: trpc_middleware_js_1.adminProcedure
|
|
5395
|
+
.input(types_76.notificationRulesCapability.methods.resolveArtifactUrl.input.loose())
|
|
5396
|
+
.output(types_76.notificationRulesCapability.methods.resolveArtifactUrl.output)
|
|
5397
|
+
.query(async ({ input, ctx }) => {
|
|
5398
|
+
const { nodeId, ...methodInput } = input;
|
|
5399
|
+
const p = resolveProvider('notification-rules', nodeId, () => getProvider(ctx), createRemoteProxy);
|
|
5400
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
|
|
5401
|
+
return p.resolveArtifactUrl(methodInput);
|
|
5402
|
+
}),
|
|
5394
5403
|
listSnoozes: trpc_middleware_js_1.protectedProcedure
|
|
5395
5404
|
.input(types_76.notificationRulesCapability.methods.listSnoozes.input.loose())
|
|
5396
5405
|
.output(types_76.notificationRulesCapability.methods.listSnoozes.output)
|
|
@@ -7568,6 +7577,15 @@ function createCapRouter_recording(getProvider, createRemoteProxy) {
|
|
|
7568
7577
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
|
|
7569
7578
|
return p.readGopBytes(methodInput);
|
|
7570
7579
|
}),
|
|
7580
|
+
readWindowBytes: trpc_middleware_js_1.adminProcedure
|
|
7581
|
+
.input(types_92.recordingCapability.methods.readWindowBytes.input.loose())
|
|
7582
|
+
.output(types_92.recordingCapability.methods.readWindowBytes.output)
|
|
7583
|
+
.query(async ({ input, ctx }) => {
|
|
7584
|
+
const { nodeId, ...methodInput } = input;
|
|
7585
|
+
const p = resolveProvider('recording', nodeId, () => getProvider(ctx), createRemoteProxy);
|
|
7586
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
|
|
7587
|
+
return p.readWindowBytes(methodInput);
|
|
7588
|
+
}),
|
|
7571
7589
|
setDeviceConfig: trpc_middleware_js_1.adminProcedure
|
|
7572
7590
|
.input(types_92.recordingCapability.methods.setDeviceConfig.input.loose())
|
|
7573
7591
|
.output(types_92.recordingCapability.methods.setDeviceConfig.output)
|
|
@@ -9108,6 +9126,31 @@ function createCapRouter_system(getProvider, createRemoteProxy) {
|
|
|
9108
9126
|
const p = resolveProvider('system', input?.nodeId, () => getProvider(ctx), createRemoteProxy);
|
|
9109
9127
|
return p.detectSiteLocation();
|
|
9110
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
|
+
}),
|
|
9111
9154
|
});
|
|
9112
9155
|
}
|
|
9113
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
|
+
}
|
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* WHO is calling the hub over HTTP - measured at the transport, never inferred.
|
|
4
|
+
*
|
|
5
|
+
* ## The number this exists to explain
|
|
6
|
+
*
|
|
7
|
+
* `FleetReadCensus` (`packages/system/src/builtins/device-manager/fleet-read-census.ts`)
|
|
8
|
+
* measured `deviceManager.listAll` at **4 960 calls in a two-minute boot
|
|
9
|
+
* window**, ~1 017 rows each. It attributes the ADDONS correctly (~64 calls in
|
|
10
|
+
* total, carried as data over the cap channel) and says **nothing** about the
|
|
11
|
+
* other 4 900 - by construction: it lives in the row store and can only read
|
|
12
|
+
* the local JS stack, and for a call that arrived over the wire every frame
|
|
13
|
+
* above it is the same generic dispatcher regardless of who called.
|
|
14
|
+
*
|
|
15
|
+
* The HTTP layer is the one place that still holds the caller's identity:
|
|
16
|
+
* source IP, `User-Agent`, and the principal the bearer resolved to. So this
|
|
17
|
+
* census counts there.
|
|
18
|
+
*
|
|
19
|
+
* Two client-side fixes (admin-ui `GlobalSearch`, embed `EmbedGridPage`) moved
|
|
20
|
+
* the number from 4 888 to 4 960 - i.e. not at all. Guessing the next most
|
|
21
|
+
* plausible caller is exactly what this repo has already got wrong twice at
|
|
22
|
+
* half a day each. An attribution is a measurement or it is a guess.
|
|
23
|
+
*
|
|
24
|
+
* ## Reading the NEGATIVE - the result this is most likely to produce
|
|
25
|
+
*
|
|
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.
|
|
38
|
+
*
|
|
39
|
+
* A census that collected nothing still reports. Silence after an arm is
|
|
40
|
+
* indistinguishable from a census that never armed.
|
|
41
|
+
*
|
|
42
|
+
* ## Cost when disarmed
|
|
43
|
+
*
|
|
44
|
+
* {@link HttpRequestCensus.armed} is a plain boolean FIELD, not a clock
|
|
45
|
+
* comparison. Every caller checks it first and returns - no `Date.now()`, no
|
|
46
|
+
* string, no allocation. This sits on the hub's tRPC entry path at ~41
|
|
47
|
+
* requests/second; a diagnostic that costs something while switched off is a
|
|
48
|
+
* tax nobody remembers enabling.
|
|
49
|
+
*
|
|
50
|
+
* The window therefore closes on a TIMER rather than on a clock read taken per
|
|
51
|
+
* request. Stale timers are neutralised by a generation counter instead of
|
|
52
|
+
* being cleared, so no timer handle has to be stored or typed.
|
|
53
|
+
*/
|
|
54
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
55
|
+
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;
|
|
56
|
+
exports.shortenUserAgent = shortenUserAgent;
|
|
57
|
+
exports.parseTrpcProcedures = parseTrpcProcedures;
|
|
58
|
+
/** Route prefix the tRPC plugin is registered under (`main.ts`). */
|
|
59
|
+
exports.TRPC_URL_PREFIX = '/trpc/';
|
|
60
|
+
/**
|
|
61
|
+
* Longest window the census may be armed for.
|
|
62
|
+
*
|
|
63
|
+
* Thirty minutes rather than the ten `FleetReadCensus` allows, because the
|
|
64
|
+
* measurement this instrument exists for spans a RESTART: the operator arms
|
|
65
|
+
* it, restarts the hub, and the boot storm has to land inside the window that
|
|
66
|
+
* was already running. Ten minutes is not enough room for a container
|
|
67
|
+
* recreation plus a cold boot.
|
|
68
|
+
*/
|
|
69
|
+
exports.MAX_WINDOW_MS = 30 * 60_000;
|
|
70
|
+
/** Shortest useful window. Anything below this cannot contain a boot. */
|
|
71
|
+
exports.MIN_WINDOW_MS = 1_000;
|
|
72
|
+
/** Default cadence of the aggregated report line. */
|
|
73
|
+
exports.DEFAULT_REPORT_EVERY_MS = 30_000;
|
|
74
|
+
/**
|
|
75
|
+
* Floor on the report cadence.
|
|
76
|
+
*
|
|
77
|
+
* The report is ONE aggregated line. At the measured rate a per-request line
|
|
78
|
+
* would be 41 lines a second, which is itself an incident - and a cadence an
|
|
79
|
+
* operator could set to 100 ms would reproduce that with an aggregate.
|
|
80
|
+
*/
|
|
81
|
+
exports.MIN_REPORT_EVERY_MS = 5_000;
|
|
82
|
+
/**
|
|
83
|
+
* Bound on distinct `(procedure, ua, ip, principal)` groups held in memory.
|
|
84
|
+
*
|
|
85
|
+
* IPs and user-agents are attacker-influenced: a client rotating either would
|
|
86
|
+
* otherwise grow the map without limit inside an armed window. Overflow is
|
|
87
|
+
* COUNTED, never dropped silently - the totals stay exact, which is what the
|
|
88
|
+
* negative proof rests on.
|
|
89
|
+
*/
|
|
90
|
+
exports.MAX_GROUPS = 500;
|
|
91
|
+
/**
|
|
92
|
+
* Bound on distinct procedure names. The router's procedure set is closed and
|
|
93
|
+
* far below this; the bound exists so a garbage path cannot grow the map.
|
|
94
|
+
* Names beyond it fold into {@link PROCEDURE_OVERFLOW} rather than vanishing.
|
|
95
|
+
*/
|
|
96
|
+
exports.MAX_PROCEDURES = 500;
|
|
97
|
+
/** User-agent prefix kept in a group key. Full UA strings are long and their
|
|
98
|
+
* tail is build metadata that splits one client into many rows. */
|
|
99
|
+
exports.USER_AGENT_MAX_CHARS = 80;
|
|
100
|
+
/** Bound on procedures counted from one batched URL. tRPC's own `maxBatchSize`
|
|
101
|
+
* guards the router; this guards the census against a URL that never reaches
|
|
102
|
+
* a procedure at all. */
|
|
103
|
+
exports.MAX_BATCH_PROCEDURES = 200;
|
|
104
|
+
/** Synthetic name for batch entries beyond {@link MAX_BATCH_PROCEDURES}. */
|
|
105
|
+
exports.BATCH_OVERFLOW_PROCEDURE = '(batch-overflow)';
|
|
106
|
+
/** Synthetic name for procedures beyond {@link MAX_PROCEDURES}. */
|
|
107
|
+
exports.PROCEDURE_OVERFLOW = '(procedure-overflow)';
|
|
108
|
+
/** Placeholder used when a request carries no such signal. Never blank: an
|
|
109
|
+
* empty field reads as a logging defect rather than as an absent header. */
|
|
110
|
+
exports.UNKNOWN = 'unknown';
|
|
111
|
+
/** Group-key field separator. A character that cannot appear in a tRPC
|
|
112
|
+
* procedure path, so two different tuples can never collide into one row. */
|
|
113
|
+
const KEY_SEPARATOR = ' | ';
|
|
114
|
+
function defaultSchedule(fn, ms) {
|
|
115
|
+
// `unref` so an armed census never holds the process open at shutdown.
|
|
116
|
+
setTimeout(fn, ms).unref();
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Truncate a user-agent to a comparable prefix.
|
|
120
|
+
*
|
|
121
|
+
* Exported because the truncation is part of the group KEY: a spec that builds
|
|
122
|
+
* an expected key by hand must use the same rule, or it pins the wrong thing.
|
|
123
|
+
*/
|
|
124
|
+
function shortenUserAgent(ua) {
|
|
125
|
+
if (ua === null)
|
|
126
|
+
return exports.UNKNOWN;
|
|
127
|
+
const trimmed = ua.trim();
|
|
128
|
+
if (trimmed.length === 0)
|
|
129
|
+
return exports.UNKNOWN;
|
|
130
|
+
if (trimmed.length <= exports.USER_AGENT_MAX_CHARS)
|
|
131
|
+
return trimmed;
|
|
132
|
+
return `${trimmed.slice(0, exports.USER_AGENT_MAX_CHARS)}~`;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The procedures one tRPC HTTP request invokes.
|
|
136
|
+
*
|
|
137
|
+
* ## Why this is not `url.split(',')`
|
|
138
|
+
*
|
|
139
|
+
* tRPC splits the path on `,` **only when `batch=1`**, and only for the JSON
|
|
140
|
+
* content-type handler; `multipart/form-data` and `application/octet-stream`
|
|
141
|
+
* are always single-call, and a non-batched path containing a comma is ONE
|
|
142
|
+
* procedure name. Counting a batch as one call undercounts by the batch factor
|
|
143
|
+
* - in exactly the direction that would clear an innocent transport - and
|
|
144
|
+
* splitting a non-batch path overcounts. Both rules are mirrored here
|
|
145
|
+
* deliberately from `@trpc/server`'s `jsonContentTypeHandler.parse`, and both
|
|
146
|
+
* are pinned by spec.
|
|
147
|
+
*
|
|
148
|
+
* Returns `[]` for a URL that is not under the tRPC prefix, and for the bare
|
|
149
|
+
* prefix with no path.
|
|
150
|
+
*/
|
|
151
|
+
function parseTrpcProcedures(url, contentType) {
|
|
152
|
+
const queryAt = url.indexOf('?');
|
|
153
|
+
const pathname = queryAt === -1 ? url : url.slice(0, queryAt);
|
|
154
|
+
const query = queryAt === -1 ? '' : url.slice(queryAt + 1);
|
|
155
|
+
if (!pathname.startsWith(exports.TRPC_URL_PREFIX))
|
|
156
|
+
return [];
|
|
157
|
+
// The plugin route is `/trpc/:path` - one segment. Anything after a further
|
|
158
|
+
// `/` is not part of the procedure path.
|
|
159
|
+
const rest = pathname.slice(exports.TRPC_URL_PREFIX.length);
|
|
160
|
+
const slashAt = rest.indexOf('/');
|
|
161
|
+
const rawPath = slashAt === -1 ? rest : rest.slice(0, slashAt);
|
|
162
|
+
if (rawPath.length === 0)
|
|
163
|
+
return [];
|
|
164
|
+
const decoded = decodePathSafely(rawPath);
|
|
165
|
+
if (!isBatchCall(query, contentType)) {
|
|
166
|
+
const single = decoded.trim();
|
|
167
|
+
return single.length === 0 ? [] : [single];
|
|
168
|
+
}
|
|
169
|
+
const out = [];
|
|
170
|
+
let overflowed = false;
|
|
171
|
+
for (const part of decoded.split(',')) {
|
|
172
|
+
const name = part.trim();
|
|
173
|
+
if (name.length === 0)
|
|
174
|
+
continue;
|
|
175
|
+
if (out.length >= exports.MAX_BATCH_PROCEDURES) {
|
|
176
|
+
overflowed = true;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
out.push(name);
|
|
180
|
+
}
|
|
181
|
+
if (overflowed)
|
|
182
|
+
out.push(exports.BATCH_OVERFLOW_PROCEDURE);
|
|
183
|
+
return out;
|
|
184
|
+
}
|
|
185
|
+
/** `decodeURIComponent` throws on a malformed escape. A garbage path is still
|
|
186
|
+
* a request that arrived, so it is counted under its raw text rather than
|
|
187
|
+
* dropped - a dropped request is a hole in the total the negative rests on. */
|
|
188
|
+
function decodePathSafely(raw) {
|
|
189
|
+
try {
|
|
190
|
+
return decodeURIComponent(raw);
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return raw;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* `batch=1` in the query string, and a content-type that can batch.
|
|
198
|
+
*
|
|
199
|
+
* The two non-JSON handlers hard-code `isBatchCall: false` regardless of the
|
|
200
|
+
* query string, so honouring `batch=1` for them would split a procedure name
|
|
201
|
+
* that legitimately contains a comma.
|
|
202
|
+
*/
|
|
203
|
+
function isBatchCall(query, contentType) {
|
|
204
|
+
if (!hasBatchFlag(query))
|
|
205
|
+
return false;
|
|
206
|
+
if (typeof contentType !== 'string')
|
|
207
|
+
return true;
|
|
208
|
+
const lower = contentType.toLowerCase();
|
|
209
|
+
if (lower.startsWith('multipart/form-data'))
|
|
210
|
+
return false;
|
|
211
|
+
if (lower.startsWith('application/octet-stream'))
|
|
212
|
+
return false;
|
|
213
|
+
return true;
|
|
214
|
+
}
|
|
215
|
+
function hasBatchFlag(query) {
|
|
216
|
+
if (query.length === 0)
|
|
217
|
+
return false;
|
|
218
|
+
for (const pair of query.split('&')) {
|
|
219
|
+
if (pair === 'batch=1')
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
return false;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Armed-window counter for tRPC requests arriving over HTTP.
|
|
226
|
+
*
|
|
227
|
+
* Disarmed it is one boolean read at every call site and nothing else.
|
|
228
|
+
*/
|
|
229
|
+
class HttpRequestCensus {
|
|
230
|
+
now;
|
|
231
|
+
schedule;
|
|
232
|
+
/** The ONLY thing a disarmed request path reads. */
|
|
233
|
+
isArmed = false;
|
|
234
|
+
/** Stamps every scheduled tick. A tick whose stamp is stale belongs to a
|
|
235
|
+
* window that was re-armed or disarmed, and does nothing. */
|
|
236
|
+
generation = 0;
|
|
237
|
+
armedAt = 0;
|
|
238
|
+
closedAt = 0;
|
|
239
|
+
currentWindowMs = 0;
|
|
240
|
+
currentReportEveryMs = exports.DEFAULT_REPORT_EVERY_MS;
|
|
241
|
+
httpRequests = 0;
|
|
242
|
+
batchedRequests = 0;
|
|
243
|
+
procedureCalls = 0;
|
|
244
|
+
wsConnections = 0;
|
|
245
|
+
unattributedCalls = 0;
|
|
246
|
+
byProcedure = new Map();
|
|
247
|
+
byGroup = new Map();
|
|
248
|
+
logger = null;
|
|
249
|
+
constructor(options = {}) {
|
|
250
|
+
this.now = options.now ?? Date.now;
|
|
251
|
+
this.schedule = options.schedule ?? defaultSchedule;
|
|
252
|
+
}
|
|
253
|
+
/** The report sink. Absent until boot wires it; a census with no logger
|
|
254
|
+
* still counts and still answers `snapshot()`. */
|
|
255
|
+
setLogger(logger) {
|
|
256
|
+
this.logger = logger;
|
|
257
|
+
}
|
|
258
|
+
get armed() {
|
|
259
|
+
return this.isArmed;
|
|
260
|
+
}
|
|
261
|
+
/** Epoch ms the current window closes at. 0 when disarmed. */
|
|
262
|
+
get armedUntilMs() {
|
|
263
|
+
return this.isArmed ? this.armedAt + this.currentWindowMs : 0;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Arm for `windowMs`, clamped to [{@link MIN_WINDOW_MS}, {@link MAX_WINDOW_MS}].
|
|
267
|
+
*
|
|
268
|
+
* Re-arming CLEARS the counts and restarts the window: two overlapping
|
|
269
|
+
* measurements in one table is a table nobody can divide by a duration.
|
|
270
|
+
*/
|
|
271
|
+
arm(windowMs, reportEveryMs = exports.DEFAULT_REPORT_EVERY_MS) {
|
|
272
|
+
const clampedWindow = clamp(windowMs, exports.MIN_WINDOW_MS, exports.MAX_WINDOW_MS);
|
|
273
|
+
const clampedReport = clamp(reportEveryMs, exports.MIN_REPORT_EVERY_MS, clampedWindow);
|
|
274
|
+
this.reset();
|
|
275
|
+
this.generation += 1;
|
|
276
|
+
this.isArmed = true;
|
|
277
|
+
this.armedAt = this.now();
|
|
278
|
+
this.closedAt = 0;
|
|
279
|
+
this.currentWindowMs = clampedWindow;
|
|
280
|
+
this.currentReportEveryMs = clampedReport;
|
|
281
|
+
this.scheduleTick(this.generation);
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Close the window now and emit the final report.
|
|
285
|
+
*
|
|
286
|
+
* The counts SURVIVE - a window may be read as many times as the operator
|
|
287
|
+
* likes after it closed, and re-arming in order to read would throw away
|
|
288
|
+
* exactly the numbers being asked for.
|
|
289
|
+
*/
|
|
290
|
+
disarm(reason) {
|
|
291
|
+
if (!this.isArmed)
|
|
292
|
+
return;
|
|
293
|
+
this.isArmed = false;
|
|
294
|
+
this.closedAt = this.now();
|
|
295
|
+
this.generation += 1;
|
|
296
|
+
this.report(reason);
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Count one HTTP request.
|
|
300
|
+
*
|
|
301
|
+
* Callers check {@link armed} FIRST so nothing is built for a disarmed
|
|
302
|
+
* census; the guard is repeated here so a request already in flight when the
|
|
303
|
+
* window closed cannot land in a window it does not belong to.
|
|
304
|
+
*/
|
|
305
|
+
observeHttpRequest(observation) {
|
|
306
|
+
if (!this.isArmed)
|
|
307
|
+
return;
|
|
308
|
+
if (observation.procedures.length === 0)
|
|
309
|
+
return;
|
|
310
|
+
this.httpRequests += 1;
|
|
311
|
+
if (observation.procedures.length > 1)
|
|
312
|
+
this.batchedRequests += 1;
|
|
313
|
+
const userAgent = shortenUserAgent(observation.userAgent);
|
|
314
|
+
const ip = observation.ip ?? exports.UNKNOWN;
|
|
315
|
+
const principal = observation.principal;
|
|
316
|
+
for (const procedure of observation.procedures) {
|
|
317
|
+
this.procedureCalls += 1;
|
|
318
|
+
this.countProcedure(procedure);
|
|
319
|
+
const key = [procedure, userAgent, ip, principal].join(KEY_SEPARATOR);
|
|
320
|
+
const group = this.byGroup.get(key);
|
|
321
|
+
if (group !== undefined) {
|
|
322
|
+
group.calls += 1;
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (this.byGroup.size >= exports.MAX_GROUPS) {
|
|
326
|
+
this.unattributedCalls += 1;
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
this.byGroup.set(key, { procedure, userAgent, ip, principal, calls: 1 });
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Count one tRPC WebSocket connection opening.
|
|
334
|
+
*
|
|
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".
|
|
339
|
+
*/
|
|
340
|
+
observeWsConnection() {
|
|
341
|
+
if (!this.isArmed)
|
|
342
|
+
return;
|
|
343
|
+
this.wsConnections += 1;
|
|
344
|
+
}
|
|
345
|
+
/** Everything the window measured, busiest first. */
|
|
346
|
+
snapshot(limit = exports.MAX_GROUPS) {
|
|
347
|
+
const elapsedMs = this.elapsedMs();
|
|
348
|
+
const perMin = (calls) => elapsedMs === 0 ? 0 : Math.round((calls * 60_000) / elapsedMs);
|
|
349
|
+
const procedures = [...this.byProcedure.entries()]
|
|
350
|
+
.map(([procedure, count]) => ({
|
|
351
|
+
procedure,
|
|
352
|
+
calls: count.calls,
|
|
353
|
+
perMin: perMin(count.calls),
|
|
354
|
+
}))
|
|
355
|
+
.toSorted((a, b) => b.calls - a.calls);
|
|
356
|
+
const groups = [...this.byGroup.values()]
|
|
357
|
+
.map((group) => ({
|
|
358
|
+
procedure: group.procedure,
|
|
359
|
+
userAgent: group.userAgent,
|
|
360
|
+
ip: group.ip,
|
|
361
|
+
principal: group.principal,
|
|
362
|
+
calls: group.calls,
|
|
363
|
+
perMin: perMin(group.calls),
|
|
364
|
+
}))
|
|
365
|
+
.toSorted((a, b) => b.calls - a.calls);
|
|
366
|
+
return {
|
|
367
|
+
armed: this.isArmed,
|
|
368
|
+
elapsedMs,
|
|
369
|
+
windowMs: this.currentWindowMs,
|
|
370
|
+
armedUntilMs: this.armedUntilMs,
|
|
371
|
+
httpRequests: this.httpRequests,
|
|
372
|
+
batchedRequests: this.batchedRequests,
|
|
373
|
+
procedureCalls: this.procedureCalls,
|
|
374
|
+
wsConnections: this.wsConnections,
|
|
375
|
+
distinctGroups: this.byGroup.size,
|
|
376
|
+
unattributedCalls: this.unattributedCalls,
|
|
377
|
+
procedures: procedures.slice(0, limit),
|
|
378
|
+
groups: groups.slice(0, limit),
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Emit ONE aggregated line.
|
|
383
|
+
*
|
|
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.
|
|
386
|
+
*/
|
|
387
|
+
report(phase) {
|
|
388
|
+
const logger = this.logger;
|
|
389
|
+
if (logger === null)
|
|
390
|
+
return;
|
|
391
|
+
const snap = this.snapshot();
|
|
392
|
+
logger.info('http request census', {
|
|
393
|
+
meta: {
|
|
394
|
+
phase,
|
|
395
|
+
armed: snap.armed,
|
|
396
|
+
elapsedMs: snap.elapsedMs,
|
|
397
|
+
windowMs: snap.windowMs,
|
|
398
|
+
httpRequests: snap.httpRequests,
|
|
399
|
+
batchedRequests: snap.batchedRequests,
|
|
400
|
+
procedureCalls: snap.procedureCalls,
|
|
401
|
+
wsConnections: snap.wsConnections,
|
|
402
|
+
distinctGroups: snap.distinctGroups,
|
|
403
|
+
unattributedCalls: snap.unattributedCalls,
|
|
404
|
+
procedures: snap.procedures.slice(0, REPORTED_PROCEDURES),
|
|
405
|
+
top: snap.groups.slice(0, REPORTED_GROUPS).map((group) => ({
|
|
406
|
+
procedure: group.procedure,
|
|
407
|
+
ua: group.userAgent,
|
|
408
|
+
ip: group.ip,
|
|
409
|
+
principal: group.principal,
|
|
410
|
+
calls: group.calls,
|
|
411
|
+
perMin: group.perMin,
|
|
412
|
+
})),
|
|
413
|
+
},
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
countProcedure(procedure) {
|
|
417
|
+
const existing = this.byProcedure.get(procedure);
|
|
418
|
+
if (existing !== undefined) {
|
|
419
|
+
existing.calls += 1;
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
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;
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
this.byProcedure.set(procedure, { calls: 1 });
|
|
431
|
+
}
|
|
432
|
+
elapsedMs() {
|
|
433
|
+
if (this.armedAt === 0)
|
|
434
|
+
return 0;
|
|
435
|
+
const end = this.isArmed ? this.now() : this.closedAt;
|
|
436
|
+
return Math.max(0, end - this.armedAt);
|
|
437
|
+
}
|
|
438
|
+
reset() {
|
|
439
|
+
this.byProcedure.clear();
|
|
440
|
+
this.byGroup.clear();
|
|
441
|
+
this.httpRequests = 0;
|
|
442
|
+
this.batchedRequests = 0;
|
|
443
|
+
this.procedureCalls = 0;
|
|
444
|
+
this.wsConnections = 0;
|
|
445
|
+
this.unattributedCalls = 0;
|
|
446
|
+
}
|
|
447
|
+
scheduleTick(generation) {
|
|
448
|
+
this.schedule(() => {
|
|
449
|
+
if (generation !== this.generation || !this.isArmed)
|
|
450
|
+
return;
|
|
451
|
+
if (this.now() - this.armedAt >= this.currentWindowMs) {
|
|
452
|
+
this.disarm('window-closed');
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
this.report('interval');
|
|
456
|
+
this.scheduleTick(generation);
|
|
457
|
+
}, this.currentReportEveryMs);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
exports.HttpRequestCensus = HttpRequestCensus;
|
|
461
|
+
/** Per-procedure rows carried on one report line. The router's procedure set
|
|
462
|
+
* is small; this is a guard against a garbage path, not a real cut. */
|
|
463
|
+
const REPORTED_PROCEDURES = 40;
|
|
464
|
+
/** Caller groups carried on one report line. Enough to name a culprit,
|
|
465
|
+
* bounded so one line stays a line. */
|
|
466
|
+
const REPORTED_GROUPS = 25;
|
|
467
|
+
function clamp(value, min, max) {
|
|
468
|
+
if (!Number.isFinite(value))
|
|
469
|
+
return min;
|
|
470
|
+
return Math.min(Math.max(value, min), max);
|
|
471
|
+
}
|
|
@@ -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
|
+
}
|
package/dist/main.js
CHANGED
|
@@ -66,7 +66,12 @@ const server_upload_1 = require("./api/server-upload");
|
|
|
66
66
|
const sse_no_compression_js_1 = require("./api/sse-no-compression.js");
|
|
67
67
|
const precompressed_asset_js_1 = require("./api/static/precompressed-asset.js");
|
|
68
68
|
const spa_static_1 = require("./api/static/spa-static");
|
|
69
|
+
const cap_providers_1 = require("./api/core/cap-providers");
|
|
70
|
+
const logging_settings_1 = require("./api/core/logging-settings");
|
|
71
|
+
const request_census_settings_1 = require("./api/core/request-census-settings");
|
|
69
72
|
const core_cap_bridge_1 = require("./api/trpc/core-cap-bridge");
|
|
73
|
+
const http_request_census_hook_1 = require("./api/trpc/http-request-census-hook");
|
|
74
|
+
const http_request_census_singleton_1 = require("./api/trpc/http-request-census.singleton");
|
|
70
75
|
const trpc_context_1 = require("./api/trpc/trpc.context");
|
|
71
76
|
const trpc_router_1 = require("./api/trpc/trpc.router");
|
|
72
77
|
const trpc_error_principal_1 = require("./api/trpc/trpc-error-principal");
|
|
@@ -487,6 +492,12 @@ async function bootstrap() {
|
|
|
487
492
|
catch (err) {
|
|
488
493
|
console.warn('[bootstrap] device-name cache seed skipped:', err instanceof Error ? err.message : err);
|
|
489
494
|
}
|
|
495
|
+
// The process-wide HTTP request census. Disarmed here and for the rest of
|
|
496
|
+
// this boot unless `restore()` (below, just before `listen`) finds a window
|
|
497
|
+
// an operator armed earlier. The logger is attached now so a restored census
|
|
498
|
+
// has somewhere to report before the first request arrives.
|
|
499
|
+
const httpRequestCensus = (0, http_request_census_singleton_1.getHttpRequestCensus)();
|
|
500
|
+
httpRequestCensus.setLogger(loggingService.createLogger('tRPC'));
|
|
490
501
|
try {
|
|
491
502
|
const authService = app.get(auth_service_1.AuthService);
|
|
492
503
|
// Normally already built and bridged onto the mesh in `beforeAddonBoot`
|
|
@@ -506,11 +517,19 @@ async function bootstrap() {
|
|
|
506
517
|
prefix: '/trpc',
|
|
507
518
|
trpcOptions: {
|
|
508
519
|
router: appRouter,
|
|
509
|
-
createContext: ({ req }) =>
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
520
|
+
createContext: async ({ req }) => {
|
|
521
|
+
const trpcCtx = await (0, trpc_context_1.createTrpcContext)(req, authService, addonRegistry, shareTokenService,
|
|
522
|
+
// A bearer refused for NOT being an API credential never reaches a
|
|
523
|
+
// procedure, so `onError` below never sees it — the refusal would
|
|
524
|
+
// be silent without this. Same reason `gateAddonJwt` logs (D103).
|
|
525
|
+
app.get(logging_service_1.LoggingService).createLogger('tRPC'));
|
|
526
|
+
// WHO called, counted here because this is the first point at which
|
|
527
|
+
// a principal exists AND the only one tRPC runs exactly once per
|
|
528
|
+
// HTTP request (batched or not). Disarmed this is a boolean read and
|
|
529
|
+
// a return — see `http-request-census-hook.ts`.
|
|
530
|
+
(0, http_request_census_hook_1.recordTrpcHttpRequest)(httpRequestCensus, req, trpcCtx.user);
|
|
531
|
+
return trpcCtx;
|
|
532
|
+
},
|
|
514
533
|
onError: ({ path: trpcPath, error, ctx, }) => {
|
|
515
534
|
const trpcLogger = app.get(logging_service_1.LoggingService).createLogger('tRPC');
|
|
516
535
|
trpcLogger.warn('tRPC error', {
|
|
@@ -1071,7 +1090,14 @@ async function bootstrap() {
|
|
|
1071
1090
|
(0, ws_1.applyWSSHandler)({
|
|
1072
1091
|
wss,
|
|
1073
1092
|
router: appRouter,
|
|
1074
|
-
createContext: (opts) =>
|
|
1093
|
+
createContext: (opts) => {
|
|
1094
|
+
// One count per CONNECTION, not per call: the WS adapter builds one
|
|
1095
|
+
// context per socket and per-message procedure names never reach this
|
|
1096
|
+
// layer. It is here so a near-zero HTTP total reads as "the traffic
|
|
1097
|
+
// went to the other plane" rather than as "the census was off".
|
|
1098
|
+
httpRequestCensus.observeWsConnection();
|
|
1099
|
+
return (0, trpc_context_1.createWsTrpcContext)(opts, authService, addonRegistry, shareTokenService, app.get(logging_service_1.LoggingService).createLogger('tRPC:ws'));
|
|
1100
|
+
},
|
|
1075
1101
|
onError: ({ path: trpcPath, error, ctx, }) => {
|
|
1076
1102
|
const trpcLogger = app.get(logging_service_1.LoggingService).createLogger('tRPC:ws');
|
|
1077
1103
|
trpcLogger.warn('tRPC error', {
|
|
@@ -1303,6 +1329,34 @@ async function bootstrap() {
|
|
|
1303
1329
|
console.error('[bootstrap] Failed to set up viewer UI static serving:', err);
|
|
1304
1330
|
}
|
|
1305
1331
|
};
|
|
1332
|
+
// Establish the logging mirror and re-arm any diagnostic window that was
|
|
1333
|
+
// armed BEFORE this boot.
|
|
1334
|
+
//
|
|
1335
|
+
// Deliberately here, immediately before `listen`: the tRPC plugin is
|
|
1336
|
+
// registered long before this point but the socket is not open yet, so the
|
|
1337
|
+
// census is already counting when the first client reconnects — which is
|
|
1338
|
+
// the entire window the boot storm lives in. Awaited (one KV read) rather
|
|
1339
|
+
// than fired and forgotten, because "it will probably finish in time" is not
|
|
1340
|
+
// a property a measurement can rest on. It must never be the reason a hub
|
|
1341
|
+
// fails to boot, hence the catch — and a restore that fails leaves the
|
|
1342
|
+
// mirror at its default rather than inventing a level (D49).
|
|
1343
|
+
try {
|
|
1344
|
+
const settingsStore = (0, cap_providers_1.buildSettingsStoreGateway)(capabilityRegistry);
|
|
1345
|
+
const loggingLogger = loggingService.createLogger('logging-settings');
|
|
1346
|
+
await new logging_settings_1.LoggingSettingsService({
|
|
1347
|
+
store: settingsStore,
|
|
1348
|
+
gate: (0, system_1.getLoggingGate)(),
|
|
1349
|
+
requestCensus: new request_census_settings_1.RequestCensusService({
|
|
1350
|
+
census: httpRequestCensus,
|
|
1351
|
+
store: settingsStore,
|
|
1352
|
+
logger: loggingLogger,
|
|
1353
|
+
}),
|
|
1354
|
+
logger: loggingLogger,
|
|
1355
|
+
}).restore();
|
|
1356
|
+
}
|
|
1357
|
+
catch (censusErr) {
|
|
1358
|
+
console.warn('[bootstrap] logging settings restore skipped:', censusErr instanceof Error ? censusErr.message : censusErr);
|
|
1359
|
+
}
|
|
1306
1360
|
try {
|
|
1307
1361
|
const listenHost = (0, system_1.allFamiliesListenHost)(host).host;
|
|
1308
1362
|
try {
|