@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.30 → 3.5.0-ultramodern.32

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 (207) hide show
  1. package/dist/cjs/contract-gate-snapshot-store/file-store.js +102 -0
  2. package/dist/cjs/contract-gate-snapshot-store/http-store.js +142 -0
  3. package/dist/cjs/contract-gate-snapshot-store/index.js +58 -0
  4. package/dist/cjs/contract-gate-snapshot-store/resolve.js +122 -0
  5. package/dist/cjs/contract-gate-snapshot-store/types.js +44 -0
  6. package/dist/cjs/contractGateAutopilot.js +27 -6
  7. package/dist/cjs/index.js +13 -13
  8. package/dist/cjs/module-federation-css/collector.js +79 -0
  9. package/dist/cjs/module-federation-css/index.js +55 -0
  10. package/dist/cjs/module-federation-css/manifest.js +144 -0
  11. package/dist/cjs/module-federation-css/plugin.js +71 -0
  12. package/dist/cjs/module-federation-css/remote.js +133 -0
  13. package/dist/cjs/runtime-fallback-signal/auth.js +87 -0
  14. package/dist/cjs/runtime-fallback-signal/constants.js +72 -0
  15. package/dist/cjs/runtime-fallback-signal/contract-gate.js +64 -0
  16. package/dist/cjs/runtime-fallback-signal/endpoint.js +50 -0
  17. package/dist/cjs/runtime-fallback-signal/errors.js +44 -0
  18. package/dist/cjs/runtime-fallback-signal/index.js +99 -0
  19. package/dist/cjs/runtime-fallback-signal/payload.js +72 -0
  20. package/dist/cjs/runtime-fallback-signal/source.js +66 -0
  21. package/dist/cjs/runtime-fallback-signal/state.js +57 -0
  22. package/dist/cjs/runtime-fallback-signal/status.js +47 -0
  23. package/dist/cjs/runtime-fallback-signal/trust-policy.js +108 -0
  24. package/dist/cjs/runtime-fallback-signal/types.js +18 -0
  25. package/dist/cjs/runtimeFallbackSignal.js +32 -281
  26. package/dist/cjs/telemetry/canary.js +180 -0
  27. package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
  28. package/dist/cjs/telemetry/canarySetup.js +107 -0
  29. package/dist/cjs/telemetry/envelope.js +148 -0
  30. package/dist/cjs/telemetry/exporters.js +148 -0
  31. package/dist/cjs/telemetry/lifecycle.js +98 -0
  32. package/dist/cjs/telemetry/metrics.js +115 -0
  33. package/dist/cjs/telemetry/plugin.js +185 -0
  34. package/dist/cjs/telemetry/registry.js +348 -0
  35. package/dist/cjs/telemetry/registryTypes.js +46 -0
  36. package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
  37. package/dist/cjs/telemetry.js +32 -343
  38. package/dist/cjs/telemetryCore.js +14 -767
  39. package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
  40. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
  41. package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
  42. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +68 -0
  43. package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
  44. package/dist/esm/contractGateAutopilot.mjs +26 -5
  45. package/dist/esm/index.mjs +2 -2
  46. package/dist/esm/module-federation-css/collector.mjs +38 -0
  47. package/dist/esm/module-federation-css/index.mjs +4 -0
  48. package/dist/esm/module-federation-css/manifest.mjs +69 -0
  49. package/dist/esm/module-federation-css/plugin.mjs +33 -0
  50. package/dist/esm/module-federation-css/remote.mjs +92 -0
  51. package/dist/esm/runtime-fallback-signal/auth.mjs +40 -0
  52. package/dist/esm/runtime-fallback-signal/constants.mjs +10 -0
  53. package/dist/esm/runtime-fallback-signal/contract-gate.mjs +26 -0
  54. package/dist/esm/runtime-fallback-signal/endpoint.mjs +12 -0
  55. package/dist/esm/runtime-fallback-signal/errors.mjs +6 -0
  56. package/dist/esm/runtime-fallback-signal/index.mjs +9 -0
  57. package/dist/esm/runtime-fallback-signal/payload.mjs +31 -0
  58. package/dist/esm/runtime-fallback-signal/source.mjs +22 -0
  59. package/dist/esm/runtime-fallback-signal/state.mjs +16 -0
  60. package/dist/esm/runtime-fallback-signal/status.mjs +9 -0
  61. package/dist/esm/runtime-fallback-signal/trust-policy.mjs +67 -0
  62. package/dist/esm/runtime-fallback-signal/types.mjs +0 -0
  63. package/dist/esm/runtimeFallbackSignal.mjs +1 -222
  64. package/dist/esm/telemetry/canary.mjs +142 -0
  65. package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
  66. package/dist/esm/telemetry/canarySetup.mjs +69 -0
  67. package/dist/esm/telemetry/envelope.mjs +101 -0
  68. package/dist/esm/telemetry/exporters.mjs +104 -0
  69. package/dist/esm/telemetry/lifecycle.mjs +60 -0
  70. package/dist/esm/telemetry/metrics.mjs +77 -0
  71. package/dist/esm/telemetry/plugin.mjs +87 -0
  72. package/dist/esm/telemetry/registry.mjs +310 -0
  73. package/dist/esm/telemetry/registryTypes.mjs +8 -0
  74. package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
  75. package/dist/esm/telemetry.mjs +1 -275
  76. package/dist/esm/telemetryCore.mjs +6 -759
  77. package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
  78. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
  79. package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
  80. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +70 -0
  81. package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
  82. package/dist/esm-node/contractGateAutopilot.mjs +26 -5
  83. package/dist/esm-node/index.mjs +2 -2
  84. package/dist/esm-node/module-federation-css/collector.mjs +39 -0
  85. package/dist/esm-node/module-federation-css/index.mjs +5 -0
  86. package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
  87. package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
  88. package/dist/esm-node/module-federation-css/remote.mjs +93 -0
  89. package/dist/esm-node/runtime-fallback-signal/auth.mjs +41 -0
  90. package/dist/esm-node/runtime-fallback-signal/constants.mjs +11 -0
  91. package/dist/esm-node/runtime-fallback-signal/contract-gate.mjs +27 -0
  92. package/dist/esm-node/runtime-fallback-signal/endpoint.mjs +13 -0
  93. package/dist/esm-node/runtime-fallback-signal/errors.mjs +7 -0
  94. package/dist/esm-node/runtime-fallback-signal/index.mjs +10 -0
  95. package/dist/esm-node/runtime-fallback-signal/payload.mjs +32 -0
  96. package/dist/esm-node/runtime-fallback-signal/source.mjs +23 -0
  97. package/dist/esm-node/runtime-fallback-signal/state.mjs +17 -0
  98. package/dist/esm-node/runtime-fallback-signal/status.mjs +10 -0
  99. package/dist/esm-node/runtime-fallback-signal/trust-policy.mjs +68 -0
  100. package/dist/esm-node/runtime-fallback-signal/types.mjs +1 -0
  101. package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
  102. package/dist/esm-node/telemetry/canary.mjs +143 -0
  103. package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
  104. package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
  105. package/dist/esm-node/telemetry/envelope.mjs +102 -0
  106. package/dist/esm-node/telemetry/exporters.mjs +105 -0
  107. package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
  108. package/dist/esm-node/telemetry/metrics.mjs +78 -0
  109. package/dist/esm-node/telemetry/plugin.mjs +88 -0
  110. package/dist/esm-node/telemetry/registry.mjs +311 -0
  111. package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
  112. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
  113. package/dist/esm-node/telemetry.mjs +1 -275
  114. package/dist/esm-node/telemetryCore.mjs +6 -759
  115. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
  116. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +11 -0
  117. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
  118. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
  119. package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
  120. package/dist/types/contractGateAutopilot.d.ts +4 -2
  121. package/dist/types/index.d.ts +2 -2
  122. package/dist/types/module-federation-css/collector.d.ts +25 -0
  123. package/dist/types/module-federation-css/index.d.ts +8 -0
  124. package/dist/types/module-federation-css/manifest.d.ts +33 -0
  125. package/dist/types/module-federation-css/plugin.d.ts +23 -0
  126. package/dist/types/module-federation-css/remote.d.ts +20 -0
  127. package/dist/types/runtime-fallback-signal/auth.d.ts +18 -0
  128. package/dist/types/runtime-fallback-signal/constants.d.ts +9 -0
  129. package/dist/types/runtime-fallback-signal/contract-gate.d.ts +2 -0
  130. package/dist/types/runtime-fallback-signal/endpoint.d.ts +1 -0
  131. package/dist/types/runtime-fallback-signal/errors.d.ts +2 -0
  132. package/dist/types/runtime-fallback-signal/index.d.ts +10 -0
  133. package/dist/types/runtime-fallback-signal/payload.d.ts +6 -0
  134. package/dist/types/runtime-fallback-signal/source.d.ts +3 -0
  135. package/dist/types/runtime-fallback-signal/state.d.ts +3 -0
  136. package/dist/types/runtime-fallback-signal/status.d.ts +2 -0
  137. package/dist/types/runtime-fallback-signal/trust-policy.d.ts +13 -0
  138. package/dist/types/runtime-fallback-signal/types.d.ts +50 -0
  139. package/dist/types/runtimeFallbackSignal.d.ts +1 -94
  140. package/dist/types/telemetry/canary.d.ts +85 -0
  141. package/dist/types/telemetry/canaryEvaluation.d.ts +19 -0
  142. package/dist/types/telemetry/canarySetup.d.ts +17 -0
  143. package/dist/types/telemetry/envelope.d.ts +45 -0
  144. package/dist/types/telemetry/exporters.d.ts +12 -0
  145. package/dist/types/telemetry/lifecycle.d.ts +18 -0
  146. package/dist/types/telemetry/metrics.d.ts +3 -0
  147. package/dist/types/telemetry/plugin.d.ts +12 -0
  148. package/dist/types/telemetry/registry.d.ts +72 -0
  149. package/dist/types/telemetry/registryTypes.d.ts +50 -0
  150. package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
  151. package/dist/types/telemetry.d.ts +1 -12
  152. package/dist/types/telemetryCore.d.ts +6 -257
  153. package/package.json +7 -7
  154. package/src/contract-gate-snapshot-store/file-store.ts +85 -0
  155. package/src/contract-gate-snapshot-store/http-store.ts +159 -0
  156. package/src/contract-gate-snapshot-store/index.ts +20 -0
  157. package/src/contract-gate-snapshot-store/resolve.ts +175 -0
  158. package/src/contract-gate-snapshot-store/types.ts +64 -0
  159. package/src/contractGateAutopilot.ts +45 -9
  160. package/src/index.ts +6 -6
  161. package/src/module-federation-css/collector.ts +82 -0
  162. package/src/module-federation-css/index.ts +14 -0
  163. package/src/module-federation-css/manifest.ts +166 -0
  164. package/src/module-federation-css/plugin.ts +86 -0
  165. package/src/module-federation-css/remote.ts +165 -0
  166. package/src/runtime-fallback-signal/auth.ts +117 -0
  167. package/src/runtime-fallback-signal/constants.ts +19 -0
  168. package/src/runtime-fallback-signal/contract-gate.ts +43 -0
  169. package/src/runtime-fallback-signal/endpoint.ts +22 -0
  170. package/src/runtime-fallback-signal/errors.ts +10 -0
  171. package/src/runtime-fallback-signal/index.ts +36 -0
  172. package/src/runtime-fallback-signal/payload.ts +79 -0
  173. package/src/runtime-fallback-signal/source.ts +49 -0
  174. package/src/runtime-fallback-signal/state.ts +34 -0
  175. package/src/runtime-fallback-signal/status.ts +22 -0
  176. package/src/runtime-fallback-signal/trust-policy.ts +179 -0
  177. package/src/runtime-fallback-signal/types.ts +66 -0
  178. package/src/runtimeFallbackSignal.ts +1 -584
  179. package/src/telemetry/canary.ts +291 -0
  180. package/src/telemetry/canaryEvaluation.ts +83 -0
  181. package/src/telemetry/canarySetup.ts +160 -0
  182. package/src/telemetry/envelope.ts +189 -0
  183. package/src/telemetry/exporters.ts +165 -0
  184. package/src/telemetry/lifecycle.ts +138 -0
  185. package/src/telemetry/metrics.ts +141 -0
  186. package/src/telemetry/plugin.ts +197 -0
  187. package/src/telemetry/registry.ts +467 -0
  188. package/src/telemetry/registryTypes.ts +63 -0
  189. package/src/telemetry/runtimeEndpoints.ts +172 -0
  190. package/src/telemetry.ts +1 -554
  191. package/src/telemetryCore.ts +34 -1332
  192. package/tests/contractGateAutopilot.test.ts +205 -0
  193. package/tests/contractGateSnapshotStore.test.ts +54 -1
  194. package/tests/helpers.ts +1 -0
  195. package/tests/moduleFederationCss.test.ts +1 -1
  196. package/tests/registration.test.ts +1 -1
  197. package/tests/telemetry.test.ts +40 -0
  198. package/tests/telemetryLifecycle.test.ts +253 -2
  199. package/dist/cjs/contractGateSnapshotStore.js +0 -253
  200. package/dist/cjs/moduleFederationCss.js +0 -285
  201. package/dist/esm/contractGateSnapshotStore.mjs +0 -190
  202. package/dist/esm/moduleFederationCss.mjs +0 -225
  203. package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
  204. package/dist/esm-node/moduleFederationCss.mjs +0 -226
  205. package/dist/types/moduleFederationCss.d.ts +0 -87
  206. package/src/contractGateSnapshotStore.ts +0 -420
  207. package/src/moduleFederationCss.ts +0 -473
