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

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 +9 -9
  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,197 @@
1
+ import { parseTraceparent } from '@modern-js/create-request/server';
2
+ import type {
3
+ Context,
4
+ Next,
5
+ ServerEnv,
6
+ ServerPlugin,
7
+ ServerTelemetryUserConfig,
8
+ } from '@modern-js/server-core';
9
+ import type { CoreMonitor } from '@modern-js/types';
10
+ import { logger } from '@modern-js/utils';
11
+ import { parseServerRuntimeExtensionsEnv } from '../env';
12
+ import {
13
+ TelemetryRegistry,
14
+ type TelemetryRegistryOptions,
15
+ toTelemetryEnvelope,
16
+ } from '../telemetryCore';
17
+ import { setupTelemetryCanary } from './canarySetup';
18
+ import { registerTelemetryLifecycle } from './lifecycle';
19
+ import {
20
+ createRuntimeFallbackSignalMiddleware,
21
+ createRuntimeStatusMiddleware,
22
+ } from './runtimeEndpoints';
23
+
24
+ export {
25
+ createRuntimeFallbackSignalRuntimeState,
26
+ createRuntimeSignalError,
27
+ DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT,
28
+ DEFAULT_RUNTIME_STATUS_ENDPOINT,
29
+ enforceRuntimeFallbackSignalAuthToken,
30
+ enforceRuntimeFallbackSignalTrustPolicy,
31
+ getRuntimeSignalErrorStatusCode,
32
+ normalizeRequiredRuntimeFallbackSignalAuthConfig,
33
+ normalizeRuntimeFallbackSignalAuthConfig,
34
+ normalizeRuntimeFallbackTrustPolicy,
35
+ parseRuntimeFallbackSignalPayloadFromRawBody,
36
+ type RuntimeFallbackSignalAuthConfig,
37
+ type RuntimeFallbackSignalRuntimeState,
38
+ type RuntimeFallbackSignalSource,
39
+ type RuntimeFallbackSignalTrustContext,
40
+ type RuntimeFallbackSignalTrustPolicy,
41
+ type RuntimeSignalError,
42
+ type RuntimeSignalErrorCode,
43
+ resolveRuntimeFallbackSignalEndpoint,
44
+ } from '../runtimeFallbackSignal';
45
+ export {
46
+ createOtlpTelemetryExporter,
47
+ createTelemetryAwareMetrics,
48
+ createVictoriaMetricsTelemetryExporter,
49
+ type OtlpExporterOptions,
50
+ type TelemetryCanaryAction,
51
+ type TelemetryCanaryContractGateStatus,
52
+ type TelemetryCanaryDecision,
53
+ type TelemetryCanaryFailure,
54
+ type TelemetryCanaryFailureReason,
55
+ TelemetryCanaryOrchestrator,
56
+ type TelemetryCanaryOrchestratorOptions,
57
+ type TelemetryCanaryState,
58
+ type TelemetryCanaryStatusSnapshot,
59
+ type TelemetryEnvelope,
60
+ type TelemetryExporter,
61
+ type TelemetryExporterHealthStatus,
62
+ type TelemetryQueueStats,
63
+ TelemetryRegistry,
64
+ type TelemetryRegistryOptions,
65
+ type TelemetrySignalType,
66
+ type TelemetrySloAlert,
67
+ type TelemetrySloAlertType,
68
+ TelemetryStartupHealthError,
69
+ type VictoriaMetricsExporterOptions,
70
+ } from '../telemetryCore';
71
+
72
+ export const hasEnabledTelemetryExporters = (
73
+ config: ServerTelemetryUserConfig | undefined,
74
+ ) =>
75
+ Boolean(
76
+ config?.exporters?.otlp?.enabled ||
77
+ config?.exporters?.victoriaMetrics?.enabled,
78
+ );
79
+
80
+ /**
81
+ * Builds the registry SLO options from `server.telemetry.slo`, attaching a
82
+ * logger sink so threshold breaches surface as server warnings (parity with
83
+ * the pre-extraction prod-server harness).
84
+ */
85
+ export const resolveTelemetrySloOptions = (
86
+ sloConfig: ServerTelemetryUserConfig['slo'],
87
+ warnSink: (message: string) => void = message => logger.warn(message),
88
+ ): NonNullable<TelemetryRegistryOptions['slo']> => ({
89
+ queueUtilizationWarnThreshold: sloConfig?.queueUtilizationWarnThreshold,
90
+ queueDroppedWarnThreshold: sloConfig?.queueDroppedWarnThreshold,
91
+ alertCooldownMs: sloConfig?.alertCooldownMs,
92
+ onAlert: alert => {
93
+ warnSink(
94
+ `[telemetry.slo] ${alert.type} threshold=${alert.threshold} value=${alert.value} depth=${alert.queueDepth}/${alert.queueCapacity} dropped=${alert.totalDropped}`,
95
+ );
96
+ },
97
+ });
98
+
99
+ export const injectTelemetryPlugin = (): ServerPlugin => ({
100
+ name: '@modern-js/inject-telemetry',
101
+ setup(api) {
102
+ const serverConfig = api.getServerConfig();
103
+ const telemetryConfig = serverConfig?.server?.telemetry;
104
+ if (!telemetryConfig) {
105
+ return;
106
+ }
107
+
108
+ if (
109
+ telemetryConfig.enabled !== true &&
110
+ !hasEnabledTelemetryExporters(telemetryConfig)
111
+ ) {
112
+ return;
113
+ }
114
+
115
+ const { middlewares, metaName, appDirectory } = api.getServerContext();
116
+ const serviceName = telemetryConfig.service || metaName || 'modern-js';
117
+ const moduleName = telemetryConfig.module || 'server';
118
+ const environmentName =
119
+ telemetryConfig.environment ||
120
+ parseServerRuntimeExtensionsEnv().environmentName;
121
+
122
+ const registry = new TelemetryRegistry({
123
+ service: serviceName,
124
+ module: moduleName,
125
+ environment: environmentName,
126
+ samplingRate: telemetryConfig.samplingRate,
127
+ flushIntervalMs: telemetryConfig.flushIntervalMs,
128
+ maxBatchSize: telemetryConfig.maxBatchSize,
129
+ maxQueueSize: telemetryConfig.maxQueueSize,
130
+ redactionKeys: telemetryConfig.redactionKeys,
131
+ slo: resolveTelemetrySloOptions(telemetryConfig.slo),
132
+ });
133
+
134
+ const {
135
+ canaryOrchestrator,
136
+ gateSnapshotStorePromise,
137
+ runtimeFallbackSignalConfig,
138
+ runtimeStatusAuthConfig,
139
+ } = setupTelemetryCanary({
140
+ registry,
141
+ appDirectory,
142
+ canaryConfig: telemetryConfig.canary,
143
+ });
144
+
145
+ if (runtimeFallbackSignalConfig) {
146
+ middlewares.push(
147
+ createRuntimeFallbackSignalMiddleware(runtimeFallbackSignalConfig),
148
+ );
149
+ }
150
+ middlewares.push(
151
+ createRuntimeStatusMiddleware({
152
+ registry,
153
+ canaryOrchestrator,
154
+ runtimeFallbackSignalConfig,
155
+ runtimeStatusAuthConfig,
156
+ }),
157
+ );
158
+
159
+ middlewares.push({
160
+ name: 'inject-telemetry',
161
+ handler: async (c: Context<ServerEnv>, next: Next) => {
162
+ const monitors = c.get('monitors');
163
+ if (monitors) {
164
+ const traceContext = parseTraceparent(c.req.header('traceparent'));
165
+ const monitor: CoreMonitor = event => {
166
+ registry.enqueue(
167
+ toTelemetryEnvelope(event, {
168
+ service: serviceName,
169
+ module: moduleName,
170
+ environment: environmentName,
171
+ traceId: traceContext?.traceId,
172
+ spanId: traceContext?.spanId,
173
+ attributes: {
174
+ requestMethod: c.req.method,
175
+ requestPath: c.req.path,
176
+ },
177
+ }),
178
+ );
179
+ };
180
+ monitors.push(monitor);
181
+ }
182
+
183
+ await next();
184
+ },
185
+ });
186
+
187
+ registerTelemetryLifecycle({
188
+ api,
189
+ registry,
190
+ telemetryConfig,
191
+ canaryConfig: telemetryConfig.canary,
192
+ canaryOrchestrator,
193
+ gateSnapshotStorePromise,
194
+ appDirectory,
195
+ });
196
+ },
197
+ });
@@ -0,0 +1,424 @@
1
+ import {
2
+ buildDroppedEnvelope,
3
+ buildQueueDepthEnvelope,
4
+ buildQueueUtilizationEnvelope,
5
+ buildStartupProbeEnvelope,
6
+ clamp,
7
+ redactObject,
8
+ type TelemetryEnvelope,
9
+ type TelemetryEnvelopeBuilderContext,
10
+ type TelemetryExporter,
11
+ } from './envelope';
12
+ import {
13
+ type TelemetryExporterHealthStatus,
14
+ type TelemetryQueueStats,
15
+ type TelemetryRegistryOptions,
16
+ type TelemetrySloAlert,
17
+ type TelemetrySloAlertType,
18
+ TelemetryStartupHealthError,
19
+ } from './registryTypes';
20
+
21
+ export class TelemetryRegistry {
22
+ private readonly exporters: TelemetryExporter[] = [];
23
+ private readonly queue: TelemetryEnvelope[] = [];
24
+ private readonly redactionKeys: Set<string>;
25
+ private readonly service: string;
26
+ private readonly module: string;
27
+ private readonly environment: string;
28
+ private readonly samplingRate: number;
29
+ private readonly maxBatchSize: number;
30
+ private readonly maxQueueSize: number;
31
+ private readonly flushIntervalMs: number;
32
+ private readonly flushTimer?: ReturnType<typeof setInterval>;
33
+ private droppedCount = 0;
34
+ private totalDroppedCount = 0;
35
+ private flushing: Promise<void> | null = null;
36
+ private readonly exporterHealth = new Map<
37
+ string,
38
+ TelemetryExporterHealthStatus
39
+ >();
40
+ private readonly queueUtilizationWarnThreshold: number;
41
+ private readonly queueDroppedWarnThreshold: number;
42
+ private readonly alertCooldownMs: number;
43
+ private readonly onSloAlert?: (alert: TelemetrySloAlert) => void;
44
+ private readonly lastSloAlertAt = new Map<TelemetrySloAlertType, number>();
45
+
46
+ constructor(options: TelemetryRegistryOptions) {
47
+ this.service = options.service;
48
+ this.module = options.module;
49
+ this.environment = options.environment;
50
+ this.samplingRate = clamp(options.samplingRate ?? 1, 0, 1);
51
+ this.maxBatchSize = Math.max(1, options.maxBatchSize ?? 50);
52
+ this.maxQueueSize = Math.max(1, options.maxQueueSize ?? 1000);
53
+ this.flushIntervalMs = Math.max(50, options.flushIntervalMs ?? 1000);
54
+ this.redactionKeys = new Set(options.redactionKeys || []);
55
+ this.queueUtilizationWarnThreshold = clamp(
56
+ options.slo?.queueUtilizationWarnThreshold ?? 0.8,
57
+ 0,
58
+ 1,
59
+ );
60
+ this.queueDroppedWarnThreshold = Math.max(
61
+ 1,
62
+ options.slo?.queueDroppedWarnThreshold ?? 1,
63
+ );
64
+ this.alertCooldownMs = Math.max(0, options.slo?.alertCooldownMs ?? 60_000);
65
+ this.onSloAlert = options.slo?.onAlert;
66
+
67
+ this.flushTimer = setInterval(() => {
68
+ void this.flush();
69
+ }, this.flushIntervalMs);
70
+ if (typeof (this.flushTimer as NodeJS.Timeout).unref === 'function') {
71
+ (this.flushTimer as NodeJS.Timeout).unref();
72
+ }
73
+ }
74
+
75
+ async register(exporter: TelemetryExporter) {
76
+ this.exporters.push(exporter);
77
+ this.exporterHealth.set(exporter.name, {
78
+ name: exporter.name,
79
+ healthy: true,
80
+ failures: 0,
81
+ });
82
+ if (exporter.init) {
83
+ try {
84
+ await exporter.init({
85
+ service: this.service,
86
+ module: this.module,
87
+ environment: this.environment,
88
+ });
89
+ this.markExporterHealthy(exporter.name);
90
+ } catch (error) {
91
+ this.markExporterFailure(exporter.name, error);
92
+ throw error;
93
+ }
94
+ } else {
95
+ this.markExporterHealthy(exporter.name);
96
+ }
97
+ }
98
+
99
+ private getOrCreateExporterHealth(name: string) {
100
+ const existing = this.exporterHealth.get(name);
101
+ if (existing) {
102
+ return existing;
103
+ }
104
+
105
+ const next: TelemetryExporterHealthStatus = {
106
+ name,
107
+ healthy: true,
108
+ failures: 0,
109
+ };
110
+ this.exporterHealth.set(name, next);
111
+ return next;
112
+ }
113
+
114
+ private markExporterHealthy(name: string) {
115
+ const status = this.getOrCreateExporterHealth(name);
116
+ status.healthy = true;
117
+ status.lastSuccessAt = Date.now();
118
+ status.lastError = undefined;
119
+ }
120
+
121
+ private markExporterFailure(name: string, error: unknown) {
122
+ const status = this.getOrCreateExporterHealth(name);
123
+ status.healthy = false;
124
+ status.failures += 1;
125
+ status.lastFailureAt = Date.now();
126
+ status.lastError = error instanceof Error ? error.message : String(error);
127
+ }
128
+
129
+ private maybeEmitSloAlert(
130
+ type: TelemetrySloAlertType,
131
+ value: number,
132
+ threshold: number,
133
+ ) {
134
+ if (!this.onSloAlert || value < threshold) {
135
+ return;
136
+ }
137
+
138
+ const now = Date.now();
139
+ const lastTimestamp = this.lastSloAlertAt.get(type) ?? 0;
140
+ if (now - lastTimestamp < this.alertCooldownMs) {
141
+ return;
142
+ }
143
+
144
+ this.lastSloAlertAt.set(type, now);
145
+ const queueDepth = this.queue.length;
146
+
147
+ try {
148
+ this.onSloAlert({
149
+ timestamp: now,
150
+ service: this.service,
151
+ module: this.module,
152
+ environment: this.environment,
153
+ type,
154
+ value,
155
+ threshold,
156
+ queueDepth,
157
+ queueCapacity: this.maxQueueSize,
158
+ queueUtilization: queueDepth / this.maxQueueSize,
159
+ totalDropped: this.totalDroppedCount,
160
+ });
161
+ } catch (_error) {
162
+ // SLO alert hooks must never crash telemetry pipeline.
163
+ }
164
+ }
165
+
166
+ enqueue(envelope: TelemetryEnvelope) {
167
+ if (this.samplingRate < 1 && Math.random() > this.samplingRate) {
168
+ return;
169
+ }
170
+
171
+ const redactedEnvelope =
172
+ this.redactionKeys.size > 0
173
+ ? ({
174
+ ...envelope,
175
+ attributes: redactObject(envelope.attributes, this.redactionKeys),
176
+ } as TelemetryEnvelope)
177
+ : envelope;
178
+
179
+ if (this.queue.length >= this.maxQueueSize) {
180
+ this.queue.shift();
181
+ this.droppedCount += 1;
182
+ this.totalDroppedCount += 1;
183
+ this.maybeEmitSloAlert(
184
+ 'queue.drop',
185
+ this.droppedCount,
186
+ this.queueDroppedWarnThreshold,
187
+ );
188
+ }
189
+
190
+ this.queue.push(redactedEnvelope);
191
+ this.maybeEmitSloAlert(
192
+ 'queue.utilization',
193
+ this.queue.length / this.maxQueueSize,
194
+ this.queueUtilizationWarnThreshold,
195
+ );
196
+
197
+ if (this.queue.length >= this.maxBatchSize) {
198
+ void this.flush();
199
+ }
200
+ }
201
+
202
+ enqueueMetric(input: {
203
+ name: string;
204
+ value: number;
205
+ unit?: string;
206
+ traceId?: string;
207
+ spanId?: string;
208
+ parentSpanId?: string;
209
+ tags?: Record<string, string>;
210
+ attributes?: Record<string, unknown>;
211
+ }) {
212
+ this.enqueue({
213
+ ...this.baseEnvelope(),
214
+ signalType: 'metric',
215
+ name: input.name,
216
+ value: input.value,
217
+ unit: input.unit || 'count',
218
+ traceId: input.traceId,
219
+ spanId: input.spanId,
220
+ parentSpanId: input.parentSpanId,
221
+ tags: input.tags,
222
+ attributes: input.attributes,
223
+ });
224
+ }
225
+
226
+ enqueueLog(input: {
227
+ name: string;
228
+ level: string;
229
+ traceId?: string;
230
+ spanId?: string;
231
+ parentSpanId?: string;
232
+ tags?: Record<string, string>;
233
+ attributes?: Record<string, unknown>;
234
+ error?: TelemetryEnvelope['error'];
235
+ }) {
236
+ this.enqueue({
237
+ ...this.baseEnvelope(),
238
+ signalType: 'log',
239
+ name: input.name,
240
+ level: input.level,
241
+ traceId: input.traceId,
242
+ spanId: input.spanId,
243
+ parentSpanId: input.parentSpanId,
244
+ tags: input.tags,
245
+ attributes: input.attributes,
246
+ error: input.error,
247
+ });
248
+ }
249
+
250
+ enqueueTrace(input: {
251
+ name: string;
252
+ traceId?: string;
253
+ spanId?: string;
254
+ parentSpanId?: string;
255
+ tags?: Record<string, string>;
256
+ attributes?: Record<string, unknown>;
257
+ }) {
258
+ this.enqueue({
259
+ ...this.baseEnvelope(),
260
+ signalType: 'trace',
261
+ name: input.name,
262
+ traceId: input.traceId,
263
+ spanId: input.spanId,
264
+ parentSpanId: input.parentSpanId,
265
+ tags: input.tags,
266
+ attributes: input.attributes,
267
+ });
268
+ }
269
+
270
+ private baseEnvelope(): Pick<
271
+ TelemetryEnvelope,
272
+ 'timestamp' | 'service' | 'module' | 'environment'
273
+ > {
274
+ return {
275
+ timestamp: Date.now(),
276
+ service: this.service,
277
+ module: this.module,
278
+ environment: this.environment,
279
+ };
280
+ }
281
+
282
+ private async emitBatch(batch: TelemetryEnvelope[]) {
283
+ const results = await Promise.allSettled(
284
+ this.exporters.map(async exporter => {
285
+ await exporter.emit(batch);
286
+ return exporter.name;
287
+ }),
288
+ );
289
+
290
+ for (const [index, result] of results.entries()) {
291
+ const exporterName = this.exporters[index]?.name || `exporter-${index}`;
292
+ if (result.status === 'rejected') {
293
+ this.markExporterFailure(exporterName, result.reason);
294
+ continue;
295
+ }
296
+
297
+ this.markExporterHealthy(exporterName);
298
+ }
299
+ }
300
+
301
+ async startupHealthCheck(options?: { failLoud?: boolean }) {
302
+ if (this.exporters.length === 0) {
303
+ return;
304
+ }
305
+
306
+ const probeBatch = [
307
+ buildStartupProbeEnvelope({
308
+ service: this.service,
309
+ module: this.module,
310
+ environment: this.environment,
311
+ maxQueueSize: this.maxQueueSize,
312
+ }),
313
+ ];
314
+ const failedExporters: TelemetryExporterHealthStatus[] = [];
315
+
316
+ await Promise.all(
317
+ this.exporters.map(async exporter => {
318
+ try {
319
+ await exporter.emit(probeBatch);
320
+ this.markExporterHealthy(exporter.name);
321
+ } catch (error) {
322
+ this.markExporterFailure(exporter.name, error);
323
+ const status = this.exporterHealth.get(exporter.name);
324
+ if (status) {
325
+ failedExporters.push({ ...status });
326
+ }
327
+ }
328
+ }),
329
+ );
330
+
331
+ if ((options?.failLoud ?? true) && failedExporters.length > 0) {
332
+ throw new TelemetryStartupHealthError(failedExporters);
333
+ }
334
+ }
335
+
336
+ getExporterHealth(): TelemetryExporterHealthStatus[] {
337
+ return Array.from(this.exporterHealth.values()).map(item => ({
338
+ ...item,
339
+ }));
340
+ }
341
+
342
+ getQueueStats(): TelemetryQueueStats {
343
+ return {
344
+ depth: this.queue.length,
345
+ capacity: this.maxQueueSize,
346
+ utilization: this.queue.length / this.maxQueueSize,
347
+ pendingDropped: this.droppedCount,
348
+ totalDropped: this.totalDroppedCount,
349
+ };
350
+ }
351
+
352
+ private async flushInternal() {
353
+ const queueDepthBeforeFlush = this.queue.length;
354
+ const envelopeContext: TelemetryEnvelopeBuilderContext = {
355
+ service: this.service,
356
+ module: this.module,
357
+ environment: this.environment,
358
+ maxQueueSize: this.maxQueueSize,
359
+ };
360
+ if (queueDepthBeforeFlush > 0) {
361
+ this.queue.unshift(
362
+ buildQueueUtilizationEnvelope(envelopeContext, queueDepthBeforeFlush),
363
+ );
364
+ this.queue.unshift(
365
+ buildQueueDepthEnvelope(envelopeContext, queueDepthBeforeFlush),
366
+ );
367
+ }
368
+
369
+ if (this.droppedCount > 0) {
370
+ const droppedCount = this.droppedCount;
371
+ this.droppedCount = 0;
372
+ this.queue.unshift(buildDroppedEnvelope(envelopeContext, droppedCount));
373
+ }
374
+
375
+ if (this.queue.length === 0) {
376
+ return;
377
+ }
378
+
379
+ if (this.exporters.length === 0) {
380
+ this.queue.length = 0;
381
+ return;
382
+ }
383
+
384
+ while (this.queue.length > 0) {
385
+ const batch = this.queue.splice(0, this.maxBatchSize);
386
+ await this.emitBatch(batch);
387
+ }
388
+
389
+ await Promise.allSettled(
390
+ this.exporters.map(async exporter => {
391
+ if (exporter.flush) {
392
+ await exporter.flush();
393
+ }
394
+ }),
395
+ );
396
+ }
397
+
398
+ flush() {
399
+ if (this.flushing) {
400
+ return this.flushing;
401
+ }
402
+
403
+ this.flushing = this.flushInternal().finally(() => {
404
+ this.flushing = null;
405
+ });
406
+
407
+ return this.flushing;
408
+ }
409
+
410
+ async shutdown() {
411
+ if (this.flushTimer) {
412
+ clearInterval(this.flushTimer);
413
+ }
414
+
415
+ await this.flush();
416
+ await Promise.allSettled(
417
+ this.exporters.map(async exporter => {
418
+ if (exporter.shutdown) {
419
+ await exporter.shutdown();
420
+ }
421
+ }),
422
+ );
423
+ }
424
+ }
@@ -0,0 +1,63 @@
1
+ export interface TelemetryRegistryOptions {
2
+ service: string;
3
+ module: string;
4
+ environment: string;
5
+ samplingRate?: number;
6
+ flushIntervalMs?: number;
7
+ maxBatchSize?: number;
8
+ maxQueueSize?: number;
9
+ redactionKeys?: string[];
10
+ slo?: {
11
+ queueUtilizationWarnThreshold?: number;
12
+ queueDroppedWarnThreshold?: number;
13
+ alertCooldownMs?: number;
14
+ onAlert?: (alert: TelemetrySloAlert) => void;
15
+ };
16
+ }
17
+
18
+ export type TelemetrySloAlertType = 'queue.utilization' | 'queue.drop';
19
+
20
+ export interface TelemetrySloAlert {
21
+ timestamp: number;
22
+ service: string;
23
+ module: string;
24
+ environment: string;
25
+ type: TelemetrySloAlertType;
26
+ value: number;
27
+ threshold: number;
28
+ queueDepth: number;
29
+ queueCapacity: number;
30
+ queueUtilization: number;
31
+ totalDropped: number;
32
+ }
33
+
34
+ export interface TelemetryQueueStats {
35
+ depth: number;
36
+ capacity: number;
37
+ utilization: number;
38
+ pendingDropped: number;
39
+ totalDropped: number;
40
+ }
41
+
42
+ export interface TelemetryExporterHealthStatus {
43
+ name: string;
44
+ healthy: boolean;
45
+ failures: number;
46
+ lastError?: string;
47
+ lastSuccessAt?: number;
48
+ lastFailureAt?: number;
49
+ }
50
+
51
+ export class TelemetryStartupHealthError extends Error {
52
+ readonly code = 'TELEMETRY_EXPORTER_STARTUP_HEALTH_FAILED';
53
+
54
+ readonly failedExporters: TelemetryExporterHealthStatus[];
55
+
56
+ constructor(failedExporters: TelemetryExporterHealthStatus[]) {
57
+ super(
58
+ `Telemetry startup health check failed for exporters: ${failedExporters.map(item => item.name).join(', ')}`,
59
+ );
60
+ this.name = 'TelemetryStartupHealthError';
61
+ this.failedExporters = failedExporters;
62
+ }
63
+ }