@bleedingdev/modern-js-server-core 3.2.0-ultramodern.120 → 3.2.0-ultramodern.121

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.
Files changed (60) hide show
  1. package/dist/cjs/adapters/node/plugins/resource.js +1 -6
  2. package/dist/cjs/adapters/node/plugins/static.js +11 -185
  3. package/dist/cjs/adapters/node/plugins/staticModuleFederation.js +165 -0
  4. package/dist/cjs/adapters/node/plugins/staticPrecompressed.js +135 -0
  5. package/dist/cjs/index.js +34 -10
  6. package/dist/cjs/plugins/default.js +0 -2
  7. package/dist/cjs/plugins/index.js +2 -83
  8. package/dist/cjs/types/config/bffRuntime.js +18 -0
  9. package/dist/cjs/types/config/serverTelemetry.js +18 -0
  10. package/dist/cjs/utils/error.js +62 -0
  11. package/dist/esm/adapters/node/plugins/resource.mjs +1 -6
  12. package/dist/esm/adapters/node/plugins/static.mjs +7 -181
  13. package/dist/esm/adapters/node/plugins/staticModuleFederation.mjs +96 -0
  14. package/dist/esm/adapters/node/plugins/staticPrecompressed.mjs +91 -0
  15. package/dist/esm/index.mjs +1 -1
  16. package/dist/esm/plugins/default.mjs +0 -2
  17. package/dist/esm/plugins/index.mjs +0 -3
  18. package/dist/esm/types/config/bffRuntime.mjs +0 -0
  19. package/dist/esm/types/config/serverTelemetry.mjs +0 -0
  20. package/dist/esm/utils/error.mjs +54 -1
  21. package/dist/esm-node/adapters/node/plugins/resource.mjs +1 -6
  22. package/dist/esm-node/adapters/node/plugins/static.mjs +7 -181
  23. package/dist/esm-node/adapters/node/plugins/staticModuleFederation.mjs +97 -0
  24. package/dist/esm-node/adapters/node/plugins/staticPrecompressed.mjs +92 -0
  25. package/dist/esm-node/index.mjs +1 -1
  26. package/dist/esm-node/plugins/default.mjs +0 -2
  27. package/dist/esm-node/plugins/index.mjs +0 -3
  28. package/dist/esm-node/types/config/bffRuntime.mjs +1 -0
  29. package/dist/esm-node/types/config/serverTelemetry.mjs +1 -0
  30. package/dist/esm-node/utils/error.mjs +54 -1
  31. package/dist/types/adapters/node/plugins/staticModuleFederation.d.ts +13 -0
  32. package/dist/types/adapters/node/plugins/staticPrecompressed.d.ts +13 -0
  33. package/dist/types/index.d.ts +2 -1
  34. package/dist/types/plugins/index.d.ts +0 -3
  35. package/dist/types/types/config/bff.d.ts +2 -97
  36. package/dist/types/types/config/bffRuntime.d.ts +105 -0
  37. package/dist/types/types/config/server.d.ts +3 -337
  38. package/dist/types/types/config/serverTelemetry.d.ts +319 -0
  39. package/dist/types/utils/error.d.ts +16 -0
  40. package/package.json +5 -5
  41. package/dist/cjs/adapters/node/plugins/moduleFederationCss.js +0 -176
  42. package/dist/cjs/plugins/contractGateAutopilot.js +0 -162
  43. package/dist/cjs/plugins/contractGateSnapshotStore.js +0 -243
  44. package/dist/cjs/plugins/mfCache.js +0 -82
  45. package/dist/cjs/plugins/telemetry.js +0 -1287
  46. package/dist/esm/adapters/node/plugins/moduleFederationCss.mjs +0 -125
  47. package/dist/esm/plugins/contractGateAutopilot.mjs +0 -124
  48. package/dist/esm/plugins/contractGateSnapshotStore.mjs +0 -180
  49. package/dist/esm/plugins/mfCache.mjs +0 -35
  50. package/dist/esm/plugins/telemetry.mjs +0 -1195
  51. package/dist/esm-node/adapters/node/plugins/moduleFederationCss.mjs +0 -126
  52. package/dist/esm-node/plugins/contractGateAutopilot.mjs +0 -125
  53. package/dist/esm-node/plugins/contractGateSnapshotStore.mjs +0 -182
  54. package/dist/esm-node/plugins/mfCache.mjs +0 -36
  55. package/dist/esm-node/plugins/telemetry.mjs +0 -1196
  56. package/dist/types/adapters/node/plugins/moduleFederationCss.d.ts +0 -33
  57. package/dist/types/plugins/contractGateAutopilot.d.ts +0 -35
  58. package/dist/types/plugins/contractGateSnapshotStore.d.ts +0 -57
  59. package/dist/types/plugins/mfCache.d.ts +0 -12
  60. package/dist/types/plugins/telemetry.d.ts +0 -309