@@ -1,6 +1,7 @@
1
1
  import fs from 'fs';
2
2
  import os from 'os';
3
3
  import path from 'path';
4
+ import type { GateSnapshot } from '../src/contract-gate-snapshot-store';
4
5
  import { ContractGateAutopilot } from '../src/contractGateAutopilot';
5
6
  import {
6
7
  TelemetryCanaryOrchestrator,
@@ -149,6 +150,210 @@ describe('contract gate autopilot', () => {
149
150
  }
150
151
  });
151
152
 
153
+ test('marks unchanged gate snapshots stale after the stale window elapses', async () => {
154
+ const dir = makeTempDir();
155
+ const snapshotPath = path.join(dir, 'contract-gates.json');
156
+ const originalDateNow = Date.now;
157
+ let now = 1_000_000;
158
+ Date.now = () => now;
159
+
160
+ const registry = new TelemetryRegistry({
161
+ service: 'svc',
162
+ module: 'server',
163
+ environment: 'test',
164
+ flushIntervalMs: 60_000,
165
+ });
166
+ const orchestrator = new TelemetryCanaryOrchestrator({
167
+ registry,
168
+ rollbackConsecutiveFailures: 1,
169
+ });
170
+ fs.writeFileSync(
171
+ snapshotPath,
172
+ JSON.stringify(
173
+ {
174
+ schemaVersion: 1,
175
+ updatedAt: now,
176
+ gates: {
177
+ 'module-onboarding-certification-gates': {
178
+ passed: true,
179
+ updatedAt: now,
180
+ },
181
+ },
182
+ },
183
+ null,
184
+ 2,
185
+ ),
186
+ );
187
+
188
+ const autopilot = new ContractGateAutopilot({
189
+ orchestrator,
190
+ gateSnapshotPath: snapshotPath,
191
+ gateStaleAfterMs: 1_000,
192
+ });
193
+
194
+ try {
195
+ await autopilot.syncOnce();
196
+ expect(orchestrator.evaluate().failures).toHaveLength(0);
197
+
198
+ now += 1_001;
199
+ await autopilot.syncOnce();
200
+
201
+ const decision = orchestrator.evaluate();
202
+ expect(decision.action).toBe('rollback');
203
+ expect(
204
+ decision.failures.some(
205
+ item =>
206
+ item.reason === 'contract_gate_failed' &&
207
+ item.gate === 'module-onboarding-certification-gates',
208
+ ),
209
+ ).toBe(true);
210
+ } finally {
211
+ Date.now = originalDateNow;
212
+ autopilot.stop();
213
+ await registry.shutdown();
214
+ fs.rmSync(dir, { recursive: true, force: true });
215
+ }
216
+ });
217
+
218
+ test('ignores older snapshot reads that resolve after newer syncs', async () => {
219
+ const registry = new TelemetryRegistry({
220
+ service: 'svc',
221
+ module: 'server',
222
+ environment: 'test',
223
+ flushIntervalMs: 60_000,
224
+ });
225
+ const orchestrator = new TelemetryCanaryOrchestrator({
226
+ registry,
227
+ rollbackConsecutiveFailures: 1,
228
+ });
229
+ const snapshotResolvers: Array<
230
+ (snapshot: GateSnapshot | undefined) => void
231
+ > = [];
232
+ const autopilot = new ContractGateAutopilot({
233
+ orchestrator,
234
+ gateSnapshotStore: {
235
+ name: 'deferred',
236
+ readSnapshot: () =>
237
+ new Promise<GateSnapshot | undefined>(resolve => {
238
+ snapshotResolvers.push(resolve);
239
+ }),
240
+ writeSnapshot: async () => {},
241
+ },
242
+ gateStaleAfterMs: 0,
243
+ });
244
+
245
+ try {
246
+ const olderSync = autopilot.syncOnce();
247
+ const newerSync = autopilot.syncOnce();
248
+ expect(snapshotResolvers).toHaveLength(2);
249
+
250
+ snapshotResolvers[1]?.({
251
+ schemaVersion: 1,
252
+ updatedAt: 2_000,
253
+ gates: {
254
+ 'module-onboarding-certification-gates': {
255
+ passed: true,
256
+ updatedAt: 2_000,
257
+ },
258
+ },
259
+ });
260
+ await newerSync;
261
+ expect(orchestrator.evaluate().failures).toHaveLength(0);
262
+
263
+ snapshotResolvers[0]?.({
264
+ schemaVersion: 1,
265
+ updatedAt: 1_000,
266
+ gates: {
267
+ 'module-onboarding-certification-gates': {
268
+ passed: false,
269
+ reason: 'older snapshot resolved late',
270
+ updatedAt: 1_000,
271
+ },
272
+ },
273
+ });
274
+ await olderSync;
275
+
276
+ expect(orchestrator.evaluate().failures).toHaveLength(0);
277
+ } finally {
278
+ autopilot.stop();
279
+ await registry.shutdown();
280
+ }
281
+ });
282
+
283
+ test('clears previously applied gate failures when snapshots omit them', async () => {
284
+ const dir = makeTempDir();
285
+ const snapshotPath = path.join(dir, 'contract-gates.json');
286
+
287
+ const registry = new TelemetryRegistry({
288
+ service: 'svc',
289
+ module: 'server',
290
+ environment: 'test',
291
+ flushIntervalMs: 60_000,
292
+ });
293
+ const orchestrator = new TelemetryCanaryOrchestrator({
294
+ registry,
295
+ rollbackConsecutiveFailures: 1,
296
+ });
297
+ const autopilot = new ContractGateAutopilot({
298
+ orchestrator,
299
+ gateSnapshotPath: snapshotPath,
300
+ gateStaleAfterMs: 60_000,
301
+ });
302
+
303
+ try {
304
+ const now = Date.now();
305
+ fs.writeFileSync(
306
+ snapshotPath,
307
+ JSON.stringify(
308
+ {
309
+ schemaVersion: 1,
310
+ updatedAt: now,
311
+ gates: {
312
+ 'runtime-mf-fallback-health': {
313
+ passed: false,
314
+ reason: 'runtime_fallback:remote_load_failed',
315
+ updatedAt: now,
316
+ },
317
+ },
318
+ },
319
+ null,
320
+ 2,
321
+ ),
322
+ );
323
+
324
+ await autopilot.syncOnce();
325
+ expect(
326
+ orchestrator
327
+ .evaluate()
328
+ .failures.some(
329
+ item =>
330
+ item.reason === 'contract_gate_failed' &&
331
+ item.gate === 'runtime-mf-fallback-health',
332
+ ),
333
+ ).toBe(true);
334
+
335
+ fs.writeFileSync(
336
+ snapshotPath,
337
+ JSON.stringify(
338
+ {
339
+ schemaVersion: 1,
340
+ updatedAt: Date.now(),
341
+ gates: {},
342
+ },
343
+ null,
344
+ 2,
345
+ ),
346
+ );
347
+
348
+ await autopilot.syncOnce();
349
+ expect(orchestrator.evaluate().failures).toHaveLength(0);
350
+ } finally {
351
+ autopilot.stop();
352
+ await registry.shutdown();
353
+ fs.rmSync(dir, { recursive: true, force: true });
354
+ }
355
+ });
356
+
152
357
  test('auto-recovers runtime fallback gates after expiry window', async () => {
153
358
  const dir = makeTempDir();
154
359
  const snapshotPath = path.join(dir, 'contract-gates.json');
@@ -3,9 +3,10 @@ import { createServer } from 'http';
3
3
  import os from 'os';
4
4
  import path from 'path';
5
5
  import {
6
+ createFileContractGateSnapshotStore,
6
7
  type GateSnapshot,
7
8
  resolveContractGateSnapshotStore,
8
- } from '../src/contractGateSnapshotStore';
9
+ } from '../src/contract-gate-snapshot-store';
9
10
 
10
11
  const makeTempAppDir = () =>
11
12
  fs.mkdtempSync(path.join(os.tmpdir(), 'modern-gate-store-app-'));
@@ -26,6 +27,58 @@ exports.createContractGateSnapshotStore = ({ gateSnapshotPath }) => {
26
27
  `;
27
28
 
28
29
  describe('contract gate snapshot store', () => {
30
+ test('preserves previous file snapshot when write fails mid-write', async () => {
31
+ const appDirectory = makeTempAppDir();
32
+ try {
33
+ const snapshotPath = path.join(
34
+ appDirectory,
35
+ '.modern/contract-gates.json',
36
+ );
37
+ const store = createFileContractGateSnapshotStore(snapshotPath);
38
+ const initialSnapshot: GateSnapshot = {
39
+ schemaVersion: 1,
40
+ updatedAt: 1,
41
+ gates: {
42
+ 'runtime-mf-fallback-health': { passed: true },
43
+ },
44
+ };
45
+
46
+ await store.writeSnapshot(initialSnapshot);
47
+
48
+ const realWriteFile = fs.promises.writeFile.bind(fs.promises);
49
+ let sabotagedWrite = false;
50
+ const writeSpy = rs
51
+ .spyOn(fs.promises, 'writeFile')
52
+ .mockImplementation(async (file, _data, options) => {
53
+ if (!sabotagedWrite) {
54
+ sabotagedWrite = true;
55
+ await realWriteFile(file, '{broken', options);
56
+ throw new Error('simulated write interruption');
57
+ }
58
+
59
+ return realWriteFile(file, _data, options);
60
+ });
61
+
62
+ try {
63
+ await expect(
64
+ store.writeSnapshot({
65
+ schemaVersion: 1,
66
+ updatedAt: 2,
67
+ gates: {
68
+ 'runtime-mf-fallback-health': { passed: false },
69
+ },
70
+ }),
71
+ ).rejects.toThrow('simulated write interruption');
72
+ } finally {
73
+ writeSpy.mockRestore();
74
+ }
75
+
76
+ await expect(store.readSnapshot()).resolves.toEqual(initialSnapshot);
77
+ } finally {
78
+ fs.rmSync(appDirectory, { recursive: true, force: true });
79
+ }
80
+ });
81
+
29
82
  test('supports built-in http stateStore adapter', async () => {
30
83
  let snapshot: GateSnapshot | undefined;
31
84
 
package/tests/helpers.ts CHANGED
@@ -1,3 +1,4 @@
1
+ // Intentionally copied from server/core tests to keep runtime-extensions tests package-local.
1
2
  export function getDefaultConfig() {
2
3
  return {
3
4
  html: {},
@@ -6,7 +6,7 @@ import {
6
6
  collectDirectRemoteModuleFederationCssWithMeta,
7
7
  collectModuleFederationManifestCss,
8
8
  createModuleFederationCssCollector,
9
- } from '../src/moduleFederationCss';
9
+ } from '../src/module-federation-css';
10
10
 
11
11
  const tempDirs: string[] = [];
12
12
 
@@ -6,7 +6,7 @@ import {
6
6
  import fs from 'fs';
7
7
  import os from 'os';
8
8
  import path from 'path';
9
- import { injectModuleFederationCssPlugin } from '../src/moduleFederationCss';
9
+ import { injectModuleFederationCssPlugin } from '../src/module-federation-css';
10
10
  import { getDefaultAppContext, getDefaultConfig } from './helpers';
11
11
 
12
12
  describe('plugin registration', () => {
@@ -241,6 +241,46 @@ describe('telemetry registry', () => {
241
241
  await registry.shutdown();
242
242
  });
243
243
 
244
+ test('drop SLO alerts use pending drop pressure instead of lifetime drops', async () => {
245
+ const dropAlerts: Array<{ value: number; totalDropped: number }> = [];
246
+ const registry = new TelemetryRegistry({
247
+ service: 'svc',
248
+ module: 'server',
249
+ environment: 'test',
250
+ maxQueueSize: 1,
251
+ flushIntervalMs: 60_000,
252
+ slo: {
253
+ queueDroppedWarnThreshold: 2,
254
+ alertCooldownMs: 0,
255
+ onAlert(alert) {
256
+ if (alert.type === 'queue.drop') {
257
+ dropAlerts.push({
258
+ value: alert.value,
259
+ totalDropped: alert.totalDropped,
260
+ });
261
+ }
262
+ },
263
+ },
264
+ });
265
+
266
+ registry.enqueue(createEnvelope({ name: 'first' }));
267
+ registry.enqueue(createEnvelope({ name: 'second' }));
268
+ expect(registry.getQueueStats().pendingDropped).toBe(1);
269
+ expect(dropAlerts).toEqual([]);
270
+
271
+ await registry.flush();
272
+ expect(registry.getQueueStats().pendingDropped).toBe(0);
273
+ expect(registry.getQueueStats().totalDropped).toBe(1);
274
+
275
+ registry.enqueue(createEnvelope({ name: 'third' }));
276
+ registry.enqueue(createEnvelope({ name: 'fourth' }));
277
+
278
+ expect(registry.getQueueStats().pendingDropped).toBe(1);
279
+ expect(registry.getQueueStats().totalDropped).toBe(2);
280
+ expect(dropAlerts).toEqual([]);
281
+ await registry.shutdown();
282
+ });
283
+
244
284
  test('startup health check fails loud by default when exporter is unhealthy', async () => {
245
285
  const registry = new TelemetryRegistry({
246
286
  service: 'svc',
@@ -5,6 +5,9 @@ import {
5
5
  type ServerPlugin,
6
6
  } from '@modern-js/server-core';
7
7
  import { logger } from '@modern-js/utils';
8
+ import fs from 'fs';
9
+ import os from 'os';
10
+ import path from 'path';
8
11
  import { injectTelemetryPlugin } from '../src/telemetry';
9
12
  import { getDefaultAppContext, getDefaultConfig } from './helpers';
10
13
 
@@ -32,9 +35,12 @@ const emitMonitorEventsPlugin = (input: {
32
35
  },
33
36
  });
34
37
 
35
- const waitFor = async (predicate: () => boolean, timeoutMs = 2_000) => {
38
+ const waitFor = async (
39
+ predicate: () => boolean | Promise<boolean>,
40
+ timeoutMs = 2_000,
41
+ ) => {
36
42
  const startedAt = Date.now();
37
- while (!predicate()) {
43
+ while (!(await predicate())) {
38
44
  if (Date.now() - startedAt > timeoutMs) {
39
45
  throw new Error('waitFor timed out');
40
46
  }
@@ -93,6 +99,251 @@ describe('telemetry plugin lifecycle', () => {
93
99
  }
94
100
  });
95
101
 
102
+ test('boots canary autopilot lane and exports rollback telemetry', async () => {
103
+ const tempDir = fs.mkdtempSync(
104
+ path.join(os.tmpdir(), 'modern-telemetry-lifecycle-'),
105
+ );
106
+ const gateName = 'runtime-mf-fallback-health';
107
+ const signalToken = 'canary-lifecycle-token';
108
+ const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
109
+ const otlpEndpoint = 'http://127.0.0.1:4318/v1/logs';
110
+ const fetchCalls: Array<{
111
+ url: string;
112
+ body: string;
113
+ headers: HeadersInit | undefined;
114
+ }> = [];
115
+ const fetchMock = rs.fn(async (url: any, init?: RequestInit) => {
116
+ fetchCalls.push({
117
+ url: String(url),
118
+ body: String(init?.body ?? ''),
119
+ headers: init?.headers,
120
+ });
121
+ return new Response('{}', { status: 200 });
122
+ });
123
+ const warnSpy = rs.spyOn(logger, 'warn').mockImplementation(() => {});
124
+ const originalFetch = globalThis.fetch;
125
+ globalThis.fetch = fetchMock as typeof fetch;
126
+
127
+ const nodeServerStub = new EventEmitter();
128
+ const stubNodeServerPlugin: ServerPlugin = {
129
+ name: 'stub-node-server',
130
+ setup(api) {
131
+ api.updateServerContext({ nodeServer: nodeServerStub } as any);
132
+ },
133
+ };
134
+
135
+ try {
136
+ fs.mkdirSync(path.dirname(snapshotPath), { recursive: true });
137
+ fs.writeFileSync(
138
+ snapshotPath,
139
+ JSON.stringify({
140
+ schemaVersion: 1,
141
+ updatedAt: Date.now(),
142
+ gates: {
143
+ [gateName]: {
144
+ passed: true,
145
+ updatedAt: Date.now(),
146
+ },
147
+ },
148
+ }),
149
+ 'utf8',
150
+ );
151
+
152
+ const config = getDefaultConfig();
153
+ config.server = {
154
+ telemetry: {
155
+ enabled: true,
156
+ service: 'runtime-extensions-test',
157
+ module: 'telemetry-lifecycle',
158
+ environment: 'test',
159
+ maxQueueSize: 64,
160
+ maxBatchSize: 100,
161
+ flushIntervalMs: 60_000,
162
+ slo: {
163
+ queueUtilizationWarnThreshold: 0.01,
164
+ alertCooldownMs: 0,
165
+ },
166
+ exporters: {
167
+ otlp: {
168
+ enabled: true,
169
+ endpoint: otlpEndpoint,
170
+ headers: {
171
+ 'x-modernjs-test': 'canary-autopilot',
172
+ },
173
+ timeoutMs: 200,
174
+ },
175
+ },
176
+ canary: {
177
+ enabled: true,
178
+ evaluationIntervalMs: 250,
179
+ minConsecutiveHealthyEvaluations: 1,
180
+ rollbackConsecutiveFailures: 1,
181
+ maxQueueUtilization: 1,
182
+ maxTotalDropped: 0,
183
+ maxUnhealthyExporters: 0,
184
+ contractGates: {
185
+ [gateName]: true,
186
+ },
187
+ autopilot: {
188
+ enabled: true,
189
+ gateSnapshotPath: snapshotPath,
190
+ pollIntervalMs: 250,
191
+ gateStaleAfterMs: 60_000,
192
+ runtimeFallbackSignal: {
193
+ enabled: true,
194
+ endpoint: '/_modern/contract-gates/runtime-fallback',
195
+ gateName,
196
+ failureHoldMs: 5_000,
197
+ maxBodyBytes: 4_096,
198
+ auth: {
199
+ expectedValue: signalToken,
200
+ },
201
+ },
202
+ },
203
+ },
204
+ },
205
+ } as any;
206
+
207
+ const server = createServerBase({
208
+ config,
209
+ pwd: tempDir,
210
+ appContext: getDefaultAppContext(),
211
+ });
212
+ server.addPlugins([
213
+ ...createDefaultPlugins({ logger: false }),
214
+ stubNodeServerPlugin,
215
+ injectTelemetryPlugin(),
216
+ emitMonitorEventsPlugin({
217
+ path: '/emit',
218
+ message: 'canary-request',
219
+ count: 2,
220
+ }),
221
+ ]);
222
+ await server.init();
223
+
224
+ const statusHeaders = new Headers({
225
+ 'x-modernjs-runtime-signal-token': signalToken,
226
+ });
227
+ let statusPayload: any;
228
+
229
+ await waitFor(async () => {
230
+ const status = await server.request(
231
+ '/_modern/runtime/status',
232
+ {
233
+ method: 'GET',
234
+ headers: statusHeaders,
235
+ },
236
+ {},
237
+ );
238
+ expect(status.status).toBe(200);
239
+ statusPayload = await status.json();
240
+ return (
241
+ statusPayload.canary?.state === 'promoted' &&
242
+ statusPayload.canary?.contractGates?.some(
243
+ (gate: any) => gate.name === gateName && gate.passed === true,
244
+ )
245
+ );
246
+ });
247
+
248
+ const emitResponse = await server.request('/emit', {}, {});
249
+ expect(emitResponse.status).toBe(200);
250
+
251
+ const signalResponse = await server.request(
252
+ '/_modern/contract-gates/runtime-fallback',
253
+ {
254
+ method: 'POST',
255
+ headers: new Headers({
256
+ 'content-type': 'application/json',
257
+ 'x-modernjs-runtime-signal-token': signalToken,
258
+ }),
259
+ body: JSON.stringify({
260
+ reason: 'remote_load_failed',
261
+ phase: 'load',
262
+ appName: 'crm',
263
+ entry: 'https://remote.example.com/remoteEntry.js',
264
+ }),
265
+ },
266
+ {},
267
+ );
268
+ expect(signalResponse.status).toBe(202);
269
+
270
+ const persistedSnapshot = JSON.parse(
271
+ fs.readFileSync(snapshotPath, 'utf8'),
272
+ ) as {
273
+ gates?: Record<
274
+ string,
275
+ {
276
+ expiresAt?: number;
277
+ passed?: boolean;
278
+ reason?: string;
279
+ }
280
+ >;
281
+ };
282
+ expect(persistedSnapshot.gates?.[gateName]?.passed).toBe(false);
283
+ expect(persistedSnapshot.gates?.[gateName]?.expiresAt).toBeGreaterThan(
284
+ Date.now(),
285
+ );
286
+
287
+ await waitFor(async () => {
288
+ const status = await server.request(
289
+ '/_modern/runtime/status',
290
+ {
291
+ method: 'GET',
292
+ headers: statusHeaders,
293
+ },
294
+ {},
295
+ );
296
+ expect(status.status).toBe(200);
297
+ statusPayload = await status.json();
298
+ return (
299
+ statusPayload.canary?.state === 'rolled_back' &&
300
+ statusPayload.canary?.contractGates?.some(
301
+ (gate: any) =>
302
+ gate.name === gateName &&
303
+ gate.passed === false &&
304
+ String(gate.reason).includes('remote_load_failed'),
305
+ )
306
+ );
307
+ }, 4_000);
308
+
309
+ expect(statusPayload.telemetry?.exporterHealth).toContainEqual(
310
+ expect.objectContaining({
311
+ name: 'otlp',
312
+ healthy: true,
313
+ }),
314
+ );
315
+ expect(
316
+ fetchCalls.some(
317
+ call =>
318
+ call.url === otlpEndpoint &&
319
+ (call.headers as Record<string, string>)['x-modernjs-test'] ===
320
+ 'canary-autopilot',
321
+ ),
322
+ ).toBe(true);
323
+ expect(
324
+ warnSpy.mock.calls.some(call =>
325
+ String(call[0]).includes('[telemetry.slo] queue.utilization'),
326
+ ),
327
+ ).toBe(true);
328
+
329
+ nodeServerStub.emit('close');
330
+
331
+ await waitFor(() =>
332
+ fetchCalls.some(call =>
333
+ call.body.includes('telemetry.canary.rollback'),
334
+ ),
335
+ );
336
+ const exportedBodies = fetchCalls.map(call => call.body).join('\n');
337
+ expect(exportedBodies).toContain('telemetry.canary.rollback');
338
+ expect(exportedBodies).toContain('canary-request-0');
339
+ } finally {
340
+ nodeServerStub.emit('close');
341
+ globalThis.fetch = originalFetch;
342
+ warnSpy.mockRestore();
343
+ fs.rmSync(tempDir, { recursive: true, force: true });
344
+ }
345
+ });
346
+
96
347
  test('flushes pending envelopes when the node server closes', async () => {
97
348
  const fetchCalls: Array<{ url: string; body: string }> = [];
98
349
  const fetchMock = rs.fn(async (url: any, init?: any) => {