@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.4 → 3.5.0-ultramodern.40

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 (175) hide show
  1. package/dist/cjs/contract-gate-snapshot-normalization.js +122 -0
  2. package/dist/cjs/contract-gate-snapshot-store/file-store.js +102 -0
  3. package/dist/cjs/contract-gate-snapshot-store/http-store.js +133 -0
  4. package/dist/cjs/contract-gate-snapshot-store/index.js +58 -0
  5. package/dist/cjs/contract-gate-snapshot-store/resolve.js +124 -0
  6. package/dist/cjs/contract-gate-snapshot-store/types.js +44 -0
  7. package/dist/cjs/contractGateAutopilot.js +22 -70
  8. package/dist/cjs/index.js +6 -25
  9. package/dist/cjs/module-federation-css/collector.js +79 -0
  10. package/dist/cjs/module-federation-css/index.js +55 -0
  11. package/dist/cjs/module-federation-css/manifest.js +129 -0
  12. package/dist/cjs/module-federation-css/plugin.js +71 -0
  13. package/dist/cjs/module-federation-css/remote.js +133 -0
  14. package/dist/cjs/runtime-fallback-signal/index.js +93 -0
  15. package/dist/cjs/runtime-fallback-signal/model.js +157 -0
  16. package/dist/cjs/runtime-fallback-signal/resolver.js +163 -0
  17. package/dist/cjs/runtime-fallback-signal/store.js +83 -0
  18. package/dist/cjs/runtimeFallbackSignal.js +32 -281
  19. package/dist/cjs/telemetry/canary.js +180 -0
  20. package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
  21. package/dist/cjs/telemetry/canarySetup.js +107 -0
  22. package/dist/cjs/telemetry/envelope.js +223 -0
  23. package/dist/cjs/telemetry/exporters.js +148 -0
  24. package/dist/cjs/telemetry/lifecycle.js +98 -0
  25. package/dist/cjs/telemetry/metrics.js +115 -0
  26. package/dist/cjs/telemetry/plugin.js +185 -0
  27. package/dist/cjs/telemetry/registry.js +296 -0
  28. package/dist/cjs/telemetry/registryTypes.js +46 -0
  29. package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
  30. package/dist/cjs/telemetry.js +32 -343
  31. package/dist/cjs/telemetryCore.js +14 -767
  32. package/dist/esm/contract-gate-snapshot-normalization.mjs +81 -0
  33. package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
  34. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
  35. package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
  36. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +70 -0
  37. package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
  38. package/dist/esm/contractGateAutopilot.mjs +21 -69
  39. package/dist/esm/index.mjs +1 -2
  40. package/dist/esm/module-federation-css/collector.mjs +38 -0
  41. package/dist/esm/module-federation-css/index.mjs +4 -0
  42. package/dist/esm/module-federation-css/manifest.mjs +69 -0
  43. package/dist/esm/module-federation-css/plugin.mjs +33 -0
  44. package/dist/esm/module-federation-css/remote.mjs +92 -0
  45. package/dist/esm/runtime-fallback-signal/index.mjs +3 -0
  46. package/dist/esm/runtime-fallback-signal/model.mjs +73 -0
  47. package/dist/esm/runtime-fallback-signal/resolver.mjs +107 -0
  48. package/dist/esm/runtime-fallback-signal/store.mjs +39 -0
  49. package/dist/esm/runtimeFallbackSignal.mjs +1 -222
  50. package/dist/esm/telemetry/canary.mjs +142 -0
  51. package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
  52. package/dist/esm/telemetry/canarySetup.mjs +69 -0
  53. package/dist/esm/telemetry/envelope.mjs +164 -0
  54. package/dist/esm/telemetry/exporters.mjs +104 -0
  55. package/dist/esm/telemetry/lifecycle.mjs +60 -0
  56. package/dist/esm/telemetry/metrics.mjs +77 -0
  57. package/dist/esm/telemetry/plugin.mjs +87 -0
  58. package/dist/esm/telemetry/registry.mjs +258 -0
  59. package/dist/esm/telemetry/registryTypes.mjs +8 -0
  60. package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
  61. package/dist/esm/telemetry.mjs +1 -275
  62. package/dist/esm/telemetryCore.mjs +6 -759
  63. package/dist/esm-node/contract-gate-snapshot-normalization.mjs +82 -0
  64. package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
  65. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
  66. package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
  67. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +71 -0
  68. package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
  69. package/dist/esm-node/contractGateAutopilot.mjs +21 -69
  70. package/dist/esm-node/index.mjs +1 -2
  71. package/dist/esm-node/module-federation-css/collector.mjs +39 -0
  72. package/dist/esm-node/module-federation-css/index.mjs +5 -0
  73. package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
  74. package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
  75. package/dist/esm-node/module-federation-css/remote.mjs +93 -0
  76. package/dist/esm-node/runtime-fallback-signal/index.mjs +4 -0
  77. package/dist/esm-node/runtime-fallback-signal/model.mjs +74 -0
  78. package/dist/esm-node/runtime-fallback-signal/resolver.mjs +108 -0
  79. package/dist/esm-node/runtime-fallback-signal/store.mjs +40 -0
  80. package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
  81. package/dist/esm-node/telemetry/canary.mjs +143 -0
  82. package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
  83. package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
  84. package/dist/esm-node/telemetry/envelope.mjs +165 -0
  85. package/dist/esm-node/telemetry/exporters.mjs +105 -0
  86. package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
  87. package/dist/esm-node/telemetry/metrics.mjs +78 -0
  88. package/dist/esm-node/telemetry/plugin.mjs +88 -0
  89. package/dist/esm-node/telemetry/registry.mjs +259 -0
  90. package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
  91. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
  92. package/dist/esm-node/telemetry.mjs +1 -275
  93. package/dist/esm-node/telemetryCore.mjs +6 -759
  94. package/dist/types/contract-gate-snapshot-normalization.d.ts +15 -0
  95. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
  96. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +5 -0
  97. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
  98. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
  99. package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
  100. package/dist/types/contractGateAutopilot.d.ts +3 -6
  101. package/dist/types/index.d.ts +1 -2
  102. package/dist/types/module-federation-css/collector.d.ts +25 -0
  103. package/dist/types/module-federation-css/index.d.ts +8 -0
  104. package/dist/types/module-federation-css/manifest.d.ts +28 -0
  105. package/dist/types/module-federation-css/plugin.d.ts +23 -0
  106. package/dist/types/module-federation-css/remote.d.ts +20 -0
  107. package/dist/types/runtime-fallback-signal/index.d.ts +4 -0
  108. package/dist/types/runtime-fallback-signal/model.d.ts +70 -0
  109. package/dist/types/runtime-fallback-signal/resolver.d.ts +29 -0
  110. package/dist/types/runtime-fallback-signal/store.d.ts +4 -0
  111. package/dist/types/runtimeFallbackSignal.d.ts +1 -94
  112. package/dist/types/telemetry/canary.d.ts +85 -0
  113. package/dist/types/telemetry/canaryEvaluation.d.ts +20 -0
  114. package/dist/types/telemetry/canarySetup.d.ts +17 -0
  115. package/dist/types/telemetry/envelope.d.ts +55 -0
  116. package/dist/types/telemetry/exporters.d.ts +12 -0
  117. package/dist/types/telemetry/lifecycle.d.ts +18 -0
  118. package/dist/types/telemetry/metrics.d.ts +3 -0
  119. package/dist/types/telemetry/plugin.d.ts +12 -0
  120. package/dist/types/telemetry/registry.d.ts +69 -0
  121. package/dist/types/telemetry/registryTypes.d.ts +50 -0
  122. package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
  123. package/dist/types/telemetry.d.ts +1 -12
  124. package/dist/types/telemetryCore.d.ts +6 -257
  125. package/package.json +10 -10
  126. package/src/contract-gate-snapshot-normalization.ts +155 -0
  127. package/src/contract-gate-snapshot-store/file-store.ts +83 -0
  128. package/src/contract-gate-snapshot-store/http-store.ts +159 -0
  129. package/src/contract-gate-snapshot-store/index.ts +20 -0
  130. package/src/contract-gate-snapshot-store/resolve.ts +179 -0
  131. package/src/contract-gate-snapshot-store/types.ts +64 -0
  132. package/src/contractGateAutopilot.ts +39 -131
  133. package/src/index.ts +1 -17
  134. package/src/module-federation-css/collector.ts +82 -0
  135. package/src/module-federation-css/index.ts +14 -0
  136. package/src/module-federation-css/manifest.ts +163 -0
  137. package/src/module-federation-css/plugin.ts +86 -0
  138. package/src/module-federation-css/remote.ts +165 -0
  139. package/src/runtime-fallback-signal/index.ts +34 -0
  140. package/src/runtime-fallback-signal/model.ts +230 -0
  141. package/src/runtime-fallback-signal/resolver.ts +304 -0
  142. package/src/runtime-fallback-signal/store.ts +78 -0
  143. package/src/runtimeFallbackSignal.ts +1 -584
  144. package/src/telemetry/canary.ts +291 -0
  145. package/src/telemetry/canaryEvaluation.ts +83 -0
  146. package/src/telemetry/canarySetup.ts +160 -0
  147. package/src/telemetry/envelope.ts +277 -0
  148. package/src/telemetry/exporters.ts +165 -0
  149. package/src/telemetry/lifecycle.ts +138 -0
  150. package/src/telemetry/metrics.ts +141 -0
  151. package/src/telemetry/plugin.ts +197 -0
  152. package/src/telemetry/registry.ts +424 -0
  153. package/src/telemetry/registryTypes.ts +63 -0
  154. package/src/telemetry/runtimeEndpoints.ts +172 -0
  155. package/src/telemetry.ts +1 -554
  156. package/src/telemetryCore.ts +34 -1332
  157. package/tests/contractGateAutopilot.test.ts +205 -0
  158. package/tests/contractGateSnapshotStore.test.ts +54 -1
  159. package/tests/helpers.ts +1 -0
  160. package/tests/moduleFederationCss.test.ts +1 -1
  161. package/tests/registration.test.ts +1 -1
  162. package/tests/telemetry.test.ts +51 -0
  163. package/tests/telemetryAutopilot.test.ts +141 -0
  164. package/tests/telemetryCanaryOrchestrator.test.ts +225 -0
  165. package/tests/telemetryLifecycle.test.ts +253 -2
  166. package/tests/telemetryRegistryQueueMatrix.test.ts +227 -0
  167. package/dist/cjs/contractGateSnapshotStore.js +0 -253
  168. package/dist/cjs/moduleFederationCss.js +0 -285
  169. package/dist/esm/contractGateSnapshotStore.mjs +0 -190
  170. package/dist/esm/moduleFederationCss.mjs +0 -225
  171. package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
  172. package/dist/esm-node/moduleFederationCss.mjs +0 -226
  173. package/dist/types/moduleFederationCss.d.ts +0 -87
  174. package/src/contractGateSnapshotStore.ts +0 -420
  175. package/src/moduleFederationCss.ts +0 -473
