@netgreener/runtime 0.1.9 → 0.1.11
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/CHANGELOG.md +20 -0
- package/dist/aggregator.d.ts +2 -0
- package/dist/aggregator.js +33 -13
- package/dist/analyze/buildResourceFindings.d.ts +1 -1
- package/dist/analyze/buildResourceFindings.js +4 -2
- package/dist/analyze/findingGuidance.d.ts +14 -0
- package/dist/analyze/findingGuidance.js +52 -0
- package/dist/analyze/index.d.ts +3 -2
- package/dist/analyze/index.js +3 -2
- package/dist/analyze/projectScan.d.ts +3 -1
- package/dist/analyze/projectScan.js +29 -6
- package/dist/analyze/resourceFindingCandidate.d.ts +6 -0
- package/dist/analyze/resourceFindingCandidate.js +11 -0
- package/dist/analyze/serviceDiscovery.d.ts +23 -1
- package/dist/analyze/serviceDiscovery.js +164 -4
- package/dist/externalApiMeter.d.ts +8 -1
- package/dist/externalApiMeter.js +118 -25
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/managedCollectorLauncher.d.ts +2 -1
- package/dist/managedCollectorLauncher.js +2 -1
- package/dist/mcpToolMeter.d.ts +101 -0
- package/dist/mcpToolMeter.js +496 -0
- package/dist/next.d.ts +28 -0
- package/dist/next.js +143 -10
- package/dist/nextConfig.d.ts +34 -0
- package/dist/nextConfig.js +73 -0
- package/dist/nextEntryTransform.d.ts +9 -0
- package/dist/nextEntryTransform.js +181 -0
- package/dist/runtime.d.ts +12 -6
- package/dist/runtime.js +113 -52
- package/dist/runtimeHealth.js +1 -1
- package/dist/tenantContext.d.ts +3 -0
- package/dist/tenantContext.js +35 -9
- package/dist/types.d.ts +8 -0
- package/examples/azure-functions-gate/.funcignore +6 -0
- package/examples/azure-functions-gate/README.md +25 -0
- package/examples/azure-functions-gate/host.json +15 -0
- package/examples/azure-functions-gate/package-lock.json +161 -0
- package/examples/azure-functions-gate/package.json +14 -0
- package/examples/azure-functions-gate/src/functions/health.js +27 -0
- package/fixtures/git/canonical_git_key_vectors.v1.json +66 -0
- package/loaders/next-entry-loader.cjs +14 -0
- package/package.json +3 -1
package/dist/runtime.js
CHANGED
|
@@ -8,10 +8,30 @@ import { attachWindowTenantToRunContext, getTenantContext, tenantConfigFromRunti
|
|
|
8
8
|
import { enrichRunContextForAnomaly } from './runContextEnrichment.js';
|
|
9
9
|
import { getOccupancyTracker } from './occupancyTracker.js';
|
|
10
10
|
import { getExternalAggregator, getOriginalFetch, installOutboundInstrumentation, } from './externalApiMeter.js';
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
11
|
+
import { buildMcpLatencyV0, getMcpToolLedger, } from './mcpToolMeter.js';
|
|
12
|
+
import { CPU_SOURCE_PROCESS, MEMORY_SOURCE_PROCESS, beginProcessResourceSample, endProcessResourceSample, } from './processResources.js';
|
|
13
13
|
import { buildRuntimeHealthV0, markHooksActive, mergeHealthIntoMetadata, noteExportAttempt, noteExportMode, noteExportResult, noteFlushSkippedInFlight, _resetRuntimeHealthForTests, } from './runtimeHealth.js';
|
|
14
14
|
import { resolveLifecycle, } from './lifecycle.js';
|
|
15
|
+
function vercelDeploymentHosts() {
|
|
16
|
+
const hosts = [];
|
|
17
|
+
for (const key of ['VERCEL_URL', 'VERCEL_BRANCH_URL', 'VERCEL_PROJECT_PRODUCTION_URL']) {
|
|
18
|
+
const raw = String(process.env[key] || '').trim();
|
|
19
|
+
if (!raw)
|
|
20
|
+
continue;
|
|
21
|
+
try {
|
|
22
|
+
const host = (raw.includes('://') ? new URL(raw).hostname : raw.split('/')[0] || '')
|
|
23
|
+
.toLowerCase()
|
|
24
|
+
.replace(/^\*\./, '')
|
|
25
|
+
.replace(/^www\./, '');
|
|
26
|
+
if (host)
|
|
27
|
+
hosts.push(host);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
/* ignore a malformed deployment host */
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return hosts;
|
|
34
|
+
}
|
|
15
35
|
/**
|
|
16
36
|
* Process-wide runtime controller: record samples, periodic flush, shutdown flush.
|
|
17
37
|
* Ephemeral lifecycle skips the periodic timer and flushes at invoke/request idle.
|
|
@@ -32,11 +52,9 @@ export class NetGreenerRuntime {
|
|
|
32
52
|
/** In-flight HTTP/task units — gates ephemeral idle flush. */
|
|
33
53
|
inFlight = 0;
|
|
34
54
|
invokeFlushScheduled = false;
|
|
35
|
-
/**
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
*/
|
|
39
|
-
stickyWindowId = null;
|
|
55
|
+
/** Exact pending window; observations arriving during retries stay separate. */
|
|
56
|
+
pendingPayload = null;
|
|
57
|
+
cpuWindowMark = beginProcessResourceSample();
|
|
40
58
|
constructor(opts = {}) {
|
|
41
59
|
this.config = opts.config ?? loadRuntimeConfig();
|
|
42
60
|
this.collector = opts.collector ?? 'express_middleware';
|
|
@@ -60,10 +78,13 @@ export class NetGreenerRuntime {
|
|
|
60
78
|
if (this.outboundInstalled || !this.enabled)
|
|
61
79
|
return;
|
|
62
80
|
this.outboundInstalled = true;
|
|
63
|
-
const firstPartyHosts =
|
|
64
|
-
.
|
|
65
|
-
|
|
66
|
-
|
|
81
|
+
const firstPartyHosts = [
|
|
82
|
+
...String(process.env.NETGREENER_FIRST_PARTY_HOSTS || '')
|
|
83
|
+
.split(',')
|
|
84
|
+
.map((h) => h.trim().toLowerCase().replace(/^\*\./, '').replace(/^www\./, ''))
|
|
85
|
+
.filter(Boolean),
|
|
86
|
+
...vercelDeploymentHosts(),
|
|
87
|
+
];
|
|
67
88
|
try {
|
|
68
89
|
const apiHost = new URL(this.config.apiUrl).hostname;
|
|
69
90
|
const excluded = [...(apiHost ? [apiHost] : []), ...firstPartyHosts];
|
|
@@ -109,12 +130,18 @@ export class NetGreenerRuntime {
|
|
|
109
130
|
/**
|
|
110
131
|
* Mark end of an inbound request/task. In ephemeral mode, schedules a flush
|
|
111
132
|
* when no requests remain in flight (safe under concurrency).
|
|
133
|
+
*
|
|
134
|
+
* ``deferInvokeFlush`` only skips that idle flush. The Next.js adapter uses
|
|
135
|
+
* it so the upload runs from ``after()`` / ``waitUntil`` after the response
|
|
136
|
+
* closes. Express, Fastify, and Lambda callers keep the default.
|
|
112
137
|
*/
|
|
113
|
-
endRequest() {
|
|
138
|
+
endRequest(opts) {
|
|
114
139
|
if (this.inFlight > 0)
|
|
115
140
|
this.inFlight -= 1;
|
|
116
141
|
if (this.lifecycle !== 'ephemeral')
|
|
117
142
|
return;
|
|
143
|
+
if (opts?.deferInvokeFlush)
|
|
144
|
+
return;
|
|
118
145
|
if (this.invokeFlushScheduled)
|
|
119
146
|
return;
|
|
120
147
|
this.invokeFlushScheduled = true;
|
|
@@ -151,7 +178,7 @@ export class NetGreenerRuntime {
|
|
|
151
178
|
const serviceUnit = `${sample.method.toUpperCase()} ${sample.path}`;
|
|
152
179
|
this.aggregator.record({
|
|
153
180
|
serviceUnit,
|
|
154
|
-
unitType: 'http_route',
|
|
181
|
+
unitType: sample.unitType || 'http_route',
|
|
155
182
|
durationMs: sample.durationMs,
|
|
156
183
|
error: sample.statusCode >= 400,
|
|
157
184
|
tenantId: getTenantContext()?.tenantId ?? null,
|
|
@@ -178,6 +205,28 @@ export class NetGreenerRuntime {
|
|
|
178
205
|
...(sample.peakRssKb !== undefined ? { peakRssKb: sample.peakRssKb } : {}),
|
|
179
206
|
});
|
|
180
207
|
}
|
|
208
|
+
async exportPendingWindow() {
|
|
209
|
+
const payload = this.pendingPayload;
|
|
210
|
+
noteExportAttempt(this.exporter.mode);
|
|
211
|
+
let result;
|
|
212
|
+
try {
|
|
213
|
+
result = await this.exporter.exportRunSessionWindow(this.config, structuredClone(payload), this.uploadFetch());
|
|
214
|
+
}
|
|
215
|
+
catch (err) {
|
|
216
|
+
result = { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
217
|
+
}
|
|
218
|
+
noteExportResult(result.ok, result.ok ? undefined : 'error' in result ? result.error : 'export_failed');
|
|
219
|
+
if (result.ok)
|
|
220
|
+
this.pendingPayload = null;
|
|
221
|
+
// Observers must not mutate a pending retry or turn an ACK into a retry.
|
|
222
|
+
try {
|
|
223
|
+
this.onFlush?.(result, structuredClone(payload));
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
/* Export state is independent of application observer failures. */
|
|
227
|
+
}
|
|
228
|
+
return result;
|
|
229
|
+
}
|
|
181
230
|
async flush(kind = 'manual') {
|
|
182
231
|
if (!this.enabled)
|
|
183
232
|
return null;
|
|
@@ -185,26 +234,35 @@ export class NetGreenerRuntime {
|
|
|
185
234
|
noteFlushSkippedInFlight();
|
|
186
235
|
return null;
|
|
187
236
|
}
|
|
237
|
+
if (this.pendingPayload) {
|
|
238
|
+
this.flushing = true;
|
|
239
|
+
try {
|
|
240
|
+
return await this.exportPendingWindow();
|
|
241
|
+
}
|
|
242
|
+
finally {
|
|
243
|
+
this.flushing = false;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
188
246
|
const externalAgg = getExternalAggregator();
|
|
189
247
|
const hasRuntime = this.aggregator.hasData();
|
|
190
248
|
const hasExternal = externalAgg.hasData();
|
|
191
249
|
if (!hasRuntime && !hasExternal)
|
|
192
250
|
return null;
|
|
193
251
|
this.flushing = true;
|
|
252
|
+
let mcpSnapshot = null;
|
|
194
253
|
noteExportMode(this.exporter.mode);
|
|
195
254
|
const snapshot = hasRuntime ? this.aggregator.takeSnapshot() : null;
|
|
196
255
|
const externalSnapshot = hasExternal ? externalAgg.takeSnapshot() : null;
|
|
256
|
+
const previousCpuMark = this.cpuWindowMark;
|
|
197
257
|
try {
|
|
198
258
|
const windowStartedMs = snapshot
|
|
199
259
|
? snapshot.windowStartedMs()
|
|
200
260
|
: Date.now() - 1000;
|
|
201
261
|
const windowSeconds = Math.max(0.001, (Date.now() - windowStartedMs) / 1000);
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
: snapshot.totalDurationMs() / 1000
|
|
207
|
-
: 0;
|
|
262
|
+
const windowCpuSeconds = endProcessResourceSample(this.cpuWindowMark).cpuTimeMs / 1000;
|
|
263
|
+
this.cpuWindowMark = beginProcessResourceSample();
|
|
264
|
+
// Trend energy estimate from one process CPU delta, not overlapping requests.
|
|
265
|
+
const busySeconds = snapshot ? windowCpuSeconds : 0;
|
|
208
266
|
const util = Math.min(1, busySeconds / Math.max(windowSeconds, 0.001));
|
|
209
267
|
const windowEnergyKwh = (this.config.estimateTdpWatts * util * windowSeconds) / 1000 / 3600;
|
|
210
268
|
const occupancy = getOccupancyTracker().takeWindowSnapshot();
|
|
@@ -220,6 +278,7 @@ export class NetGreenerRuntime {
|
|
|
220
278
|
windowEnergyKwh,
|
|
221
279
|
windowSeconds,
|
|
222
280
|
windowRamGbHours,
|
|
281
|
+
windowCpuSeconds,
|
|
223
282
|
occupancy,
|
|
224
283
|
})
|
|
225
284
|
: null;
|
|
@@ -230,11 +289,17 @@ export class NetGreenerRuntime {
|
|
|
230
289
|
return null;
|
|
231
290
|
}
|
|
232
291
|
const externalV0 = externalSnapshot ? externalSnapshot.buildV0() : null;
|
|
292
|
+
const mcpLedger = getMcpToolLedger();
|
|
293
|
+
mcpSnapshot = mcpLedger.hasCalls() ? mcpLedger.takeSnapshot() : null;
|
|
294
|
+
const mcpV0 = mcpSnapshot ? mcpSnapshot.buildV0() : null;
|
|
295
|
+
if (mcpSnapshot && !mcpV0) {
|
|
296
|
+
mcpLedger.mergeSnapshot(mcpSnapshot);
|
|
297
|
+
mcpSnapshot = null;
|
|
298
|
+
}
|
|
299
|
+
const latencyV0 = buildMcpLatencyV0(mcpV0, externalV0 ?? null, windowSeconds);
|
|
233
300
|
const end = new Date();
|
|
234
301
|
const start = new Date(end.getTime() - windowSeconds * 1000);
|
|
235
|
-
|
|
236
|
-
const windowId = this.stickyWindowId ?? newRuntimeWindowId();
|
|
237
|
-
this.stickyWindowId = windowId;
|
|
302
|
+
const windowId = newRuntimeWindowId();
|
|
238
303
|
// Prefer effective RuntimeConfig over ambient process.env.
|
|
239
304
|
const tenantConfig = tenantConfigFromRuntime(this.config);
|
|
240
305
|
const runContext = {
|
|
@@ -257,19 +322,16 @@ export class NetGreenerRuntime {
|
|
|
257
322
|
tenantConfig,
|
|
258
323
|
activeContext: getTenantContext(),
|
|
259
324
|
});
|
|
260
|
-
const measuredCpu = snapshot?.hasMeasuredCpu() ?? false;
|
|
261
325
|
const measuredRss = snapshot?.hasMeasuredRss() ?? false;
|
|
262
326
|
const carbonFactor = carbonFactorDict();
|
|
263
327
|
const session_metadata = {
|
|
264
328
|
run_context: runContext,
|
|
265
329
|
...(runtimeV0 ? { service_runtime_v0: runtimeV0 } : {}),
|
|
266
330
|
...(externalV0 ? { external_api_v0: externalV0 } : {}),
|
|
331
|
+
...(mcpV0 ? { mcp_tool_v0: mcpV0 } : {}),
|
|
332
|
+
...(latencyV0 ? { mcp_latency_v0: latencyV0 } : {}),
|
|
267
333
|
measurement_provenance: {
|
|
268
|
-
cpu_source: runtimeV0
|
|
269
|
-
? measuredCpu
|
|
270
|
-
? CPU_SOURCE_PROCESS
|
|
271
|
-
: CPU_SOURCE_DURATION_PROXY
|
|
272
|
-
: 'unavailable',
|
|
334
|
+
cpu_source: runtimeV0 ? CPU_SOURCE_PROCESS : 'unavailable',
|
|
273
335
|
memory_source: measuredRss ? MEMORY_SOURCE_PROCESS : 'unavailable',
|
|
274
336
|
energy_model: runtimeV0 ? 'tdp_utilization_estimate' : 'unavailable',
|
|
275
337
|
gpu_scope: 'none',
|
|
@@ -307,40 +369,34 @@ export class NetGreenerRuntime {
|
|
|
307
369
|
runtime_window_id: windowId,
|
|
308
370
|
session_metadata,
|
|
309
371
|
};
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
noteExportResult(result.ok, result.ok ? undefined : 'error' in result ? result.error : 'export_failed');
|
|
313
|
-
mergeHealthIntoMetadata(session_metadata, buildRuntimeHealthV0());
|
|
314
|
-
if (!result.ok) {
|
|
315
|
-
if (snapshot)
|
|
316
|
-
this.aggregator.mergeSnapshot(snapshot);
|
|
317
|
-
if (externalSnapshot)
|
|
318
|
-
externalAgg.mergeSnapshot(externalSnapshot);
|
|
319
|
-
// Keep stickyWindowId so the next flush retries the same window id.
|
|
320
|
-
}
|
|
321
|
-
else {
|
|
322
|
-
this.stickyWindowId = null;
|
|
323
|
-
}
|
|
324
|
-
this.onFlush?.(result, payload);
|
|
325
|
-
return result;
|
|
372
|
+
this.pendingPayload = structuredClone(payload);
|
|
373
|
+
return await this.exportPendingWindow();
|
|
326
374
|
}
|
|
327
375
|
catch (err) {
|
|
376
|
+
this.cpuWindowMark = previousCpuMark;
|
|
328
377
|
noteExportResult(false, err instanceof Error ? err.message : String(err));
|
|
329
378
|
if (snapshot)
|
|
330
379
|
this.aggregator.mergeSnapshot(snapshot);
|
|
331
380
|
if (externalSnapshot)
|
|
332
381
|
externalAgg.mergeSnapshot(externalSnapshot);
|
|
382
|
+
if (mcpSnapshot)
|
|
383
|
+
getMcpToolLedger().mergeSnapshot(mcpSnapshot);
|
|
333
384
|
const result = {
|
|
334
385
|
ok: false,
|
|
335
386
|
error: err instanceof Error ? err.message : String(err),
|
|
336
387
|
};
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
388
|
+
try {
|
|
389
|
+
this.onFlush?.(result, {
|
|
390
|
+
project_id: this.config.projectId,
|
|
391
|
+
start_time: new Date().toISOString(),
|
|
392
|
+
end_time: new Date().toISOString(),
|
|
393
|
+
runtime_window_id: newRuntimeWindowId(),
|
|
394
|
+
session_metadata: {},
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
catch {
|
|
398
|
+
/* Observer errors must never escape telemetry flush. */
|
|
399
|
+
}
|
|
344
400
|
return result;
|
|
345
401
|
}
|
|
346
402
|
finally {
|
|
@@ -349,7 +405,12 @@ export class NetGreenerRuntime {
|
|
|
349
405
|
}
|
|
350
406
|
async shutdown() {
|
|
351
407
|
this.stop();
|
|
352
|
-
|
|
408
|
+
const hadPending = this.pendingPayload !== null;
|
|
409
|
+
const result = await this.flush('shutdown');
|
|
410
|
+
if (hadPending && result?.ok) {
|
|
411
|
+
return (await this.flush('shutdown')) ?? result;
|
|
412
|
+
}
|
|
413
|
+
return result;
|
|
353
414
|
}
|
|
354
415
|
}
|
|
355
416
|
let globalRuntime = null;
|
package/dist/runtimeHealth.js
CHANGED
|
@@ -83,7 +83,7 @@ export function buildRuntimeHealthV0() {
|
|
|
83
83
|
remediation.push('A flush was skipped while another was in flight — window data is retried on failure merge; reduce flush contention if drops grow.');
|
|
84
84
|
}
|
|
85
85
|
if (state.exportFail > 0) {
|
|
86
|
-
remediation.push('Inspect prior export errors;
|
|
86
|
+
remediation.push('Inspect prior export errors; the exact pending window is retained in memory for retry. Direct mode does not survive process restart.');
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
89
|
else if (state.exportOk > 0 || state.hooksActive) {
|
package/dist/tenantContext.d.ts
CHANGED
|
@@ -5,6 +5,9 @@ export type TenantContext = {
|
|
|
5
5
|
tenantSource: string;
|
|
6
6
|
tenantLabel?: string;
|
|
7
7
|
};
|
|
8
|
+
export declare const MAX_TENANT_BUCKETS = 200;
|
|
9
|
+
export declare const TENANT_OVERFLOW_ID = "netgreener:tenant-overflow";
|
|
10
|
+
export declare function tenantBucketId(tenantId: string, buckets: ReadonlyMap<string, unknown>): string;
|
|
8
11
|
/**
|
|
9
12
|
* Mutable ALS cell so ``setTenantContext`` (manual auth) updates the same
|
|
10
13
|
* object Express holds for finish/close after the request ALS exits.
|
package/dist/tenantContext.js
CHANGED
|
@@ -1,14 +1,21 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
2
|
const TENANT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
3
|
+
export const MAX_TENANT_BUCKETS = 200;
|
|
4
|
+
export const TENANT_OVERFLOW_ID = 'netgreener:tenant-overflow';
|
|
5
|
+
export function tenantBucketId(tenantId, buckets) {
|
|
6
|
+
return buckets.has(tenantId) || buckets.size < MAX_TENANT_BUCKETS - 1
|
|
7
|
+
? tenantId : TENANT_OVERFLOW_ID;
|
|
8
|
+
}
|
|
3
9
|
const storage = new AsyncLocalStorage();
|
|
4
10
|
export function normalizeTenantId(value) {
|
|
5
11
|
if (value === null || value === undefined)
|
|
6
12
|
return null;
|
|
7
13
|
const cleaned = String(value).trim();
|
|
8
|
-
if (!cleaned || cleaned.includes('@'))
|
|
14
|
+
if (!cleaned || cleaned.includes('@') || cleaned === TENANT_OVERFLOW_ID)
|
|
15
|
+
return null;
|
|
16
|
+
if (cleaned.length > 128)
|
|
9
17
|
return null;
|
|
10
|
-
|
|
11
|
-
return TENANT_ID_RE.test(clipped) ? clipped : null;
|
|
18
|
+
return TENANT_ID_RE.test(cleaned) ? cleaned : null;
|
|
12
19
|
}
|
|
13
20
|
function tenantConfigFromSource(fields) {
|
|
14
21
|
const source = (fields.source || 'none').trim().toLowerCase();
|
|
@@ -166,7 +173,19 @@ export function resolveTenantFromTaskData(data, config) {
|
|
|
166
173
|
return { tenantId, tenantSource: `task_kwarg:${key}` };
|
|
167
174
|
}
|
|
168
175
|
export function runWithTenantContext(ctx, fn) {
|
|
169
|
-
return storage.run({ current: ctx }, fn);
|
|
176
|
+
return storage.run({ current: normalizeTenantContext(ctx) }, fn);
|
|
177
|
+
}
|
|
178
|
+
function normalizeTenantContext(ctx) {
|
|
179
|
+
if (!ctx)
|
|
180
|
+
return null;
|
|
181
|
+
const tenantId = normalizeTenantId(ctx.tenantId);
|
|
182
|
+
if (!tenantId)
|
|
183
|
+
return null;
|
|
184
|
+
return {
|
|
185
|
+
tenantId,
|
|
186
|
+
tenantSource: String(ctx.tenantSource || 'manual').slice(0, 128),
|
|
187
|
+
...(ctx.tenantLabel ? { tenantLabel: String(ctx.tenantLabel).trim().slice(0, 128) } : {}),
|
|
188
|
+
};
|
|
170
189
|
}
|
|
171
190
|
/**
|
|
172
191
|
* Enter a mutable tenant cell for the remainder of this async chain (Fastify
|
|
@@ -174,7 +193,7 @@ export function runWithTenantContext(ctx, fn) {
|
|
|
174
193
|
* handler runs inside one callback (Express ``next``).
|
|
175
194
|
*/
|
|
176
195
|
export function enterTenantStore(ctx) {
|
|
177
|
-
const store = { current: ctx };
|
|
196
|
+
const store = { current: normalizeTenantContext(ctx) };
|
|
178
197
|
storage.enterWith(store);
|
|
179
198
|
return store;
|
|
180
199
|
}
|
|
@@ -191,12 +210,15 @@ export function getTenantContext() {
|
|
|
191
210
|
* after the middleware ALS callback returns.
|
|
192
211
|
*/
|
|
193
212
|
export function setTenantContext(ctx) {
|
|
213
|
+
const normalized = normalizeTenantContext(ctx);
|
|
214
|
+
if (!normalized)
|
|
215
|
+
throw new Error('invalid tenant_id');
|
|
194
216
|
const store = storage.getStore();
|
|
195
217
|
if (store) {
|
|
196
|
-
store.current =
|
|
218
|
+
store.current = normalized;
|
|
197
219
|
return;
|
|
198
220
|
}
|
|
199
|
-
storage.enterWith({ current:
|
|
221
|
+
storage.enterWith({ current: normalized });
|
|
200
222
|
}
|
|
201
223
|
export function collectWindowTenantIds(runtimeV0, externalV0) {
|
|
202
224
|
const ids = new Set();
|
|
@@ -212,14 +234,18 @@ export function collectWindowTenantIds(runtimeV0, externalV0) {
|
|
|
212
234
|
}
|
|
213
235
|
export function attachWindowTenantToRunContext(runContext, opts) {
|
|
214
236
|
const tenantIds = collectWindowTenantIds(opts.runtimeV0, opts.externalV0);
|
|
237
|
+
if (tenantIds.has(TENANT_OVERFLOW_ID))
|
|
238
|
+
return runContext;
|
|
215
239
|
if (tenantIds.size !== 1)
|
|
216
240
|
return runContext;
|
|
217
241
|
const tenantId = [...tenantIds][0];
|
|
218
242
|
runContext.tenant_id = tenantId;
|
|
219
|
-
const
|
|
243
|
+
const activeMatches = opts.activeContext?.tenantId === tenantId;
|
|
244
|
+
const source = (activeMatches ? opts.activeContext?.tenantSource : null)
|
|
245
|
+
|| configuredTenantSourceLabel(opts.tenantConfig);
|
|
220
246
|
if (source)
|
|
221
247
|
runContext.tenant_source = source;
|
|
222
|
-
const label = opts.activeContext?.tenantLabel;
|
|
248
|
+
const label = activeMatches ? opts.activeContext?.tenantLabel : undefined;
|
|
223
249
|
if (label)
|
|
224
250
|
runContext.tenant_label = label;
|
|
225
251
|
return runContext;
|
package/dist/types.d.ts
CHANGED
|
@@ -78,6 +78,8 @@ export type ExternalApiModelBucket = {
|
|
|
78
78
|
calls: number;
|
|
79
79
|
errors: number;
|
|
80
80
|
calls_with_usage?: number;
|
|
81
|
+
/** Calls seen with no provider usage. Not a per-call price. */
|
|
82
|
+
calls_unknown?: number;
|
|
81
83
|
input_tokens?: number;
|
|
82
84
|
output_tokens?: number;
|
|
83
85
|
total_tokens?: number;
|
|
@@ -87,6 +89,8 @@ export type ExternalApiProvider = {
|
|
|
87
89
|
calls: number;
|
|
88
90
|
errors: number;
|
|
89
91
|
calls_with_usage?: number;
|
|
92
|
+
/** Calls seen with no provider usage. Not a per-call price. */
|
|
93
|
+
calls_unknown?: number;
|
|
90
94
|
duration_ms_avg?: number;
|
|
91
95
|
hosts?: string[];
|
|
92
96
|
input_tokens?: number;
|
|
@@ -161,6 +165,10 @@ export type RuntimeSessionMetadata = {
|
|
|
161
165
|
run_context?: RunContext;
|
|
162
166
|
service_runtime_v0?: ServiceRuntimeV0;
|
|
163
167
|
external_api_v0?: ExternalApiV0;
|
|
168
|
+
/** Same-process MCP tool series. Not an API cost and not a second bill. */
|
|
169
|
+
mcp_tool_v0?: Record<string, unknown>;
|
|
170
|
+
/** Wall time beside MCP and HTTP durations. Overlap is marked, not stacked. */
|
|
171
|
+
mcp_latency_v0?: Record<string, unknown>;
|
|
164
172
|
measurement_provenance?: MeasurementProvenance;
|
|
165
173
|
[key: string]: unknown;
|
|
166
174
|
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Azure Functions gate (isolated)
|
|
2
|
+
|
|
3
|
+
Isolated serverless-thin dogfood for `CHK-R6.serverless-degraded`.
|
|
4
|
+
|
|
5
|
+
**Does not** touch existing NetGreener prod resources. Create under
|
|
6
|
+
`rg-ng-runtime-gate-test` only. Env secrets live in
|
|
7
|
+
`../../.env.azure-test-servers` (gitignored).
|
|
8
|
+
|
|
9
|
+
## Deployed app (example)
|
|
10
|
+
|
|
11
|
+
- Function App: `fn-ng-runtime-gate-20261014`
|
|
12
|
+
- URL: `https://fn-ng-runtime-gate-20261014.azurewebsites.net/api/health`
|
|
13
|
+
|
|
14
|
+
## Local publish
|
|
15
|
+
|
|
16
|
+
```powershell
|
|
17
|
+
npm install
|
|
18
|
+
func azure functionapp publish fn-ng-runtime-gate-20261014 --javascript
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Tear down
|
|
22
|
+
|
|
23
|
+
```powershell
|
|
24
|
+
az group delete -n rg-ng-runtime-gate-test --yes
|
|
25
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": "2.0",
|
|
3
|
+
"logging": {
|
|
4
|
+
"applicationInsights": {
|
|
5
|
+
"samplingSettings": {
|
|
6
|
+
"isEnabled": true,
|
|
7
|
+
"excludedTypes": "Request"
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
},
|
|
11
|
+
"extensionBundle": {
|
|
12
|
+
"id": "Microsoft.Azure.Functions.ExtensionBundle",
|
|
13
|
+
"version": "[4.*, 5.0.0)"
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "ng-azure-functions-gate",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"lockfileVersion": 3,
|
|
5
|
+
"requires": true,
|
|
6
|
+
"packages": {
|
|
7
|
+
"": {
|
|
8
|
+
"name": "ng-azure-functions-gate",
|
|
9
|
+
"version": "0.1.0",
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"@azure/functions": "^4.6.0",
|
|
12
|
+
"@netgreener/runtime": "0.1.9"
|
|
13
|
+
},
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": "^22.0.0 || ^24.0.0"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"node_modules/@azure/functions": {
|
|
19
|
+
"version": "4.16.5",
|
|
20
|
+
"resolved": "https://registry.npmjs.org/@azure/functions/-/functions-4.16.5.tgz",
|
|
21
|
+
"integrity": "sha512-h0lVUeI/Q36SyE2xGQOXZqBbmSgQHNLk8pvMxhq3Dw1TaT3eGWs2X25dceGJ153aXXkjcTEdkxg3D2Gcz1uJ0w==",
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@azure/functions-extensions-base": "0.3.0",
|
|
25
|
+
"cookie": "^0.7.0"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=20.0"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"node_modules/@azure/functions-extensions-base": {
|
|
32
|
+
"version": "0.3.0",
|
|
33
|
+
"resolved": "https://registry.npmjs.org/@azure/functions-extensions-base/-/functions-extensions-base-0.3.0.tgz",
|
|
34
|
+
"integrity": "sha512-Cux0hLu5ZXlC/Kb+yvJVhRLIdkfFwui2HeT5oGZL00r/GCUUkhGTzRfZUjRN4Bq729mPv3okPucz2z7SMQLStA==",
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=18.0"
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"node_modules/@netgreener/runtime": {
|
|
41
|
+
"version": "0.1.9",
|
|
42
|
+
"resolved": "https://registry.npmjs.org/@netgreener/runtime/-/runtime-0.1.9.tgz",
|
|
43
|
+
"integrity": "sha512-dp4vwl968K58zk6eTCurJjLFQMaFg2jZrtOoEI5AREuZbl1v9Tkgbvm80A4GAWgIWA7la2TJS6MlUFKt7w3G7Q==",
|
|
44
|
+
"license": "UNLICENSED",
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"ajv": "^8.20.0",
|
|
47
|
+
"ajv-formats": "^3.0.1"
|
|
48
|
+
},
|
|
49
|
+
"bin": {
|
|
50
|
+
"netgreener": "dist/cli/netgreener.js",
|
|
51
|
+
"netgreener-analyze": "dist/analyze/cli.js"
|
|
52
|
+
},
|
|
53
|
+
"engines": {
|
|
54
|
+
"node": "^22.0.0 || ^24.0.0"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"axios": ">=1",
|
|
58
|
+
"bullmq": ">=4",
|
|
59
|
+
"express": ">=4",
|
|
60
|
+
"fastify": ">=4",
|
|
61
|
+
"typescript": ">=5"
|
|
62
|
+
},
|
|
63
|
+
"peerDependenciesMeta": {
|
|
64
|
+
"axios": {
|
|
65
|
+
"optional": true
|
|
66
|
+
},
|
|
67
|
+
"bullmq": {
|
|
68
|
+
"optional": true
|
|
69
|
+
},
|
|
70
|
+
"express": {
|
|
71
|
+
"optional": true
|
|
72
|
+
},
|
|
73
|
+
"fastify": {
|
|
74
|
+
"optional": true
|
|
75
|
+
},
|
|
76
|
+
"typescript": {
|
|
77
|
+
"optional": true
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
"node_modules/ajv": {
|
|
82
|
+
"version": "8.20.0",
|
|
83
|
+
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
|
|
84
|
+
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
|
|
85
|
+
"license": "MIT",
|
|
86
|
+
"dependencies": {
|
|
87
|
+
"fast-deep-equal": "^3.1.3",
|
|
88
|
+
"fast-uri": "^3.0.1",
|
|
89
|
+
"json-schema-traverse": "^1.0.0",
|
|
90
|
+
"require-from-string": "^2.0.2"
|
|
91
|
+
},
|
|
92
|
+
"funding": {
|
|
93
|
+
"type": "github",
|
|
94
|
+
"url": "https://github.com/sponsors/epoberezkin"
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
"node_modules/ajv-formats": {
|
|
98
|
+
"version": "3.0.1",
|
|
99
|
+
"resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
|
|
100
|
+
"integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
|
|
101
|
+
"license": "MIT",
|
|
102
|
+
"dependencies": {
|
|
103
|
+
"ajv": "^8.0.0"
|
|
104
|
+
},
|
|
105
|
+
"peerDependencies": {
|
|
106
|
+
"ajv": "^8.0.0"
|
|
107
|
+
},
|
|
108
|
+
"peerDependenciesMeta": {
|
|
109
|
+
"ajv": {
|
|
110
|
+
"optional": true
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
"node_modules/cookie": {
|
|
115
|
+
"version": "0.7.2",
|
|
116
|
+
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
|
|
117
|
+
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
|
|
118
|
+
"license": "MIT",
|
|
119
|
+
"engines": {
|
|
120
|
+
"node": ">= 0.6"
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
"node_modules/fast-deep-equal": {
|
|
124
|
+
"version": "3.1.3",
|
|
125
|
+
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
|
126
|
+
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
|
127
|
+
"license": "MIT"
|
|
128
|
+
},
|
|
129
|
+
"node_modules/fast-uri": {
|
|
130
|
+
"version": "3.1.8",
|
|
131
|
+
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
|
|
132
|
+
"integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
|
|
133
|
+
"funding": [
|
|
134
|
+
{
|
|
135
|
+
"type": "github",
|
|
136
|
+
"url": "https://github.com/sponsors/fastify"
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
"type": "opencollective",
|
|
140
|
+
"url": "https://opencollective.com/fastify"
|
|
141
|
+
}
|
|
142
|
+
],
|
|
143
|
+
"license": "BSD-3-Clause"
|
|
144
|
+
},
|
|
145
|
+
"node_modules/json-schema-traverse": {
|
|
146
|
+
"version": "1.0.0",
|
|
147
|
+
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
|
|
148
|
+
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
|
|
149
|
+
"license": "MIT"
|
|
150
|
+
},
|
|
151
|
+
"node_modules/require-from-string": {
|
|
152
|
+
"version": "2.0.2",
|
|
153
|
+
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
|
|
154
|
+
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
|
|
155
|
+
"license": "MIT",
|
|
156
|
+
"engines": {
|
|
157
|
+
"node": ">=0.10.0"
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "ng-azure-functions-gate",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/functions/*.js",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": "^22.0.0 || ^24.0.0"
|
|
9
|
+
},
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"@azure/functions": "^4.6.0",
|
|
12
|
+
"@netgreener/runtime": "0.1.9"
|
|
13
|
+
}
|
|
14
|
+
}
|