@@ -1,1287 +0,0 @@
1
- "use strict";
2
- var __webpack_require__ = {};
3
- (()=>{
4
- __webpack_require__.d = (exports1, getters, values)=>{
5
- var define = (defs, kind)=>{
6
- for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
- enumerable: true,
8
- [kind]: defs[key]
9
- });
10
- };
11
- define(getters, "get");
12
- define(values, "value");
13
- };
14
- })();
15
- (()=>{
16
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
- })();
18
- (()=>{
19
- __webpack_require__.r = (exports1)=>{
20
- if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
- value: 'Module'
22
- });
23
- Object.defineProperty(exports1, '__esModule', {
24
- value: true
25
- });
26
- };
27
- })();
28
- var __webpack_exports__ = {};
29
- __webpack_require__.r(__webpack_exports__);
30
- __webpack_require__.d(__webpack_exports__, {
31
- DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT: ()=>DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT,
32
- DEFAULT_RUNTIME_STATUS_ENDPOINT: ()=>DEFAULT_RUNTIME_STATUS_ENDPOINT,
33
- TelemetryCanaryOrchestrator: ()=>TelemetryCanaryOrchestrator,
34
- TelemetryRegistry: ()=>TelemetryRegistry,
35
- TelemetryStartupHealthError: ()=>TelemetryStartupHealthError,
36
- createOtlpTelemetryExporter: ()=>createOtlpTelemetryExporter,
37
- createRuntimeFallbackSignalRuntimeState: ()=>createRuntimeFallbackSignalRuntimeState,
38
- createRuntimeSignalError: ()=>createRuntimeSignalError,
39
- createTelemetryAwareMetrics: ()=>createTelemetryAwareMetrics,
40
- createVictoriaMetricsTelemetryExporter: ()=>createVictoriaMetricsTelemetryExporter,
41
- enforceRuntimeFallbackSignalAuthToken: ()=>enforceRuntimeFallbackSignalAuthToken,
42
- enforceRuntimeFallbackSignalTrustPolicy: ()=>enforceRuntimeFallbackSignalTrustPolicy,
43
- getRuntimeSignalErrorStatusCode: ()=>getRuntimeSignalErrorStatusCode,
44
- hasEnabledTelemetryExporters: ()=>hasEnabledTelemetryExporters,
45
- injectTelemetryPlugin: ()=>injectTelemetryPlugin,
46
- normalizeRuntimeFallbackSignalAuthConfig: ()=>normalizeRuntimeFallbackSignalAuthConfig,
47
- normalizeRuntimeFallbackTrustPolicy: ()=>normalizeRuntimeFallbackTrustPolicy,
48
- parseRuntimeFallbackSignalPayloadFromRawBody: ()=>parseRuntimeFallbackSignalPayloadFromRawBody,
49
- resolveRuntimeFallbackSignalEndpoint: ()=>resolveRuntimeFallbackSignalEndpoint
50
- });
51
- const external_contractGateAutopilot_js_namespaceObject = require("./contractGateAutopilot.js");
52
- const external_contractGateSnapshotStore_js_namespaceObject = require("./contractGateSnapshotStore.js");
53
- class TelemetryStartupHealthError extends Error {
54
- constructor(failedExporters){
55
- super(`Telemetry startup health check failed for exporters: ${failedExporters.map((item)=>item.name).join(', ')}`), this.code = 'TELEMETRY_EXPORTER_STARTUP_HEALTH_FAILED';
56
- this.name = 'TelemetryStartupHealthError';
57
- this.failedExporters = failedExporters;
58
- }
59
- }
60
- const TRACEPARENT_REGEX = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i;
61
- const DEFAULT_OTLP_ENDPOINT = 'http://127.0.0.1:4318/v1/logs';
62
- const DEFAULT_VM_ENDPOINT = 'http://127.0.0.1:8428/api/v1/import/prometheus';
63
- const DEFAULT_TIMEOUT_MS = 5000;
64
- const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
65
- const DEFAULT_RUNTIME_STATUS_ENDPOINT = '/_modern/runtime/status';
66
- const DEFAULT_RUNTIME_FALLBACK_GATE_NAME = 'runtime-mf-fallback-health';
67
- const DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS = 300000;
68
- const DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES = 16384;
69
- const DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER = 'x-modernjs-runtime-signal-token';
70
- const DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW = 30;
71
- const DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS = 60000;
72
- const DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS = 10000;
73
- function clamp(value, min, max) {
74
- return Math.max(min, Math.min(max, value));
75
- }
76
- function isRecord(value) {
77
- return 'object' == typeof value && null !== value && !Array.isArray(value);
78
- }
79
- function redactObject(value, redactionKeys) {
80
- if (!isRecord(value)) return;
81
- const output = {};
82
- for (const [key, nested] of Object.entries(value)){
83
- if (redactionKeys.has(key)) {
84
- output[key] = '[REDACTED]';
85
- continue;
86
- }
87
- if (Array.isArray(nested)) {
88
- output[key] = nested.map((item)=>{
89
- if (isRecord(item)) return redactObject(item, redactionKeys);
90
- return item;
91
- });
92
- continue;
93
- }
94
- if (isRecord(nested)) {
95
- output[key] = redactObject(nested, redactionKeys);
96
- continue;
97
- }
98
- output[key] = nested;
99
- }
100
- return output;
101
- }
102
- function normalizeLabels(labels) {
103
- if (!labels) return;
104
- const normalized = {};
105
- for (const [key, value] of Object.entries(labels))if (null != value) normalized[key] = String(value);
106
- return Object.keys(normalized).length > 0 ? normalized : void 0;
107
- }
108
- function parseTraceparent(header) {
109
- if (!header) return;
110
- const match = header.trim().match(TRACEPARENT_REGEX);
111
- if (!match) return;
112
- const traceId = match[1]?.toLowerCase();
113
- const spanId = match[2]?.toLowerCase();
114
- if (!traceId || !spanId) return;
115
- return {
116
- traceId,
117
- spanId
118
- };
119
- }
120
- function extractError(args) {
121
- for (const arg of args)if (arg instanceof Error) return {
122
- name: arg.name,
123
- message: arg.message,
124
- stack: arg.stack
125
- };
126
- }
127
- function toTelemetryEnvelope(event, input) {
128
- const base = {
129
- timestamp: Date.now(),
130
- service: input.service,
131
- module: input.module,
132
- environment: input.environment,
133
- ...input.traceId ? {
134
- traceId: input.traceId
135
- } : {},
136
- ...input.spanId ? {
137
- spanId: input.spanId
138
- } : {},
139
- ...input.attributes ? {
140
- attributes: input.attributes
141
- } : {}
142
- };
143
- if ('log' === event.type) {
144
- const payload = event.payload;
145
- const args = payload.args || [];
146
- const signalType = 'trace' === payload.level ? 'trace' : 'log';
147
- return {
148
- ...base,
149
- signalType,
150
- name: payload.message,
151
- level: payload.level,
152
- attributes: {
153
- ...base.attributes || {},
154
- args
155
- },
156
- error: extractError(args)
157
- };
158
- }
159
- if ('timing' === event.type) return {
160
- ...base,
161
- signalType: 'metric',
162
- name: event.payload.name,
163
- value: event.payload.dur,
164
- unit: 'ms',
165
- tags: normalizeLabels(event.payload.tags),
166
- attributes: {
167
- ...base.attributes || {},
168
- desc: event.payload.desc,
169
- args: event.payload.args
170
- }
171
- };
172
- return {
173
- ...base,
174
- signalType: 'metric',
175
- name: event.payload.name,
176
- value: 1,
177
- unit: 'count',
178
- tags: normalizeLabels(event.payload.tags),
179
- attributes: {
180
- ...base.attributes || {},
181
- args: event.payload.args
182
- }
183
- };
184
- }
185
- async function postWithTimeout(options) {
186
- const controller = new AbortController();
187
- const timer = setTimeout(()=>controller.abort(), options.timeoutMs);
188
- if ('function' == typeof timer.unref) timer.unref();
189
- try {
190
- const response = await fetch(options.endpoint, {
191
- method: 'POST',
192
- body: options.body,
193
- headers: options.headers,
194
- signal: controller.signal
195
- });
196
- if (!response.ok) throw new Error(`Telemetry exporter request failed: ${response.status} ${response.statusText}`);
197
- } finally{
198
- clearTimeout(timer);
199
- }
200
- }
201
- function sanitizeMetricName(value) {
202
- return value.replace(/[^a-zA-Z0-9_:]/g, '_').replace(/_+/g, '_');
203
- }
204
- function escapeLabelValue(value) {
205
- return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
206
- }
207
- function toPrometheusLine(envelope, metricPrefix) {
208
- const metricName = sanitizeMetricName(`${metricPrefix}_${envelope.signalType}_${envelope.name}`);
209
- const labels = {
210
- service: envelope.service,
211
- module: envelope.module,
212
- environment: envelope.environment,
213
- ...envelope.level ? {
214
- level: envelope.level
215
- } : {},
216
- ...envelope.traceId ? {
217
- trace_id: envelope.traceId
218
- } : {},
219
- ...envelope.spanId ? {
220
- span_id: envelope.spanId
221
- } : {},
222
- ...envelope.tags || {}
223
- };
224
- const labelPairs = Object.entries(labels).sort(([a], [b])=>a.localeCompare(b)).map(([key, value])=>`${sanitizeMetricName(key)}="${escapeLabelValue(value)}"`);
225
- const labelText = labelPairs.length > 0 ? `{${labelPairs.join(',')}}` : '';
226
- const value = 'number' == typeof envelope.value && Number.isFinite(envelope.value) ? envelope.value : 1;
227
- const timestampMs = envelope.timestamp;
228
- return `${metricName}${labelText} ${value} ${timestampMs}`;
229
- }
230
- function createOtlpTelemetryExporter(options = {}) {
231
- const endpoint = options.endpoint || DEFAULT_OTLP_ENDPOINT;
232
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
233
- const headers = {
234
- 'content-type': 'application/json',
235
- ...options.headers || {}
236
- };
237
- return {
238
- name: 'otlp',
239
- async emit (batch) {
240
- if (0 === batch.length) return;
241
- const body = JSON.stringify({
242
- resource: {
243
- service: batch[0]?.service,
244
- module: batch[0]?.module,
245
- environment: batch[0]?.environment
246
- },
247
- emittedAt: Date.now(),
248
- events: batch
249
- });
250
- await postWithTimeout({
251
- endpoint,
252
- body,
253
- headers,
254
- timeoutMs
255
- });
256
- }
257
- };
258
- }
259
- function createVictoriaMetricsTelemetryExporter(options = {}) {
260
- const endpoint = options.endpoint || DEFAULT_VM_ENDPOINT;
261
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
262
- const metricPrefix = sanitizeMetricName(options.metricPrefix || 'modernjs');
263
- const headers = {
264
- 'content-type': 'text/plain; version=0.0.4',
265
- ...options.headers || {}
266
- };
267
- return {
268
- name: 'victoria-metrics',
269
- async emit (batch) {
270
- if (0 === batch.length) return;
271
- const lines = batch.map((item)=>toPrometheusLine(item, metricPrefix));
272
- await postWithTimeout({
273
- endpoint,
274
- body: `${lines.join('\n')}\n`,
275
- headers,
276
- timeoutMs
277
- });
278
- }
279
- };
280
- }
281
- class TelemetryRegistry {
282
- async register(exporter) {
283
- this.exporters.push(exporter);
284
- this.exporterHealth.set(exporter.name, {
285
- name: exporter.name,
286
- healthy: true,
287
- failures: 0
288
- });
289
- if (exporter.init) try {
290
- await exporter.init({
291
- service: this.service,
292
- module: this.module,
293
- environment: this.environment
294
- });
295
- this.markExporterHealthy(exporter.name);
296
- } catch (error) {
297
- this.markExporterFailure(exporter.name, error);
298
- throw error;
299
- }
300
- else this.markExporterHealthy(exporter.name);
301
- }
302
- getOrCreateExporterHealth(name) {
303
- const existing = this.exporterHealth.get(name);
304
- if (existing) return existing;
305
- const next = {
306
- name,
307
- healthy: true,
308
- failures: 0
309
- };
310
- this.exporterHealth.set(name, next);
311
- return next;
312
- }
313
- markExporterHealthy(name) {
314
- const status = this.getOrCreateExporterHealth(name);
315
- status.healthy = true;
316
- status.lastSuccessAt = Date.now();
317
- status.lastError = void 0;
318
- }
319
- markExporterFailure(name, error) {
320
- const status = this.getOrCreateExporterHealth(name);
321
- status.healthy = false;
322
- status.failures += 1;
323
- status.lastFailureAt = Date.now();
324
- status.lastError = error instanceof Error ? error.message : String(error);
325
- }
326
- maybeEmitSloAlert(type, value, threshold) {
327
- if (!this.onSloAlert || value < threshold) return;
328
- const now = Date.now();
329
- const lastTimestamp = this.lastSloAlertAt.get(type) ?? 0;
330
- if (now - lastTimestamp < this.alertCooldownMs) return;
331
- this.lastSloAlertAt.set(type, now);
332
- const queueDepth = this.queue.length;
333
- try {
334
- this.onSloAlert({
335
- timestamp: now,
336
- service: this.service,
337
- module: this.module,
338
- environment: this.environment,
339
- type,
340
- value,
341
- threshold,
342
- queueDepth,
343
- queueCapacity: this.maxQueueSize,
344
- queueUtilization: queueDepth / this.maxQueueSize,
345
- totalDropped: this.totalDroppedCount
346
- });
347
- } catch (_error) {}
348
- }
349
- enqueue(envelope) {
350
- if (this.samplingRate < 1 && Math.random() > this.samplingRate) return;
351
- const redactedEnvelope = this.redactionKeys.size > 0 ? {
352
- ...envelope,
353
- attributes: redactObject(envelope.attributes, this.redactionKeys)
354
- } : envelope;
355
- if (this.queue.length >= this.maxQueueSize) {
356
- this.queue.shift();
357
- this.droppedCount += 1;
358
- this.totalDroppedCount += 1;
359
- this.maybeEmitSloAlert('queue.drop', this.totalDroppedCount, this.queueDroppedWarnThreshold);
360
- }
361
- this.queue.push(redactedEnvelope);
362
- this.maybeEmitSloAlert('queue.utilization', this.queue.length / this.maxQueueSize, this.queueUtilizationWarnThreshold);
363
- if (this.queue.length >= this.maxBatchSize) this.flush();
364
- }
365
- enqueueMetric(input) {
366
- this.enqueue({
367
- timestamp: Date.now(),
368
- service: this.service,
369
- module: this.module,
370
- environment: this.environment,
371
- signalType: 'metric',
372
- name: input.name,
373
- value: input.value,
374
- unit: input.unit || 'count',
375
- traceId: input.traceId,
376
- spanId: input.spanId,
377
- parentSpanId: input.parentSpanId,
378
- tags: input.tags,
379
- attributes: input.attributes
380
- });
381
- }
382
- enqueueLog(input) {
383
- this.enqueue({
384
- timestamp: Date.now(),
385
- service: this.service,
386
- module: this.module,
387
- environment: this.environment,
388
- signalType: 'log',
389
- name: input.name,
390
- level: input.level,
391
- traceId: input.traceId,
392
- spanId: input.spanId,
393
- parentSpanId: input.parentSpanId,
394
- tags: input.tags,
395
- attributes: input.attributes,
396
- error: input.error
397
- });
398
- }
399
- enqueueTrace(input) {
400
- this.enqueue({
401
- timestamp: Date.now(),
402
- service: this.service,
403
- module: this.module,
404
- environment: this.environment,
405
- signalType: 'trace',
406
- name: input.name,
407
- traceId: input.traceId,
408
- spanId: input.spanId,
409
- parentSpanId: input.parentSpanId,
410
- tags: input.tags,
411
- attributes: input.attributes
412
- });
413
- }
414
- buildDroppedEnvelope(droppedCount) {
415
- return {
416
- timestamp: Date.now(),
417
- service: this.service,
418
- module: this.module,
419
- environment: this.environment,
420
- signalType: 'metric',
421
- name: 'telemetry.queue.dropped',
422
- value: droppedCount,
423
- unit: 'count',
424
- tags: {
425
- reason: 'queue_backpressure'
426
- }
427
- };
428
- }
429
- buildQueueDepthEnvelope(queueDepth) {
430
- return {
431
- timestamp: Date.now(),
432
- service: this.service,
433
- module: this.module,
434
- environment: this.environment,
435
- signalType: 'metric',
436
- name: 'telemetry.queue.depth',
437
- value: queueDepth,
438
- unit: 'count',
439
- tags: {
440
- capacity: String(this.maxQueueSize)
441
- }
442
- };
443
- }
444
- buildQueueUtilizationEnvelope(queueDepth) {
445
- return {
446
- timestamp: Date.now(),
447
- service: this.service,
448
- module: this.module,
449
- environment: this.environment,
450
- signalType: 'metric',
451
- name: 'telemetry.queue.utilization',
452
- value: queueDepth / this.maxQueueSize,
453
- unit: 'ratio',
454
- tags: {
455
- capacity: String(this.maxQueueSize)
456
- }
457
- };
458
- }
459
- async emitBatch(batch) {
460
- const results = await Promise.allSettled(this.exporters.map(async (exporter)=>{
461
- await exporter.emit(batch);
462
- return exporter.name;
463
- }));
464
- for (const [index, result] of results.entries()){
465
- const exporterName = this.exporters[index]?.name || `exporter-${index}`;
466
- if ('rejected' === result.status) {
467
- this.markExporterFailure(exporterName, result.reason);
468
- continue;
469
- }
470
- this.markExporterHealthy(exporterName);
471
- }
472
- }
473
- buildStartupProbeEnvelope() {
474
- return {
475
- timestamp: Date.now(),
476
- service: this.service,
477
- module: this.module,
478
- environment: this.environment,
479
- signalType: 'log',
480
- name: 'telemetry.exporter.startup_probe',
481
- level: 'info',
482
- tags: {
483
- phase: 'startup'
484
- },
485
- attributes: {
486
- source: 'TelemetryRegistry'
487
- }
488
- };
489
- }
490
- async startupHealthCheck(options) {
491
- if (0 === this.exporters.length) return;
492
- const probeBatch = [
493
- this.buildStartupProbeEnvelope()
494
- ];
495
- const failedExporters = [];
496
- await Promise.all(this.exporters.map(async (exporter)=>{
497
- try {
498
- await exporter.emit(probeBatch);
499
- this.markExporterHealthy(exporter.name);
500
- } catch (error) {
501
- this.markExporterFailure(exporter.name, error);
502
- const status = this.exporterHealth.get(exporter.name);
503
- if (status) failedExporters.push({
504
- ...status
505
- });
506
- }
507
- }));
508
- if ((options?.failLoud ?? true) && failedExporters.length > 0) throw new TelemetryStartupHealthError(failedExporters);
509
- }
510
- getExporterHealth() {
511
- return Array.from(this.exporterHealth.values()).map((item)=>({
512
- ...item
513
- }));
514
- }
515
- getQueueStats() {
516
- return {
517
- depth: this.queue.length,
518
- capacity: this.maxQueueSize,
519
- utilization: this.queue.length / this.maxQueueSize,
520
- pendingDropped: this.droppedCount,
521
- totalDropped: this.totalDroppedCount
522
- };
523
- }
524
- async flushInternal() {
525
- const queueDepthBeforeFlush = this.queue.length;
526
- if (queueDepthBeforeFlush > 0) {
527
- this.queue.unshift(this.buildQueueUtilizationEnvelope(queueDepthBeforeFlush));
528
- this.queue.unshift(this.buildQueueDepthEnvelope(queueDepthBeforeFlush));
529
- }
530
- if (this.droppedCount > 0) {
531
- const droppedCount = this.droppedCount;
532
- this.droppedCount = 0;
533
- this.queue.unshift(this.buildDroppedEnvelope(droppedCount));
534
- }
535
- if (0 === this.queue.length) return;
536
- if (0 === this.exporters.length) {
537
- this.queue.length = 0;
538
- return;
539
- }
540
- while(this.queue.length > 0){
541
- const batch = this.queue.splice(0, this.maxBatchSize);
542
- await this.emitBatch(batch);
543
- }
544
- await Promise.allSettled(this.exporters.map(async (exporter)=>{
545
- if (exporter.flush) await exporter.flush();
546
- }));
547
- }
548
- flush() {
549
- if (this.flushing) return this.flushing;
550
- this.flushing = this.flushInternal().finally(()=>{
551
- this.flushing = null;
552
- });
553
- return this.flushing;
554
- }
555
- async shutdown() {
556
- if (this.flushTimer) clearInterval(this.flushTimer);
557
- await this.flush();
558
- await Promise.allSettled(this.exporters.map(async (exporter)=>{
559
- if (exporter.shutdown) await exporter.shutdown();
560
- }));
561
- }
562
- constructor(options){
563
- this.exporters = [];
564
- this.queue = [];
565
- this.droppedCount = 0;
566
- this.totalDroppedCount = 0;
567
- this.flushing = null;
568
- this.exporterHealth = new Map();
569
- this.lastSloAlertAt = new Map();
570
- this.service = options.service;
571
- this.module = options.module;
572
- this.environment = options.environment;
573
- this.samplingRate = clamp(options.samplingRate ?? 1, 0, 1);
574
- this.maxBatchSize = Math.max(1, options.maxBatchSize ?? 50);
575
- this.maxQueueSize = Math.max(1, options.maxQueueSize ?? 1000);
576
- this.flushIntervalMs = Math.max(50, options.flushIntervalMs ?? 1000);
577
- this.redactionKeys = new Set(options.redactionKeys || []);
578
- this.queueUtilizationWarnThreshold = clamp(options.slo?.queueUtilizationWarnThreshold ?? 0.8, 0, 1);
579
- this.queueDroppedWarnThreshold = Math.max(1, options.slo?.queueDroppedWarnThreshold ?? 1);
580
- this.alertCooldownMs = Math.max(0, options.slo?.alertCooldownMs ?? 60000);
581
- this.onSloAlert = options.slo?.onAlert;
582
- this.flushTimer = setInterval(()=>{
583
- this.flush();
584
- }, this.flushIntervalMs);
585
- if ('function' == typeof this.flushTimer.unref) this.flushTimer.unref();
586
- }
587
- }
588
- class TelemetryCanaryOrchestrator {
589
- setRequiredContractGates(gates) {
590
- this.requiredContractGates = Array.from(new Set(gates.map((item)=>item.trim()).filter(Boolean)));
591
- }
592
- addRequiredContractGate(name) {
593
- const normalizedName = name.trim();
594
- if (!normalizedName) return;
595
- if (!this.requiredContractGates.includes(normalizedName)) this.requiredContractGates.push(normalizedName);
596
- }
597
- setContractGate(name, passed, reason) {
598
- this.contractGates.set(name, {
599
- name,
600
- passed,
601
- reason,
602
- updatedAt: Date.now()
603
- });
604
- }
605
- setContractGates(gates) {
606
- for (const [name, value] of Object.entries(gates)){
607
- if ('boolean' == typeof value) {
608
- this.setContractGate(name, value);
609
- continue;
610
- }
611
- this.setContractGate(name, value.passed, value.reason);
612
- }
613
- }
614
- resetToCanary() {
615
- this.state = 'canary';
616
- this.consecutiveHealthy = 0;
617
- this.consecutiveFailures = 0;
618
- }
619
- collectFailures() {
620
- const failures = [];
621
- const queueStats = this.registry.getQueueStats();
622
- const unhealthyExporterCount = this.registry.getExporterHealth().filter((item)=>!item.healthy).length;
623
- if (queueStats.utilization > this.maxQueueUtilization) failures.push({
624
- reason: 'queue_utilization',
625
- threshold: this.maxQueueUtilization,
626
- value: queueStats.utilization
627
- });
628
- if (queueStats.totalDropped > this.maxTotalDropped) failures.push({
629
- reason: 'queue_dropped',
630
- threshold: this.maxTotalDropped,
631
- value: queueStats.totalDropped
632
- });
633
- if (unhealthyExporterCount > this.maxUnhealthyExporters) failures.push({
634
- reason: 'unhealthy_exporter',
635
- threshold: this.maxUnhealthyExporters,
636
- value: unhealthyExporterCount
637
- });
638
- for (const gateName of this.requiredContractGates){
639
- const gate = this.contractGates.get(gateName);
640
- if (!gate) {
641
- failures.push({
642
- reason: 'contract_gate_missing',
643
- gate: gateName,
644
- message: `Contract gate "${gateName}" is missing`
645
- });
646
- continue;
647
- }
648
- if (!gate.passed) failures.push({
649
- reason: 'contract_gate_failed',
650
- gate: gateName,
651
- message: gate.reason || `Contract gate "${gateName}" is not passing`
652
- });
653
- }
654
- return {
655
- failures,
656
- queueStats,
657
- unhealthyExporterCount
658
- };
659
- }
660
- evaluate() {
661
- const now = Date.now();
662
- const { failures, queueStats, unhealthyExporterCount } = this.collectFailures();
663
- let action = 'hold';
664
- if (failures.length > 0) {
665
- this.consecutiveHealthy = 0;
666
- this.consecutiveFailures += 1;
667
- if ('rolled_back' !== this.state && this.consecutiveFailures >= this.rollbackConsecutiveFailures) {
668
- this.state = 'rolled_back';
669
- action = 'rollback';
670
- }
671
- } else {
672
- this.consecutiveFailures = 0;
673
- this.consecutiveHealthy += 1;
674
- if ('canary' === this.state && this.consecutiveHealthy >= this.minConsecutiveHealthyEvaluations) {
675
- this.state = 'promoted';
676
- action = 'promote';
677
- }
678
- }
679
- const decision = {
680
- timestamp: now,
681
- action,
682
- state: this.state,
683
- consecutiveHealthy: this.consecutiveHealthy,
684
- consecutiveFailures: this.consecutiveFailures,
685
- failures,
686
- queueStats,
687
- unhealthyExporterCount,
688
- contractGates: Array.from(this.contractGates.values()).map((item)=>({
689
- ...item
690
- }))
691
- };
692
- try {
693
- this.onEvaluate?.(decision);
694
- } catch (_error) {}
695
- if ('promote' === action) try {
696
- this.onPromote?.(decision);
697
- } catch (_error) {}
698
- if ('rollback' === action) try {
699
- this.onRollback?.(decision);
700
- } catch (_error) {}
701
- return decision;
702
- }
703
- getStatusSnapshot() {
704
- const now = Date.now();
705
- const { failures, queueStats, unhealthyExporterCount } = this.collectFailures();
706
- return {
707
- timestamp: now,
708
- state: this.state,
709
- consecutiveHealthy: this.consecutiveHealthy,
710
- consecutiveFailures: this.consecutiveFailures,
711
- queueStats,
712
- unhealthyExporterCount,
713
- requiredContractGates: [
714
- ...this.requiredContractGates
715
- ],
716
- contractGates: Array.from(this.contractGates.values()).map((item)=>({
717
- ...item
718
- })),
719
- failurePreview: failures
720
- };
721
- }
722
- start() {
723
- if (this.evaluationTimer) return;
724
- this.evaluationTimer = setInterval(()=>{
725
- this.evaluate();
726
- }, this.evaluationIntervalMs);
727
- if ('function' == typeof this.evaluationTimer.unref) this.evaluationTimer.unref();
728
- }
729
- stop() {
730
- if (this.evaluationTimer) {
731
- clearInterval(this.evaluationTimer);
732
- this.evaluationTimer = void 0;
733
- }
734
- }
735
- constructor(options){
736
- this.requiredContractGates = [];
737
- this.contractGates = new Map();
738
- this.state = 'canary';
739
- this.consecutiveHealthy = 0;
740
- this.consecutiveFailures = 0;
741
- this.registry = options.registry;
742
- this.evaluationIntervalMs = Math.max(250, options.evaluationIntervalMs ?? 15000);
743
- this.minConsecutiveHealthyEvaluations = Math.max(1, options.minConsecutiveHealthyEvaluations ?? 3);
744
- this.rollbackConsecutiveFailures = Math.max(1, options.rollbackConsecutiveFailures ?? 2);
745
- this.maxQueueUtilization = clamp(options.maxQueueUtilization ?? 0.8, 0, 1);
746
- this.maxTotalDropped = Math.max(0, options.maxTotalDropped ?? 0);
747
- this.maxUnhealthyExporters = Math.max(0, options.maxUnhealthyExporters ?? 0);
748
- this.setRequiredContractGates(options.requiredContractGates || []);
749
- this.onEvaluate = options.onEvaluate;
750
- this.onPromote = options.onPromote;
751
- this.onRollback = options.onRollback;
752
- }
753
- }
754
- function normalizeMetricsInput(prefixOrTags, tags) {
755
- if ('string' == typeof prefixOrTags) return {
756
- prefix: prefixOrTags,
757
- tags: tags || {}
758
- };
759
- if (isRecord(prefixOrTags)) return {
760
- prefix: void 0,
761
- tags: prefixOrTags
762
- };
763
- return {
764
- prefix: void 0,
765
- tags: tags || {}
766
- };
767
- }
768
- function normalizeMetricName(name, prefix) {
769
- return prefix && prefix.length > 0 ? `${prefix}.${name}` : name;
770
- }
771
- function toTelemetryMetricTags(tags) {
772
- const output = {};
773
- for (const [key, value] of Object.entries(tags))if (null != value) output[key] = String(value);
774
- return output;
775
- }
776
- function getTraceContext(tags) {
777
- const traceId = 'string' == typeof tags.trace_id ? tags.trace_id : 'string' == typeof tags.traceId ? tags.traceId : void 0;
778
- const spanId = 'string' == typeof tags.span_id ? tags.span_id : 'string' == typeof tags.spanId ? tags.spanId : void 0;
779
- const parentSpanId = 'string' == typeof tags.parent_span_id ? tags.parent_span_id : 'string' == typeof tags.parentSpanId ? tags.parentSpanId : void 0;
780
- return {
781
- traceId,
782
- spanId,
783
- parentSpanId
784
- };
785
- }
786
- const createTelemetryAwareMetrics = (baseMetrics, registry)=>{
787
- const emitCounter = (name, value, prefixOrTags, tags)=>{
788
- const normalized = normalizeMetricsInput(prefixOrTags, tags);
789
- baseMetrics.emitCounter(name, value, normalized.prefix, normalized.tags);
790
- try {
791
- const metricName = normalizeMetricName(name, normalized.prefix);
792
- const traceContext = getTraceContext(normalized.tags);
793
- registry.enqueueMetric({
794
- name: metricName,
795
- value,
796
- unit: 'count',
797
- traceId: traceContext.traceId,
798
- spanId: traceContext.spanId,
799
- parentSpanId: traceContext.parentSpanId,
800
- tags: toTelemetryMetricTags(normalized.tags),
801
- attributes: normalized.tags
802
- });
803
- } catch (_error) {}
804
- };
805
- const emitTimer = (name, value, prefixOrTags, tags)=>{
806
- const normalized = normalizeMetricsInput(prefixOrTags, tags);
807
- baseMetrics.emitTimer(name, value, normalized.prefix, normalized.tags);
808
- try {
809
- const metricName = normalizeMetricName(name, normalized.prefix);
810
- const traceContext = getTraceContext(normalized.tags);
811
- registry.enqueueMetric({
812
- name: metricName,
813
- value,
814
- unit: 'ms',
815
- traceId: traceContext.traceId,
816
- spanId: traceContext.spanId,
817
- parentSpanId: traceContext.parentSpanId,
818
- tags: toTelemetryMetricTags(normalized.tags),
819
- attributes: normalized.tags
820
- });
821
- } catch (_error) {}
822
- };
823
- return {
824
- ...baseMetrics,
825
- emitCounter,
826
- emitTimer
827
- };
828
- };
829
- function resolveRuntimeFallbackSignalEndpoint(configuredEndpoint) {
830
- const rawEndpoint = configuredEndpoint?.trim();
831
- if (!rawEndpoint) return DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
832
- if (rawEndpoint.startsWith('/')) return rawEndpoint;
833
- try {
834
- return new URL(rawEndpoint).pathname || DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
835
- } catch (_error) {
836
- return `/${rawEndpoint.replace(/^\/+/, '')}`;
837
- }
838
- }
839
- function createRuntimeSignalError(message, code) {
840
- const error = new Error(message);
841
- error.code = code;
842
- return error;
843
- }
844
- function getUtf8ByteLength(input) {
845
- if ("u" > typeof Buffer) return Buffer.byteLength(input);
846
- return new TextEncoder().encode(input).length;
847
- }
848
- function normalizeRuntimeSignalOrigin(value) {
849
- if ('string' != typeof value || 0 === value.trim().length) return;
850
- try {
851
- return new URL(value).origin;
852
- } catch (_error) {
853
- return;
854
- }
855
- }
856
- function normalizeRuntimeSignalAppName(payload) {
857
- if ('string' != typeof payload.appName) return 'unknown';
858
- const normalized = payload.appName.trim();
859
- return normalized.length > 0 ? normalized : 'unknown';
860
- }
861
- function normalizeRuntimeSignalRuntimeDigest(payload) {
862
- if ('string' == typeof payload.runtimeDigest && payload.runtimeDigest.trim()) return payload.runtimeDigest.trim();
863
- const metadata = payload.metadata;
864
- if (metadata && 'object' == typeof metadata && !Array.isArray(metadata) && 'string' == typeof metadata.runtimeDigest) {
865
- const digest = String(metadata.runtimeDigest).trim();
866
- if (digest) return digest;
867
- }
868
- }
869
- function normalizeRuntimeFallbackSignalAuthConfig(configured) {
870
- const headerName = 'string' == typeof configured?.headerName && configured.headerName.trim() ? configured.headerName.trim().toLowerCase() : DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER;
871
- const expectedFromEnv = 'string' == typeof configured?.expectedValueEnv && configured.expectedValueEnv.trim().length > 0 ? process.env[configured.expectedValueEnv.trim()] : void 0;
872
- const expectedFromConfig = 'string' == typeof configured?.expectedValue && configured.expectedValue.trim().length > 0 ? configured.expectedValue.trim() : void 0;
873
- const expectedValue = expectedFromConfig || expectedFromEnv;
874
- const enabled = configured?.enabled === true;
875
- if (enabled && !expectedValue) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled is true but no expected token is configured');
876
- return {
877
- enabled,
878
- headerName,
879
- expectedValue
880
- };
881
- }
882
- function enforceRuntimeFallbackSignalAuthToken(token, authConfig) {
883
- if (!authConfig.enabled) return;
884
- if (!token || token !== authConfig.expectedValue) throw createRuntimeSignalError('runtime fallback signal auth failed', 'UNAUTHORIZED');
885
- }
886
- function enforceRuntimeFallbackSignalAuth(c, runtimeSignalConfig) {
887
- enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeSignalConfig.auth.headerName), runtimeSignalConfig.auth);
888
- }
889
- function normalizeRuntimeFallbackTrustPolicy(configured) {
890
- const allowedApps = Array.isArray(configured?.allowedApps) ? configured.allowedApps.map((item)=>'string' == typeof item ? item.trim() : '').filter(Boolean) : [];
891
- const allowedEntryOrigins = Array.isArray(configured?.allowedEntryOrigins) ? configured.allowedEntryOrigins.map((item)=>normalizeRuntimeSignalOrigin(item)).filter((item)=>Boolean(item)) : [];
892
- const expectedRuntimeDigestsRaw = configured?.expectedRuntimeDigests || {};
893
- const expectedRuntimeDigests = {};
894
- Object.entries(expectedRuntimeDigestsRaw).forEach(([appName, digest])=>{
895
- if ('string' == typeof appName && appName.trim().length > 0 && 'string' == typeof digest && digest.trim().length > 0) expectedRuntimeDigests[appName.trim()] = digest.trim();
896
- });
897
- return {
898
- allowedApps,
899
- allowedEntryOrigins,
900
- expectedRuntimeDigests,
901
- enforceRuntimeDigest: configured?.enforceRuntimeDigest === true,
902
- maxSignalsPerWindow: Math.max(1, Math.floor(configured?.maxSignalsPerWindow ?? DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW)),
903
- windowMs: Math.max(1000, Math.floor(configured?.windowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS)),
904
- dedupeWindowMs: Math.max(0, Math.floor(configured?.dedupeWindowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS))
905
- };
906
- }
907
- function createRuntimeFallbackSignalRuntimeState() {
908
- return {
909
- rateLimitBySource: new Map(),
910
- dedupeByFingerprint: new Map()
911
- };
912
- }
913
- function cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy) {
914
- const dedupeExpiryMs = Math.max(trustPolicy.dedupeWindowMs, trustPolicy.windowMs, 1000);
915
- runtimeState.dedupeByFingerprint.forEach((lastSeenAt, fingerprint)=>{
916
- if (now - lastSeenAt > dedupeExpiryMs) runtimeState.dedupeByFingerprint.delete(fingerprint);
917
- });
918
- runtimeState.rateLimitBySource.forEach((state, source)=>{
919
- if (now - state.windowStartedAt > 2 * trustPolicy.windowMs) runtimeState.rateLimitBySource.delete(source);
920
- });
921
- }
922
- function enforceRuntimeFallbackSignalTrustPolicy(payload, runtimeSignalContext) {
923
- const { trustPolicy, runtimeState } = runtimeSignalContext;
924
- const now = Date.now();
925
- cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy);
926
- const appName = normalizeRuntimeSignalAppName(payload);
927
- const entryOrigin = normalizeRuntimeSignalOrigin(payload.entry);
928
- const runtimeDigest = normalizeRuntimeSignalRuntimeDigest(payload);
929
- if (trustPolicy.allowedApps.length > 0 && !trustPolicy.allowedApps.includes(appName)) throw createRuntimeSignalError(`runtime fallback signal app "${appName}" is not trusted`, 'UNTRUSTED_SOURCE');
930
- if (trustPolicy.allowedEntryOrigins.length > 0) {
931
- if (!entryOrigin || !trustPolicy.allowedEntryOrigins.includes(entryOrigin)) throw createRuntimeSignalError(`runtime fallback signal entry origin "${entryOrigin || 'unknown'}" is not trusted`, 'UNTRUSTED_SOURCE');
932
- }
933
- const expectedDigest = trustPolicy.expectedRuntimeDigests[appName];
934
- if (expectedDigest && runtimeDigest !== expectedDigest) throw createRuntimeSignalError(`runtime fallback runtimeDigest mismatch for app "${appName}"`, 'UNTRUSTED_SOURCE');
935
- if (trustPolicy.enforceRuntimeDigest && !runtimeDigest) throw createRuntimeSignalError(`runtime fallback signal for app "${appName}" is missing runtimeDigest`, 'UNTRUSTED_SOURCE');
936
- const dedupeFingerprint = JSON.stringify({
937
- appName,
938
- entryOrigin: entryOrigin || 'unknown',
939
- reason: payload.reason || 'runtime_fallback',
940
- phase: payload.phase || 'unknown',
941
- runtimeDigest: runtimeDigest || 'unknown'
942
- });
943
- const dedupeWindowMs = trustPolicy.dedupeWindowMs;
944
- if (dedupeWindowMs > 0) {
945
- const lastSeenAt = runtimeState.dedupeByFingerprint.get(dedupeFingerprint);
946
- runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
947
- if ('number' == typeof lastSeenAt && now - lastSeenAt <= dedupeWindowMs) return {
948
- deduped: true
949
- };
950
- } else runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
951
- const sourceKey = `${appName}@${entryOrigin || 'unknown'}`;
952
- const rateState = runtimeState.rateLimitBySource.get(sourceKey);
953
- if (!rateState || now - rateState.windowStartedAt > trustPolicy.windowMs) runtimeState.rateLimitBySource.set(sourceKey, {
954
- count: 1,
955
- windowStartedAt: now
956
- });
957
- else {
958
- if (rateState.count >= trustPolicy.maxSignalsPerWindow) throw createRuntimeSignalError(`runtime fallback signal rate-limited for source "${sourceKey}"`, 'RATE_LIMITED');
959
- rateState.count += 1;
960
- }
961
- return {
962
- deduped: false
963
- };
964
- }
965
- function maybeWarnLegacyOtlpEndpoint(endpoint) {
966
- if (!endpoint || !endpoint.includes('/v1/metrics')) return;
967
- console.warn(`[telemetry] OTLP endpoint "${endpoint}" looks like a metrics path. UltraModern telemetry exporter expects log-style envelopes (default: ${DEFAULT_OTLP_ENDPOINT}).`);
968
- }
969
- async function parseRuntimeFallbackSignalPayload(c, maxBodyBytes) {
970
- const contentLengthHeader = c.req.header('content-length');
971
- if (contentLengthHeader) {
972
- const contentLength = Number.parseInt(contentLengthHeader, 10);
973
- if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
974
- }
975
- const rawBody = await c.req.raw.text();
976
- const payload = parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes);
977
- return {
978
- rawBody,
979
- payload
980
- };
981
- }
982
- function parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes) {
983
- if (!rawBody || 0 === rawBody.trim().length) throw createRuntimeSignalError('runtime fallback signal body is empty', 'INVALID_PAYLOAD');
984
- if (getUtf8ByteLength(rawBody) > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
985
- let payload;
986
- try {
987
- payload = JSON.parse(rawBody);
988
- } catch (_error) {
989
- throw createRuntimeSignalError('runtime fallback signal body must be valid JSON', 'INVALID_PAYLOAD');
990
- }
991
- if (!payload || 'object' != typeof payload || Array.isArray(payload)) throw createRuntimeSignalError('runtime fallback signal body must be a JSON object', 'INVALID_PAYLOAD');
992
- return payload;
993
- }
994
- function getRuntimeSignalErrorStatusCode(signalError) {
995
- if ('PAYLOAD_TOO_LARGE' === signalError.code) return 413;
996
- if ('INVALID_PAYLOAD' === signalError.code) return 400;
997
- if ('UNAUTHORIZED' === signalError.code) return 401;
998
- if ('RATE_LIMITED' === signalError.code) return 429;
999
- if ('UNTRUSTED_SOURCE' === signalError.code) return 403;
1000
- return 500;
1001
- }
1002
- async function persistRuntimeFallbackContractGate(payload, runtimeSignalConfig) {
1003
- const now = Date.now();
1004
- const gateSnapshotStore = await runtimeSignalConfig.gateSnapshotStore;
1005
- const snapshot = await gateSnapshotStore.readSnapshot() || {};
1006
- const existingGates = snapshot.gates && 'object' == typeof snapshot.gates ? snapshot.gates : {};
1007
- const reason = 'string' == typeof payload.reason ? payload.reason : 'runtime_fallback';
1008
- const phase = 'string' == typeof payload.phase ? payload.phase : 'unknown';
1009
- const appName = 'string' == typeof payload.appName ? payload.appName : 'unknown';
1010
- const entry = 'string' == typeof payload.entry ? payload.entry : void 0;
1011
- snapshot.schemaVersion = 'number' == typeof snapshot.schemaVersion ? snapshot.schemaVersion : external_contractGateSnapshotStore_js_namespaceObject.CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
1012
- snapshot.updatedAt = now;
1013
- snapshot.gates = {
1014
- ...existingGates,
1015
- [runtimeSignalConfig.gateName]: {
1016
- passed: false,
1017
- reason: `runtime_fallback:${reason} phase=${phase} app=${appName}${entry ? ` entry=${entry}` : ''}`,
1018
- updatedAt: now,
1019
- expiresAt: now + runtimeSignalConfig.failureHoldMs,
1020
- source: 'runtime-mf-fallback-signal',
1021
- metadata: payload
1022
- }
1023
- };
1024
- await gateSnapshotStore.writeSnapshot(snapshot);
1025
- }
1026
- function emitCanaryDecisionMetric(registry, decision, action) {
1027
- try {
1028
- registry.enqueueMetric({
1029
- name: `telemetry.canary.${action}`,
1030
- value: 1,
1031
- unit: 'count',
1032
- tags: {
1033
- action,
1034
- state: decision.state,
1035
- failures: String(decision.failures.length)
1036
- }
1037
- });
1038
- } catch (_error) {}
1039
- }
1040
- const hasEnabledTelemetryExporters = (config)=>Boolean(config?.exporters?.otlp?.enabled || config?.exporters?.victoriaMetrics?.enabled);
1041
- const injectTelemetryPlugin = ()=>({
1042
- name: '@modern-js/inject-telemetry',
1043
- setup (api) {
1044
- const serverConfig = api.getServerConfig();
1045
- const telemetryConfig = serverConfig?.server?.telemetry;
1046
- if (!telemetryConfig) return;
1047
- if (true !== telemetryConfig.enabled && !hasEnabledTelemetryExporters(telemetryConfig)) return;
1048
- const { middlewares, metaName, appDirectory } = api.getServerContext();
1049
- const serviceName = telemetryConfig.service || metaName || 'modern-js';
1050
- const moduleName = telemetryConfig.module || 'server';
1051
- const environmentName = telemetryConfig.environment || process.env.MODERN_ENV || process.env.NODE_ENV || 'development';
1052
- const registry = new TelemetryRegistry({
1053
- service: serviceName,
1054
- module: moduleName,
1055
- environment: environmentName,
1056
- samplingRate: telemetryConfig.samplingRate,
1057
- flushIntervalMs: telemetryConfig.flushIntervalMs,
1058
- maxBatchSize: telemetryConfig.maxBatchSize,
1059
- maxQueueSize: telemetryConfig.maxQueueSize,
1060
- redactionKeys: telemetryConfig.redactionKeys
1061
- });
1062
- let canaryOrchestrator;
1063
- let contractGateAutopilot;
1064
- let runtimeFallbackSignalConfig;
1065
- let gateSnapshotStorePromise;
1066
- const canaryConfig = telemetryConfig.canary;
1067
- if (canaryConfig?.enabled) {
1068
- const contractGates = canaryConfig.contractGates;
1069
- canaryOrchestrator = new TelemetryCanaryOrchestrator({
1070
- registry,
1071
- evaluationIntervalMs: canaryConfig.evaluationIntervalMs,
1072
- minConsecutiveHealthyEvaluations: canaryConfig.minConsecutiveHealthyEvaluations,
1073
- rollbackConsecutiveFailures: canaryConfig.rollbackConsecutiveFailures,
1074
- maxQueueUtilization: canaryConfig.maxQueueUtilization,
1075
- maxTotalDropped: canaryConfig.maxTotalDropped,
1076
- maxUnhealthyExporters: canaryConfig.maxUnhealthyExporters,
1077
- requiredContractGates: Object.keys(contractGates || {}),
1078
- onPromote: (decision)=>{
1079
- emitCanaryDecisionMetric(registry, decision, 'promote');
1080
- },
1081
- onRollback: (decision)=>{
1082
- emitCanaryDecisionMetric(registry, decision, 'rollback');
1083
- }
1084
- });
1085
- if (contractGates) canaryOrchestrator.setContractGates(contractGates);
1086
- const autopilotEnabled = canaryConfig.autopilot?.enabled ?? true;
1087
- if (autopilotEnabled) {
1088
- const gateSnapshotPath = (0, external_contractGateSnapshotStore_js_namespaceObject.resolveContractGateSnapshotPath)(appDirectory, canaryConfig.autopilot?.gateSnapshotPath);
1089
- gateSnapshotStorePromise = (0, external_contractGateSnapshotStore_js_namespaceObject.resolveContractGateSnapshotStore)({
1090
- appDirectory,
1091
- gateSnapshotPath: gateSnapshotPath || external_contractGateSnapshotStore_js_namespaceObject.DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
1092
- stateStore: canaryConfig.autopilot?.stateStore
1093
- });
1094
- const runtimeSignalConfig = canaryConfig.autopilot?.runtimeFallbackSignal;
1095
- const runtimeSignalEnabled = runtimeSignalConfig?.enabled ?? true;
1096
- if (runtimeSignalEnabled && gateSnapshotStorePromise) runtimeFallbackSignalConfig = {
1097
- endpoint: resolveRuntimeFallbackSignalEndpoint(runtimeSignalConfig?.endpoint),
1098
- gateName: runtimeSignalConfig?.gateName?.trim() || DEFAULT_RUNTIME_FALLBACK_GATE_NAME,
1099
- gateSnapshotStore: gateSnapshotStorePromise,
1100
- failureHoldMs: Math.max(1000, runtimeSignalConfig?.failureHoldMs ?? DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS),
1101
- maxBodyBytes: Math.max(512, runtimeSignalConfig?.maxBodyBytes ?? DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES),
1102
- auth: normalizeRuntimeFallbackSignalAuthConfig(runtimeSignalConfig?.auth),
1103
- trustPolicy: normalizeRuntimeFallbackTrustPolicy(runtimeSignalConfig?.trustPolicy),
1104
- runtimeState: createRuntimeFallbackSignalRuntimeState()
1105
- };
1106
- }
1107
- }
1108
- if (runtimeFallbackSignalConfig) {
1109
- const signalConfig = runtimeFallbackSignalConfig;
1110
- middlewares.push({
1111
- name: 'telemetry-runtime-fallback-signal',
1112
- path: signalConfig.endpoint,
1113
- method: 'post',
1114
- order: 'pre',
1115
- handler: async (c)=>{
1116
- try {
1117
- enforceRuntimeFallbackSignalAuth(c, signalConfig);
1118
- const { payload } = await parseRuntimeFallbackSignalPayload(c, signalConfig.maxBodyBytes);
1119
- const trustResult = enforceRuntimeFallbackSignalTrustPolicy(payload, signalConfig);
1120
- if (trustResult.deduped) return c.json({
1121
- ok: true,
1122
- deduped: true
1123
- }, 202);
1124
- await persistRuntimeFallbackContractGate(payload, signalConfig);
1125
- return c.json({
1126
- ok: true
1127
- }, 202);
1128
- } catch (error) {
1129
- const signalError = error;
1130
- const status = getRuntimeSignalErrorStatusCode(signalError);
1131
- return c.json({
1132
- ok: false,
1133
- error: signalError instanceof Error ? signalError.message : String(signalError)
1134
- }, status);
1135
- }
1136
- }
1137
- });
1138
- }
1139
- middlewares.push({
1140
- name: 'telemetry-runtime-status',
1141
- path: DEFAULT_RUNTIME_STATUS_ENDPOINT,
1142
- method: 'get',
1143
- order: 'pre',
1144
- handler: async (c)=>{
1145
- try {
1146
- if (runtimeFallbackSignalConfig?.auth.enabled) enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeFallbackSignalConfig.auth.headerName), runtimeFallbackSignalConfig.auth);
1147
- return c.json({
1148
- ok: true,
1149
- timestamp: Date.now(),
1150
- telemetry: {
1151
- queueStats: registry.getQueueStats(),
1152
- exporterHealth: registry.getExporterHealth()
1153
- },
1154
- canary: canaryOrchestrator ? {
1155
- enabled: true,
1156
- ...canaryOrchestrator.getStatusSnapshot()
1157
- } : {
1158
- enabled: false
1159
- },
1160
- runtimeFallbackSignal: runtimeFallbackSignalConfig ? {
1161
- enabled: true,
1162
- endpoint: runtimeFallbackSignalConfig.endpoint,
1163
- gateName: runtimeFallbackSignalConfig.gateName,
1164
- failureHoldMs: runtimeFallbackSignalConfig.failureHoldMs,
1165
- maxBodyBytes: runtimeFallbackSignalConfig.maxBodyBytes,
1166
- auth: {
1167
- enabled: runtimeFallbackSignalConfig.auth.enabled,
1168
- headerName: runtimeFallbackSignalConfig.auth.headerName
1169
- },
1170
- trustPolicy: {
1171
- allowedApps: runtimeFallbackSignalConfig.trustPolicy.allowedApps,
1172
- allowedEntryOrigins: runtimeFallbackSignalConfig.trustPolicy.allowedEntryOrigins,
1173
- enforceRuntimeDigest: runtimeFallbackSignalConfig.trustPolicy.enforceRuntimeDigest,
1174
- expectedRuntimeDigestsCount: Object.keys(runtimeFallbackSignalConfig.trustPolicy.expectedRuntimeDigests).length,
1175
- maxSignalsPerWindow: runtimeFallbackSignalConfig.trustPolicy.maxSignalsPerWindow,
1176
- windowMs: runtimeFallbackSignalConfig.trustPolicy.windowMs,
1177
- dedupeWindowMs: runtimeFallbackSignalConfig.trustPolicy.dedupeWindowMs
1178
- }
1179
- } : {
1180
- enabled: false
1181
- }
1182
- });
1183
- } catch (error) {
1184
- const signalError = error;
1185
- return c.json({
1186
- ok: false,
1187
- error: signalError instanceof Error ? signalError.message : String(signalError)
1188
- }, getRuntimeSignalErrorStatusCode(signalError));
1189
- }
1190
- }
1191
- });
1192
- middlewares.push({
1193
- name: 'inject-telemetry',
1194
- handler: async (c, next)=>{
1195
- const monitors = c.get('monitors');
1196
- if (monitors) {
1197
- const traceContext = parseTraceparent(c.req.header('traceparent'));
1198
- const monitor = (event)=>{
1199
- registry.enqueue(toTelemetryEnvelope(event, {
1200
- service: serviceName,
1201
- module: moduleName,
1202
- environment: environmentName,
1203
- traceId: traceContext?.traceId,
1204
- spanId: traceContext?.spanId,
1205
- attributes: {
1206
- requestMethod: c.req.method,
1207
- requestPath: c.req.path
1208
- }
1209
- }));
1210
- };
1211
- monitors.push(monitor);
1212
- }
1213
- await next();
1214
- }
1215
- });
1216
- let prepared = false;
1217
- api.onPrepare(async ()=>{
1218
- if (prepared) return;
1219
- prepared = true;
1220
- if (telemetryConfig.exporters?.otlp?.enabled) {
1221
- maybeWarnLegacyOtlpEndpoint(telemetryConfig.exporters.otlp.endpoint);
1222
- await registry.register(createOtlpTelemetryExporter(telemetryConfig.exporters.otlp));
1223
- }
1224
- if (telemetryConfig.exporters?.victoriaMetrics?.enabled) await registry.register(createVictoriaMetricsTelemetryExporter(telemetryConfig.exporters.victoriaMetrics));
1225
- await registry.startupHealthCheck({
1226
- failLoud: telemetryConfig.failLoudStartup ?? true
1227
- });
1228
- if (!canaryOrchestrator) return;
1229
- canaryOrchestrator.start();
1230
- if (gateSnapshotStorePromise) {
1231
- const gateSnapshotStore = await gateSnapshotStorePromise;
1232
- contractGateAutopilot = new external_contractGateAutopilot_js_namespaceObject.ContractGateAutopilot({
1233
- orchestrator: canaryOrchestrator,
1234
- gateSnapshotPath: (0, external_contractGateSnapshotStore_js_namespaceObject.resolveContractGateSnapshotPath)(appDirectory, canaryConfig?.autopilot?.gateSnapshotPath),
1235
- gateSnapshotStore,
1236
- pollIntervalMs: canaryConfig?.autopilot?.pollIntervalMs,
1237
- gateStaleAfterMs: canaryConfig?.autopilot?.gateStaleAfterMs
1238
- });
1239
- }
1240
- if (contractGateAutopilot) await contractGateAutopilot.start();
1241
- canaryOrchestrator.evaluate();
1242
- });
1243
- }
1244
- });
1245
- exports.DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = __webpack_exports__.DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
1246
- exports.DEFAULT_RUNTIME_STATUS_ENDPOINT = __webpack_exports__.DEFAULT_RUNTIME_STATUS_ENDPOINT;
1247
- exports.TelemetryCanaryOrchestrator = __webpack_exports__.TelemetryCanaryOrchestrator;
1248
- exports.TelemetryRegistry = __webpack_exports__.TelemetryRegistry;
1249
- exports.TelemetryStartupHealthError = __webpack_exports__.TelemetryStartupHealthError;
1250
- exports.createOtlpTelemetryExporter = __webpack_exports__.createOtlpTelemetryExporter;
1251
- exports.createRuntimeFallbackSignalRuntimeState = __webpack_exports__.createRuntimeFallbackSignalRuntimeState;
1252
- exports.createRuntimeSignalError = __webpack_exports__.createRuntimeSignalError;
1253
- exports.createTelemetryAwareMetrics = __webpack_exports__.createTelemetryAwareMetrics;
1254
- exports.createVictoriaMetricsTelemetryExporter = __webpack_exports__.createVictoriaMetricsTelemetryExporter;
1255
- exports.enforceRuntimeFallbackSignalAuthToken = __webpack_exports__.enforceRuntimeFallbackSignalAuthToken;
1256
- exports.enforceRuntimeFallbackSignalTrustPolicy = __webpack_exports__.enforceRuntimeFallbackSignalTrustPolicy;
1257
- exports.getRuntimeSignalErrorStatusCode = __webpack_exports__.getRuntimeSignalErrorStatusCode;
1258
- exports.hasEnabledTelemetryExporters = __webpack_exports__.hasEnabledTelemetryExporters;
1259
- exports.injectTelemetryPlugin = __webpack_exports__.injectTelemetryPlugin;
1260
- exports.normalizeRuntimeFallbackSignalAuthConfig = __webpack_exports__.normalizeRuntimeFallbackSignalAuthConfig;
1261
- exports.normalizeRuntimeFallbackTrustPolicy = __webpack_exports__.normalizeRuntimeFallbackTrustPolicy;
1262
- exports.parseRuntimeFallbackSignalPayloadFromRawBody = __webpack_exports__.parseRuntimeFallbackSignalPayloadFromRawBody;
1263
- exports.resolveRuntimeFallbackSignalEndpoint = __webpack_exports__.resolveRuntimeFallbackSignalEndpoint;
1264
- for(var __rspack_i in __webpack_exports__)if (-1 === [
1265
- "DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT",
1266
- "DEFAULT_RUNTIME_STATUS_ENDPOINT",
1267
- "TelemetryCanaryOrchestrator",
1268
- "TelemetryRegistry",
1269
- "TelemetryStartupHealthError",
1270
- "createOtlpTelemetryExporter",
1271
- "createRuntimeFallbackSignalRuntimeState",
1272
- "createRuntimeSignalError",
1273
- "createTelemetryAwareMetrics",
1274
- "createVictoriaMetricsTelemetryExporter",
1275
- "enforceRuntimeFallbackSignalAuthToken",
1276
- "enforceRuntimeFallbackSignalTrustPolicy",
1277
- "getRuntimeSignalErrorStatusCode",
1278
- "hasEnabledTelemetryExporters",
1279
- "injectTelemetryPlugin",
1280
- "normalizeRuntimeFallbackSignalAuthConfig",
1281
- "normalizeRuntimeFallbackTrustPolicy",
1282
- "parseRuntimeFallbackSignalPayloadFromRawBody",
1283
- "resolveRuntimeFallbackSignalEndpoint"
1284
- ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
1285
- Object.defineProperty(exports, '__esModule', {
1286
- value: true
1287
- });