@@ -0,0 +1,88 @@
1
+ import "node:module";
2
+ import { parseTraceparent } from "@modern-js/create-request/server";
3
+ import { logger } from "@modern-js/utils";
4
+ import { parseServerRuntimeExtensionsEnv } from "../env.mjs";
5
+ import { TelemetryCanaryOrchestrator, TelemetryRegistry, TelemetryStartupHealthError, createOtlpTelemetryExporter, createTelemetryAwareMetrics, createVictoriaMetricsTelemetryExporter, toTelemetryEnvelope } from "../telemetryCore.mjs";
6
+ import { setupTelemetryCanary } from "./canarySetup.mjs";
7
+ import { registerTelemetryLifecycle } from "./lifecycle.mjs";
8
+ import { createRuntimeFallbackSignalMiddleware, createRuntimeStatusMiddleware } from "./runtimeEndpoints.mjs";
9
+ const hasEnabledTelemetryExporters = (config)=>Boolean(config?.exporters?.otlp?.enabled || config?.exporters?.victoriaMetrics?.enabled);
10
+ const resolveTelemetrySloOptions = (sloConfig, warnSink = (message)=>logger.warn(message))=>({
11
+ queueUtilizationWarnThreshold: sloConfig?.queueUtilizationWarnThreshold,
12
+ queueDroppedWarnThreshold: sloConfig?.queueDroppedWarnThreshold,
13
+ alertCooldownMs: sloConfig?.alertCooldownMs,
14
+ onAlert: (alert)=>{
15
+ warnSink(`[telemetry.slo] ${alert.type} threshold=${alert.threshold} value=${alert.value} depth=${alert.queueDepth}/${alert.queueCapacity} dropped=${alert.totalDropped}`);
16
+ }
17
+ });
18
+ const injectTelemetryPlugin = ()=>({
19
+ name: '@modern-js/inject-telemetry',
20
+ setup (api) {
21
+ const serverConfig = api.getServerConfig();
22
+ const telemetryConfig = serverConfig?.server?.telemetry;
23
+ if (!telemetryConfig) return;
24
+ if (true !== telemetryConfig.enabled && !hasEnabledTelemetryExporters(telemetryConfig)) return;
25
+ const { middlewares, metaName, appDirectory } = api.getServerContext();
26
+ const serviceName = telemetryConfig.service || metaName || 'modern-js';
27
+ const moduleName = telemetryConfig.module || 'server';
28
+ const environmentName = telemetryConfig.environment || parseServerRuntimeExtensionsEnv().environmentName;
29
+ const registry = new TelemetryRegistry({
30
+ service: serviceName,
31
+ module: moduleName,
32
+ environment: environmentName,
33
+ samplingRate: telemetryConfig.samplingRate,
34
+ flushIntervalMs: telemetryConfig.flushIntervalMs,
35
+ maxBatchSize: telemetryConfig.maxBatchSize,
36
+ maxQueueSize: telemetryConfig.maxQueueSize,
37
+ redactionKeys: telemetryConfig.redactionKeys,
38
+ slo: resolveTelemetrySloOptions(telemetryConfig.slo)
39
+ });
40
+ const { canaryOrchestrator, gateSnapshotStorePromise, runtimeFallbackSignalConfig, runtimeStatusAuthConfig } = setupTelemetryCanary({
41
+ registry,
42
+ appDirectory,
43
+ canaryConfig: telemetryConfig.canary
44
+ });
45
+ if (runtimeFallbackSignalConfig) middlewares.push(createRuntimeFallbackSignalMiddleware(runtimeFallbackSignalConfig));
46
+ middlewares.push(createRuntimeStatusMiddleware({
47
+ registry,
48
+ canaryOrchestrator,
49
+ runtimeFallbackSignalConfig,
50
+ runtimeStatusAuthConfig
51
+ }));
52
+ middlewares.push({
53
+ name: 'inject-telemetry',
54
+ handler: async (c, next)=>{
55
+ const monitors = c.get('monitors');
56
+ if (monitors) {
57
+ const traceContext = parseTraceparent(c.req.header('traceparent'));
58
+ const monitor = (event)=>{
59
+ registry.enqueue(toTelemetryEnvelope(event, {
60
+ service: serviceName,
61
+ module: moduleName,
62
+ environment: environmentName,
63
+ traceId: traceContext?.traceId,
64
+ spanId: traceContext?.spanId,
65
+ attributes: {
66
+ requestMethod: c.req.method,
67
+ requestPath: c.req.path
68
+ }
69
+ }));
70
+ };
71
+ monitors.push(monitor);
72
+ }
73
+ await next();
74
+ }
75
+ });
76
+ registerTelemetryLifecycle({
77
+ api,
78
+ registry,
79
+ telemetryConfig,
80
+ canaryConfig: telemetryConfig.canary,
81
+ canaryOrchestrator,
82
+ gateSnapshotStorePromise,
83
+ appDirectory
84
+ });
85
+ }
86
+ });
87
+ export { DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_STATUS_ENDPOINT, createRuntimeFallbackSignalRuntimeState, createRuntimeSignalError, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, getRuntimeSignalErrorStatusCode, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, parseRuntimeFallbackSignalPayloadFromRawBody, resolveRuntimeFallbackSignalEndpoint } from "../runtimeFallbackSignal.mjs";
88
+ export { TelemetryCanaryOrchestrator, TelemetryRegistry, TelemetryStartupHealthError, createOtlpTelemetryExporter, createTelemetryAwareMetrics, createVictoriaMetricsTelemetryExporter, hasEnabledTelemetryExporters, injectTelemetryPlugin, resolveTelemetrySloOptions };
@@ -0,0 +1,259 @@
1
+ import "node:module";
2
+ import { buildDroppedEnvelope, buildQueueDepthEnvelope, buildQueueUtilizationEnvelope, buildStartupProbeEnvelope, clamp, redactObject } from "./envelope.mjs";
3
+ import { TelemetryStartupHealthError } from "./registryTypes.mjs";
4
+ class TelemetryRegistry {
5
+ async register(exporter) {
6
+ this.exporters.push(exporter);
7
+ this.exporterHealth.set(exporter.name, {
8
+ name: exporter.name,
9
+ healthy: true,
10
+ failures: 0
11
+ });
12
+ if (exporter.init) try {
13
+ await exporter.init({
14
+ service: this.service,
15
+ module: this.module,
16
+ environment: this.environment
17
+ });
18
+ this.markExporterHealthy(exporter.name);
19
+ } catch (error) {
20
+ this.markExporterFailure(exporter.name, error);
21
+ throw error;
22
+ }
23
+ else this.markExporterHealthy(exporter.name);
24
+ }
25
+ getOrCreateExporterHealth(name) {
26
+ const existing = this.exporterHealth.get(name);
27
+ if (existing) return existing;
28
+ const next = {
29
+ name,
30
+ healthy: true,
31
+ failures: 0
32
+ };
33
+ this.exporterHealth.set(name, next);
34
+ return next;
35
+ }
36
+ markExporterHealthy(name) {
37
+ const status = this.getOrCreateExporterHealth(name);
38
+ status.healthy = true;
39
+ status.lastSuccessAt = Date.now();
40
+ status.lastError = void 0;
41
+ }
42
+ markExporterFailure(name, error) {
43
+ const status = this.getOrCreateExporterHealth(name);
44
+ status.healthy = false;
45
+ status.failures += 1;
46
+ status.lastFailureAt = Date.now();
47
+ status.lastError = error instanceof Error ? error.message : String(error);
48
+ }
49
+ maybeEmitSloAlert(type, value, threshold) {
50
+ if (!this.onSloAlert || value < threshold) return;
51
+ const now = Date.now();
52
+ const lastTimestamp = this.lastSloAlertAt.get(type) ?? 0;
53
+ if (now - lastTimestamp < this.alertCooldownMs) return;
54
+ this.lastSloAlertAt.set(type, now);
55
+ const queueDepth = this.queue.length;
56
+ try {
57
+ this.onSloAlert({
58
+ timestamp: now,
59
+ service: this.service,
60
+ module: this.module,
61
+ environment: this.environment,
62
+ type,
63
+ value,
64
+ threshold,
65
+ queueDepth,
66
+ queueCapacity: this.maxQueueSize,
67
+ queueUtilization: queueDepth / this.maxQueueSize,
68
+ totalDropped: this.totalDroppedCount
69
+ });
70
+ } catch (_error) {}
71
+ }
72
+ enqueue(envelope) {
73
+ if (this.samplingRate < 1 && Math.random() > this.samplingRate) return;
74
+ const redactedEnvelope = this.redactionKeys.size > 0 ? {
75
+ ...envelope,
76
+ attributes: redactObject(envelope.attributes, this.redactionKeys)
77
+ } : envelope;
78
+ if (this.queue.length >= this.maxQueueSize) {
79
+ this.queue.shift();
80
+ this.droppedCount += 1;
81
+ this.totalDroppedCount += 1;
82
+ this.maybeEmitSloAlert('queue.drop', this.droppedCount, this.queueDroppedWarnThreshold);
83
+ }
84
+ this.queue.push(redactedEnvelope);
85
+ this.maybeEmitSloAlert('queue.utilization', this.queue.length / this.maxQueueSize, this.queueUtilizationWarnThreshold);
86
+ if (this.queue.length >= this.maxBatchSize) this.flush();
87
+ }
88
+ enqueueMetric(input) {
89
+ this.enqueue({
90
+ ...this.baseEnvelope(),
91
+ signalType: 'metric',
92
+ name: input.name,
93
+ value: input.value,
94
+ unit: input.unit || 'count',
95
+ traceId: input.traceId,
96
+ spanId: input.spanId,
97
+ parentSpanId: input.parentSpanId,
98
+ tags: input.tags,
99
+ attributes: input.attributes
100
+ });
101
+ }
102
+ enqueueLog(input) {
103
+ this.enqueue({
104
+ ...this.baseEnvelope(),
105
+ signalType: 'log',
106
+ name: input.name,
107
+ level: input.level,
108
+ traceId: input.traceId,
109
+ spanId: input.spanId,
110
+ parentSpanId: input.parentSpanId,
111
+ tags: input.tags,
112
+ attributes: input.attributes,
113
+ error: input.error
114
+ });
115
+ }
116
+ enqueueTrace(input) {
117
+ this.enqueue({
118
+ ...this.baseEnvelope(),
119
+ signalType: 'trace',
120
+ name: input.name,
121
+ traceId: input.traceId,
122
+ spanId: input.spanId,
123
+ parentSpanId: input.parentSpanId,
124
+ tags: input.tags,
125
+ attributes: input.attributes
126
+ });
127
+ }
128
+ baseEnvelope() {
129
+ return {
130
+ timestamp: Date.now(),
131
+ service: this.service,
132
+ module: this.module,
133
+ environment: this.environment
134
+ };
135
+ }
136
+ async emitBatch(batch) {
137
+ const results = await Promise.allSettled(this.exporters.map(async (exporter)=>{
138
+ await exporter.emit(batch);
139
+ return exporter.name;
140
+ }));
141
+ for (const [index, result] of results.entries()){
142
+ const exporterName = this.exporters[index]?.name || `exporter-${index}`;
143
+ if ('rejected' === result.status) {
144
+ this.markExporterFailure(exporterName, result.reason);
145
+ continue;
146
+ }
147
+ this.markExporterHealthy(exporterName);
148
+ }
149
+ }
150
+ async startupHealthCheck(options) {
151
+ if (0 === this.exporters.length) return;
152
+ const probeBatch = [
153
+ buildStartupProbeEnvelope({
154
+ service: this.service,
155
+ module: this.module,
156
+ environment: this.environment,
157
+ maxQueueSize: this.maxQueueSize
158
+ })
159
+ ];
160
+ const failedExporters = [];
161
+ await Promise.all(this.exporters.map(async (exporter)=>{
162
+ try {
163
+ await exporter.emit(probeBatch);
164
+ this.markExporterHealthy(exporter.name);
165
+ } catch (error) {
166
+ this.markExporterFailure(exporter.name, error);
167
+ const status = this.exporterHealth.get(exporter.name);
168
+ if (status) failedExporters.push({
169
+ ...status
170
+ });
171
+ }
172
+ }));
173
+ if ((options?.failLoud ?? true) && failedExporters.length > 0) throw new TelemetryStartupHealthError(failedExporters);
174
+ }
175
+ getExporterHealth() {
176
+ return Array.from(this.exporterHealth.values()).map((item)=>({
177
+ ...item
178
+ }));
179
+ }
180
+ getQueueStats() {
181
+ return {
182
+ depth: this.queue.length,
183
+ capacity: this.maxQueueSize,
184
+ utilization: this.queue.length / this.maxQueueSize,
185
+ pendingDropped: this.droppedCount,
186
+ totalDropped: this.totalDroppedCount
187
+ };
188
+ }
189
+ async flushInternal() {
190
+ const queueDepthBeforeFlush = this.queue.length;
191
+ const envelopeContext = {
192
+ service: this.service,
193
+ module: this.module,
194
+ environment: this.environment,
195
+ maxQueueSize: this.maxQueueSize
196
+ };
197
+ if (queueDepthBeforeFlush > 0) {
198
+ this.queue.unshift(buildQueueUtilizationEnvelope(envelopeContext, queueDepthBeforeFlush));
199
+ this.queue.unshift(buildQueueDepthEnvelope(envelopeContext, queueDepthBeforeFlush));
200
+ }
201
+ if (this.droppedCount > 0) {
202
+ const droppedCount = this.droppedCount;
203
+ this.droppedCount = 0;
204
+ this.queue.unshift(buildDroppedEnvelope(envelopeContext, droppedCount));
205
+ }
206
+ if (0 === this.queue.length) return;
207
+ if (0 === this.exporters.length) {
208
+ this.queue.length = 0;
209
+ return;
210
+ }
211
+ while(this.queue.length > 0){
212
+ const batch = this.queue.splice(0, this.maxBatchSize);
213
+ await this.emitBatch(batch);
214
+ }
215
+ await Promise.allSettled(this.exporters.map(async (exporter)=>{
216
+ if (exporter.flush) await exporter.flush();
217
+ }));
218
+ }
219
+ flush() {
220
+ if (this.flushing) return this.flushing;
221
+ this.flushing = this.flushInternal().finally(()=>{
222
+ this.flushing = null;
223
+ });
224
+ return this.flushing;
225
+ }
226
+ async shutdown() {
227
+ if (this.flushTimer) clearInterval(this.flushTimer);
228
+ await this.flush();
229
+ await Promise.allSettled(this.exporters.map(async (exporter)=>{
230
+ if (exporter.shutdown) await exporter.shutdown();
231
+ }));
232
+ }
233
+ constructor(options){
234
+ this.exporters = [];
235
+ this.queue = [];
236
+ this.droppedCount = 0;
237
+ this.totalDroppedCount = 0;
238
+ this.flushing = null;
239
+ this.exporterHealth = new Map();
240
+ this.lastSloAlertAt = new Map();
241
+ this.service = options.service;
242
+ this.module = options.module;
243
+ this.environment = options.environment;
244
+ this.samplingRate = clamp(options.samplingRate ?? 1, 0, 1);
245
+ this.maxBatchSize = Math.max(1, options.maxBatchSize ?? 50);
246
+ this.maxQueueSize = Math.max(1, options.maxQueueSize ?? 1000);
247
+ this.flushIntervalMs = Math.max(50, options.flushIntervalMs ?? 1000);
248
+ this.redactionKeys = new Set(options.redactionKeys || []);
249
+ this.queueUtilizationWarnThreshold = clamp(options.slo?.queueUtilizationWarnThreshold ?? 0.8, 0, 1);
250
+ this.queueDroppedWarnThreshold = Math.max(1, options.slo?.queueDroppedWarnThreshold ?? 1);
251
+ this.alertCooldownMs = Math.max(0, options.slo?.alertCooldownMs ?? 60000);
252
+ this.onSloAlert = options.slo?.onAlert;
253
+ this.flushTimer = setInterval(()=>{
254
+ this.flush();
255
+ }, this.flushIntervalMs);
256
+ if ('function' == typeof this.flushTimer.unref) this.flushTimer.unref();
257
+ }
258
+ }
259
+ export { TelemetryRegistry };
@@ -0,0 +1,9 @@
1
+ import "node:module";
2
+ class TelemetryStartupHealthError extends Error {
3
+ constructor(failedExporters){
4
+ super(`Telemetry startup health check failed for exporters: ${failedExporters.map((item)=>item.name).join(', ')}`), this.code = 'TELEMETRY_EXPORTER_STARTUP_HEALTH_FAILED';
5
+ this.name = 'TelemetryStartupHealthError';
6
+ this.failedExporters = failedExporters;
7
+ }
8
+ }
9
+ export { TelemetryStartupHealthError };
@@ -0,0 +1,95 @@
1
+ import "node:module";
2
+ import { DEFAULT_RUNTIME_STATUS_ENDPOINT, enforceRuntimeFallbackSignalAuth, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, getRuntimeSignalErrorStatusCode, parseRuntimeFallbackSignalPayload, persistRuntimeFallbackContractGate } from "../runtimeFallbackSignal.mjs";
3
+ const getRequestRemoteAddress = (c)=>{
4
+ const env = c.env;
5
+ const remoteAddress = env?.node?.req?.socket?.remoteAddress;
6
+ return 'string' == typeof remoteAddress && remoteAddress.trim().length > 0 ? remoteAddress.trim() : void 0;
7
+ };
8
+ const createRuntimeFallbackSignalMiddleware = (signalConfig)=>({
9
+ name: 'telemetry-runtime-fallback-signal',
10
+ path: signalConfig.endpoint,
11
+ method: 'post',
12
+ order: 'pre',
13
+ handler: async (c)=>{
14
+ try {
15
+ enforceRuntimeFallbackSignalAuth(c, signalConfig);
16
+ const { payload } = await parseRuntimeFallbackSignalPayload(c, signalConfig.maxBodyBytes);
17
+ const trustResult = enforceRuntimeFallbackSignalTrustPolicy(payload, signalConfig, {
18
+ remoteAddress: getRequestRemoteAddress(c)
19
+ });
20
+ if (trustResult.deduped) return c.json({
21
+ ok: true,
22
+ deduped: true
23
+ }, 202);
24
+ await persistRuntimeFallbackContractGate(payload, signalConfig);
25
+ return c.json({
26
+ ok: true
27
+ }, 202);
28
+ } catch (error) {
29
+ const signalError = error;
30
+ const status = getRuntimeSignalErrorStatusCode(signalError);
31
+ return c.json({
32
+ ok: false,
33
+ error: signalError instanceof Error ? signalError.message : String(signalError)
34
+ }, status);
35
+ }
36
+ }
37
+ });
38
+ const createRuntimeStatusMiddleware = ({ registry, canaryOrchestrator, runtimeFallbackSignalConfig, runtimeStatusAuthConfig })=>({
39
+ name: 'telemetry-runtime-status',
40
+ path: DEFAULT_RUNTIME_STATUS_ENDPOINT,
41
+ method: 'get',
42
+ order: 'pre',
43
+ handler: async (c)=>{
44
+ try {
45
+ if (!runtimeStatusAuthConfig?.enabled) return c.json({
46
+ ok: true,
47
+ timestamp: Date.now()
48
+ });
49
+ enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeStatusAuthConfig.headerName), runtimeStatusAuthConfig);
50
+ return c.json({
51
+ ok: true,
52
+ timestamp: Date.now(),
53
+ telemetry: {
54
+ queueStats: registry.getQueueStats(),
55
+ exporterHealth: registry.getExporterHealth()
56
+ },
57
+ canary: canaryOrchestrator ? {
58
+ enabled: true,
59
+ ...canaryOrchestrator.getStatusSnapshot()
60
+ } : {
61
+ enabled: false
62
+ },
63
+ runtimeFallbackSignal: runtimeFallbackSignalConfig ? {
64
+ enabled: true,
65
+ endpoint: runtimeFallbackSignalConfig.endpoint,
66
+ gateName: runtimeFallbackSignalConfig.gateName,
67
+ failureHoldMs: runtimeFallbackSignalConfig.failureHoldMs,
68
+ maxBodyBytes: runtimeFallbackSignalConfig.maxBodyBytes,
69
+ auth: {
70
+ enabled: runtimeFallbackSignalConfig.auth.enabled,
71
+ headerName: runtimeFallbackSignalConfig.auth.headerName
72
+ },
73
+ trustPolicy: {
74
+ allowedApps: runtimeFallbackSignalConfig.trustPolicy.allowedApps,
75
+ allowedEntryOrigins: runtimeFallbackSignalConfig.trustPolicy.allowedEntryOrigins,
76
+ enforceRuntimeDigest: runtimeFallbackSignalConfig.trustPolicy.enforceRuntimeDigest,
77
+ expectedRuntimeDigestsCount: Object.keys(runtimeFallbackSignalConfig.trustPolicy.expectedRuntimeDigests).length,
78
+ maxSignalsPerWindow: runtimeFallbackSignalConfig.trustPolicy.maxSignalsPerWindow,
79
+ windowMs: runtimeFallbackSignalConfig.trustPolicy.windowMs,
80
+ dedupeWindowMs: runtimeFallbackSignalConfig.trustPolicy.dedupeWindowMs
81
+ }
82
+ } : {
83
+ enabled: false
84
+ }
85
+ });
86
+ } catch (error) {
87
+ const signalError = error;
88
+ return c.json({
89
+ ok: false,
90
+ error: signalError instanceof Error ? signalError.message : String(signalError)
91
+ }, getRuntimeSignalErrorStatusCode(signalError));
92
+ }
93
+ }
94
+ });
95
+ export { createRuntimeFallbackSignalMiddleware, createRuntimeStatusMiddleware };