@bsv/overlay-express 2.2.1 → 2.3.1

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 (53) hide show
  1. package/README.md +33 -0
  2. package/dist/cjs/mod.js +10 -1
  3. package/dist/cjs/mod.js.map +1 -1
  4. package/dist/cjs/package.json +12 -11
  5. package/dist/cjs/src/BanAwareDiscoveryStorage.js +78 -0
  6. package/dist/cjs/src/BanAwareDiscoveryStorage.js.map +1 -0
  7. package/dist/cjs/src/BanAwareTopicManager.js +71 -0
  8. package/dist/cjs/src/BanAwareTopicManager.js.map +1 -0
  9. package/dist/cjs/src/OverlayExpress.js +375 -96
  10. package/dist/cjs/src/OverlayExpress.js.map +1 -1
  11. package/dist/cjs/src/OverlayMonitor.js +464 -0
  12. package/dist/cjs/src/OverlayMonitor.js.map +1 -0
  13. package/dist/cjs/src/ReorgStream.js +193 -0
  14. package/dist/cjs/src/ReorgStream.js.map +1 -0
  15. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
  16. package/dist/esm/mod.js +3 -0
  17. package/dist/esm/mod.js.map +1 -1
  18. package/dist/esm/src/BanAwareDiscoveryStorage.js +79 -0
  19. package/dist/esm/src/BanAwareDiscoveryStorage.js.map +1 -0
  20. package/dist/esm/src/BanAwareTopicManager.js +71 -0
  21. package/dist/esm/src/BanAwareTopicManager.js.map +1 -0
  22. package/dist/esm/src/OverlayExpress.js +375 -94
  23. package/dist/esm/src/OverlayExpress.js.map +1 -1
  24. package/dist/esm/src/OverlayMonitor.js +458 -0
  25. package/dist/esm/src/OverlayMonitor.js.map +1 -0
  26. package/dist/esm/src/ReorgStream.js +190 -0
  27. package/dist/esm/src/ReorgStream.js.map +1 -0
  28. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
  29. package/dist/types/mod.d.ts +4 -1
  30. package/dist/types/mod.d.ts.map +1 -1
  31. package/dist/types/src/BanAwareDiscoveryStorage.d.ts +36 -0
  32. package/dist/types/src/BanAwareDiscoveryStorage.d.ts.map +1 -0
  33. package/dist/types/src/BanAwareTopicManager.d.ts +28 -0
  34. package/dist/types/src/BanAwareTopicManager.d.ts.map +1 -0
  35. package/dist/types/src/OverlayExpress.d.ts +82 -4
  36. package/dist/types/src/OverlayExpress.d.ts.map +1 -1
  37. package/dist/types/src/OverlayMonitor.d.ts +169 -0
  38. package/dist/types/src/OverlayMonitor.d.ts.map +1 -0
  39. package/dist/types/src/ReorgStream.d.ts +74 -0
  40. package/dist/types/src/ReorgStream.d.ts.map +1 -0
  41. package/dist/types/tsconfig.types.tsbuildinfo +1 -1
  42. package/mod.ts +20 -1
  43. package/package.json +12 -11
  44. package/src/BanAwareDiscoveryStorage.ts +91 -0
  45. package/src/BanAwareTopicManager.ts +87 -0
  46. package/src/OverlayExpress.ts +461 -102
  47. package/src/OverlayMonitor.ts +657 -0
  48. package/src/ReorgStream.ts +221 -0
  49. package/src/__tests__/BanAwareDiscoveryStorage.test.ts +131 -0
  50. package/src/__tests__/BanAwareTopicManager.test.ts +132 -0
  51. package/src/__tests__/OverlayExpress.test.ts +86 -1
  52. package/src/__tests__/OverlayMonitor.test.ts +181 -0
  53. package/src/__tests__/ReorgStream.test.ts +66 -0
@@ -0,0 +1,464 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OverlayMonitor = void 0;
4
+ exports.analyzeOverlayAnchorTip = analyzeOverlayAnchorTip;
5
+ exports.analyzeOverlayLookupResponse = analyzeOverlayLookupResponse;
6
+ const sdk_1 = require("@bsv/sdk");
7
+ const defaultThresholds = {
8
+ responseBytes: 1024 * 1024,
9
+ beefBytes: 64 * 1024,
10
+ txsWithoutProof: 1,
11
+ requireSubjectProof: true,
12
+ anchorTipLagBlocks: 6,
13
+ expiredUnprovenCount: 0
14
+ };
15
+ /**
16
+ * OverlayMonitor runs generic Overlay Express /lookup probes and reports response
17
+ * size plus BEEF proof shape. It is intended for long-running monitor workers or
18
+ * scheduled jobs, analogous to a storage monitor but scoped to overlay health.
19
+ */
20
+ class OverlayMonitor {
21
+ constructor(config) {
22
+ var _a, _b, _c, _d;
23
+ this.running = false;
24
+ this.targets = config.targets;
25
+ this.thresholds = { ...defaultThresholds, ...config.thresholds };
26
+ // Bind to globalThis so calling through this.fetchImpl does not rebind `this`
27
+ // (browser fetch throws "Illegal invocation" when invoked as a method).
28
+ this.fetchImpl = (_a = config.fetchImpl) !== null && _a !== void 0 ? _a : fetch.bind(globalThis);
29
+ this.logger = (_b = config.logger) !== null && _b !== void 0 ? _b : console;
30
+ this.onReport = config.onReport;
31
+ this.now = (_c = config.now) !== null && _c !== void 0 ? _c : (() => new Date());
32
+ this.intervalMs = config.intervalMs;
33
+ this.timeoutMs = (_d = config.timeoutMs) !== null && _d !== void 0 ? _d : 30000;
34
+ }
35
+ async runOnce() {
36
+ var _a, _b;
37
+ const startedAt = this.now();
38
+ const results = [];
39
+ const anchorResults = [];
40
+ for (const target of this.targets) {
41
+ for (const probe of target.probes) {
42
+ results.push(await this.runProbe(target, probe));
43
+ }
44
+ for (const probe of (_a = target.anchorProbes) !== null && _a !== void 0 ? _a : []) {
45
+ anchorResults.push(await this.runAnchorProbe(target, probe));
46
+ }
47
+ }
48
+ const completedAt = this.now();
49
+ const report = {
50
+ startedAt,
51
+ completedAt,
52
+ durationMs: completedAt.getTime() - startedAt.getTime(),
53
+ results,
54
+ anchorResults,
55
+ summary: summarize(results, anchorResults, this.targets.length)
56
+ };
57
+ await ((_b = this.onReport) === null || _b === void 0 ? void 0 : _b.call(this, report));
58
+ return report;
59
+ }
60
+ start() {
61
+ if (this.intervalMs === undefined) {
62
+ throw new Error('intervalMs is required to start OverlayMonitor');
63
+ }
64
+ if (this.timer !== undefined)
65
+ return;
66
+ this.timer = setInterval(() => {
67
+ if (this.running)
68
+ return;
69
+ this.running = true;
70
+ this.runOnce()
71
+ .catch(error => {
72
+ this.logger.error('OverlayMonitor run failed', error);
73
+ })
74
+ .finally(() => {
75
+ this.running = false;
76
+ });
77
+ }, this.intervalMs);
78
+ }
79
+ stop() {
80
+ if (this.timer !== undefined) {
81
+ clearInterval(this.timer);
82
+ this.timer = undefined;
83
+ }
84
+ }
85
+ async runProbe(target, probe) {
86
+ var _a;
87
+ const startedAt = this.now();
88
+ const url = new URL('/lookup', target.baseUrl).toString();
89
+ const controller = new AbortController();
90
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
91
+ try {
92
+ const response = await this.fetchImpl(url, {
93
+ method: 'POST',
94
+ headers: {
95
+ Accept: 'application/json',
96
+ 'Content-Type': 'application/json',
97
+ ...target.headers
98
+ },
99
+ body: JSON.stringify({ service: probe.service, query: probe.query }),
100
+ signal: controller.signal
101
+ });
102
+ const text = await response.text();
103
+ const responseBytes = new TextEncoder().encode(text).length;
104
+ const completedAt = this.now();
105
+ let body;
106
+ try {
107
+ body = text.length === 0 ? {} : JSON.parse(text);
108
+ }
109
+ catch (error) {
110
+ return makeFailedResult({
111
+ target,
112
+ probe,
113
+ url,
114
+ status: response.status,
115
+ ok: response.ok,
116
+ responseBytes,
117
+ durationMs: completedAt.getTime() - startedAt.getTime(),
118
+ error: error instanceof Error ? error.message : 'Invalid JSON response'
119
+ });
120
+ }
121
+ return analyzeOverlayLookupResponse({
122
+ target: target.name,
123
+ url,
124
+ probe: (_a = probe.name) !== null && _a !== void 0 ? _a : probe.service,
125
+ service: probe.service,
126
+ status: response.status,
127
+ ok: response.ok,
128
+ responseBody: body,
129
+ responseBytes,
130
+ durationMs: completedAt.getTime() - startedAt.getTime(),
131
+ thresholds: this.thresholds,
132
+ maxOutputs: probe.maxOutputs
133
+ });
134
+ }
135
+ catch (error) {
136
+ const completedAt = this.now();
137
+ const fallbackMessage = error instanceof Error ? error.message : 'Lookup probe failed';
138
+ const message = controller.signal.aborted
139
+ ? `Lookup probe timed out after ${this.timeoutMs}ms`
140
+ : fallbackMessage;
141
+ return makeFailedResult({
142
+ target,
143
+ probe,
144
+ url,
145
+ status: 0,
146
+ ok: false,
147
+ responseBytes: 0,
148
+ durationMs: completedAt.getTime() - startedAt.getTime(),
149
+ error: message
150
+ });
151
+ }
152
+ finally {
153
+ clearTimeout(timeout);
154
+ }
155
+ }
156
+ async runAnchorProbe(target, probe) {
157
+ var _a;
158
+ const startedAt = this.now();
159
+ const url = new URL('/requestTopicAnchorTip', target.baseUrl).toString();
160
+ const controller = new AbortController();
161
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
162
+ try {
163
+ const response = await this.fetchImpl(url, {
164
+ method: 'POST',
165
+ headers: {
166
+ Accept: 'application/json',
167
+ 'Content-Type': 'application/json',
168
+ 'x-bsv-topic': probe.topic,
169
+ ...target.headers
170
+ },
171
+ body: JSON.stringify({}),
172
+ signal: controller.signal
173
+ });
174
+ const text = await response.text();
175
+ const responseBytes = new TextEncoder().encode(text).length;
176
+ const completedAt = this.now();
177
+ let body;
178
+ try {
179
+ body = text.length === 0 ? {} : JSON.parse(text);
180
+ }
181
+ catch (error) {
182
+ return makeFailedAnchorResult({
183
+ target,
184
+ probe,
185
+ url,
186
+ status: response.status,
187
+ ok: response.ok,
188
+ responseBytes,
189
+ durationMs: completedAt.getTime() - startedAt.getTime(),
190
+ error: error instanceof Error ? error.message : 'Invalid JSON response'
191
+ });
192
+ }
193
+ return analyzeOverlayAnchorTip({
194
+ target: target.name,
195
+ url,
196
+ probe: (_a = probe.name) !== null && _a !== void 0 ? _a : probe.topic,
197
+ topic: probe.topic,
198
+ status: response.status,
199
+ ok: response.ok,
200
+ responseBody: body,
201
+ responseBytes,
202
+ durationMs: completedAt.getTime() - startedAt.getTime(),
203
+ thresholds: this.thresholds,
204
+ expectedTac: probe.expectedTac,
205
+ expectedBlockHeight: probe.expectedBlockHeight,
206
+ currentHeight: probe.currentHeight,
207
+ maxTipLagBlocks: probe.maxTipLagBlocks
208
+ });
209
+ }
210
+ catch (error) {
211
+ const completedAt = this.now();
212
+ const fallbackMessage = error instanceof Error ? error.message : 'Anchor probe failed';
213
+ const message = controller.signal.aborted
214
+ ? `Anchor probe timed out after ${this.timeoutMs}ms`
215
+ : fallbackMessage;
216
+ return makeFailedAnchorResult({
217
+ target,
218
+ probe,
219
+ url,
220
+ status: 0,
221
+ ok: false,
222
+ responseBytes: 0,
223
+ durationMs: completedAt.getTime() - startedAt.getTime(),
224
+ error: message
225
+ });
226
+ }
227
+ finally {
228
+ clearTimeout(timeout);
229
+ }
230
+ }
231
+ }
232
+ exports.OverlayMonitor = OverlayMonitor;
233
+ function analyzeOverlayAnchorTip(options) {
234
+ var _a, _b;
235
+ const thresholds = { ...defaultThresholds, ...options.thresholds };
236
+ const blockHeight = typeof options.responseBody.blockHeight === 'number' ? options.responseBody.blockHeight : undefined;
237
+ const tac = typeof options.responseBody.tac === 'string' ? options.responseBody.tac : undefined;
238
+ let expiredUnprovenCount;
239
+ if (typeof options.responseBody.expiredUnprovenCount === 'number') {
240
+ expiredUnprovenCount = options.responseBody.expiredUnprovenCount;
241
+ }
242
+ else if (typeof options.responseBody.unprovenExpiredCount === 'number') {
243
+ expiredUnprovenCount = options.responseBody.unprovenExpiredCount;
244
+ }
245
+ else {
246
+ expiredUnprovenCount = undefined;
247
+ }
248
+ const warnings = [];
249
+ if (options.expectedTac !== undefined && tac !== undefined && tac !== options.expectedTac) {
250
+ warnings.push({
251
+ code: 'anchor-tip-mismatch',
252
+ message: 'Topic anchor TAC does not match expected value',
253
+ value: true,
254
+ threshold: false
255
+ });
256
+ }
257
+ const expectedHeight = (_a = options.expectedBlockHeight) !== null && _a !== void 0 ? _a : options.currentHeight;
258
+ const maxLag = (_b = options.maxTipLagBlocks) !== null && _b !== void 0 ? _b : thresholds.anchorTipLagBlocks;
259
+ if (expectedHeight !== undefined && blockHeight !== undefined && expectedHeight - blockHeight > maxLag) {
260
+ warnings.push({
261
+ code: 'anchor-stale-height',
262
+ message: `Topic anchor tip is ${expectedHeight - blockHeight} blocks behind`,
263
+ value: expectedHeight - blockHeight,
264
+ threshold: maxLag
265
+ });
266
+ }
267
+ if (expiredUnprovenCount !== undefined && expiredUnprovenCount > thresholds.expiredUnprovenCount) {
268
+ warnings.push({
269
+ code: 'expired-unproven-state',
270
+ message: `Overlay reports ${expiredUnprovenCount} expired unproven transactions`,
271
+ value: expiredUnprovenCount,
272
+ threshold: thresholds.expiredUnprovenCount
273
+ });
274
+ }
275
+ return {
276
+ target: options.target,
277
+ url: options.url,
278
+ probe: options.probe,
279
+ topic: options.topic,
280
+ status: options.status,
281
+ ok: options.ok,
282
+ responseBytes: options.responseBytes,
283
+ blockHeight,
284
+ tac,
285
+ warnings,
286
+ durationMs: options.durationMs
287
+ };
288
+ }
289
+ function analyzeOverlayLookupResponse(options) {
290
+ var _a;
291
+ const thresholds = { ...defaultThresholds, ...options.thresholds };
292
+ const outputs = extractOutputs(options.responseBody);
293
+ const maxOutputs = (_a = options.maxOutputs) !== null && _a !== void 0 ? _a : outputs.length;
294
+ const analyzedOutputs = outputs.slice(0, maxOutputs).map(analyzeOutput);
295
+ const warnings = [];
296
+ if (options.responseBytes >= thresholds.responseBytes) {
297
+ warnings.push({
298
+ code: 'response-bytes',
299
+ message: `Lookup response is ${options.responseBytes} bytes`,
300
+ value: options.responseBytes,
301
+ threshold: thresholds.responseBytes
302
+ });
303
+ }
304
+ for (const output of analyzedOutputs) {
305
+ addOutputWarnings(warnings, output, thresholds);
306
+ }
307
+ return {
308
+ target: options.target,
309
+ url: options.url,
310
+ probe: options.probe,
311
+ service: options.service,
312
+ status: options.status,
313
+ ok: options.ok,
314
+ responseBytes: options.responseBytes,
315
+ outputCount: outputs.length,
316
+ analyzedOutputCount: analyzedOutputs.length,
317
+ outputs: analyzedOutputs,
318
+ warnings,
319
+ durationMs: options.durationMs,
320
+ error: options.error
321
+ };
322
+ }
323
+ function makeFailedResult(options) {
324
+ var _a;
325
+ return {
326
+ target: options.target.name,
327
+ url: options.url,
328
+ probe: (_a = options.probe.name) !== null && _a !== void 0 ? _a : options.probe.service,
329
+ service: options.probe.service,
330
+ status: options.status,
331
+ ok: options.ok,
332
+ responseBytes: options.responseBytes,
333
+ outputCount: 0,
334
+ analyzedOutputCount: 0,
335
+ outputs: [],
336
+ warnings: [],
337
+ durationMs: options.durationMs,
338
+ error: options.error
339
+ };
340
+ }
341
+ function makeFailedAnchorResult(options) {
342
+ var _a;
343
+ return {
344
+ target: options.target.name,
345
+ url: options.url,
346
+ probe: (_a = options.probe.name) !== null && _a !== void 0 ? _a : options.probe.topic,
347
+ topic: options.probe.topic,
348
+ status: options.status,
349
+ ok: options.ok,
350
+ responseBytes: options.responseBytes,
351
+ warnings: [],
352
+ durationMs: options.durationMs,
353
+ error: options.error
354
+ };
355
+ }
356
+ function summarize(results, anchorResults, targetCount) {
357
+ return {
358
+ targetCount,
359
+ probeCount: results.length,
360
+ anchorProbeCount: anchorResults.length,
361
+ failedProbeCount: results.filter(result => !result.ok || result.error !== undefined).length +
362
+ anchorResults.filter(result => !result.ok || result.error !== undefined).length,
363
+ responseBytes: results.reduce((sum, result) => sum + result.responseBytes, 0) +
364
+ anchorResults.reduce((sum, result) => sum + result.responseBytes, 0),
365
+ outputCount: results.reduce((sum, result) => sum + result.outputCount, 0),
366
+ analyzedOutputCount: results.reduce((sum, result) => sum + result.analyzedOutputCount, 0),
367
+ outputsMissingSubjectProof: results.reduce((sum, result) => {
368
+ return sum + result.outputs.filter(output => output.subjectHasProof === false).length;
369
+ }, 0),
370
+ warningCount: results.reduce((sum, result) => sum + result.warnings.length, 0) +
371
+ anchorResults.reduce((sum, result) => sum + result.warnings.length, 0)
372
+ };
373
+ }
374
+ function extractOutputs(body) {
375
+ if (typeof body !== 'object' || body === null || !('outputs' in body))
376
+ return [];
377
+ const outputs = body.outputs;
378
+ if (!Array.isArray(outputs))
379
+ return [];
380
+ return outputs.filter((output) => typeof output === 'object' && output !== null);
381
+ }
382
+ function analyzeOutput(output) {
383
+ var _a, _b, _c;
384
+ const outputIndex = typeof output.outputIndex === 'number' ? output.outputIndex : -1;
385
+ const beef = readNumberArray(output.beef);
386
+ const context = readNumberArray(output.context);
387
+ if (beef === undefined) {
388
+ return {
389
+ outputIndex,
390
+ beefBytes: 0,
391
+ contextBytes: context === null || context === void 0 ? void 0 : context.length,
392
+ error: 'Output did not include numeric BEEF'
393
+ };
394
+ }
395
+ try {
396
+ const subjectTx = sdk_1.Transaction.fromBEEF(beef);
397
+ const txid = subjectTx.id('hex');
398
+ const parsedBeef = sdk_1.Beef.fromBinary(beef);
399
+ const subject = parsedBeef.findTxid(txid);
400
+ const subjectRawTxBytes = (_b = (_a = subject === null || subject === void 0 ? void 0 : subject.rawTx) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : subjectTx.toBinary().length;
401
+ const proofCount = parsedBeef.txs.filter(tx => tx.hasProof).length;
402
+ const txsWithoutProof = parsedBeef.txs.filter(tx => !tx.hasProof && !tx.isTxidOnly).length;
403
+ return {
404
+ outputIndex,
405
+ txid,
406
+ beefBytes: beef.length,
407
+ txCount: parsedBeef.txs.length,
408
+ proofCount,
409
+ txsWithoutProof,
410
+ subjectHasProof: (_c = subject === null || subject === void 0 ? void 0 : subject.hasProof) !== null && _c !== void 0 ? _c : false,
411
+ subjectRawTxBytes,
412
+ currentToSubjectRawRatio: subjectRawTxBytes > 0 ? beef.length / subjectRawTxBytes : undefined,
413
+ contextBytes: context === null || context === void 0 ? void 0 : context.length
414
+ };
415
+ }
416
+ catch (error) {
417
+ return {
418
+ outputIndex,
419
+ beefBytes: beef.length,
420
+ contextBytes: context === null || context === void 0 ? void 0 : context.length,
421
+ error: error instanceof Error ? error.message : 'Failed to parse BEEF'
422
+ };
423
+ }
424
+ }
425
+ function addOutputWarnings(warnings, output, thresholds) {
426
+ if (output.beefBytes >= thresholds.beefBytes) {
427
+ warnings.push({
428
+ code: 'beef-bytes',
429
+ message: `Output BEEF is ${output.beefBytes} bytes`,
430
+ value: output.beefBytes,
431
+ threshold: thresholds.beefBytes,
432
+ outputIndex: output.outputIndex,
433
+ txid: output.txid
434
+ });
435
+ }
436
+ if (typeof output.txsWithoutProof === 'number' && output.txsWithoutProof >= thresholds.txsWithoutProof) {
437
+ warnings.push({
438
+ code: 'txs-without-proof',
439
+ message: `Output BEEF has ${output.txsWithoutProof} transactions without direct proof`,
440
+ value: output.txsWithoutProof,
441
+ threshold: thresholds.txsWithoutProof,
442
+ outputIndex: output.outputIndex,
443
+ txid: output.txid
444
+ });
445
+ }
446
+ if (thresholds.requireSubjectProof && output.subjectHasProof === false) {
447
+ warnings.push({
448
+ code: 'subject-proof-missing',
449
+ message: 'Output subject transaction does not have a direct Merkle proof',
450
+ value: false,
451
+ threshold: true,
452
+ outputIndex: output.outputIndex,
453
+ txid: output.txid
454
+ });
455
+ }
456
+ }
457
+ function readNumberArray(value) {
458
+ if (!Array.isArray(value))
459
+ return undefined;
460
+ if (!value.every(item => Number.isInteger(item) && item >= 0 && item <= 255))
461
+ return undefined;
462
+ return value;
463
+ }
464
+ //# sourceMappingURL=OverlayMonitor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OverlayMonitor.js","sourceRoot":"","sources":["../../../src/OverlayMonitor.ts"],"names":[],"mappings":";;;AA6XA,0DAuEC;AAED,oEAmCC;AAzeD,kCAA4C;AA6I5C,MAAM,iBAAiB,GAAuC;IAC5D,aAAa,EAAE,IAAI,GAAG,IAAI;IAC1B,SAAS,EAAE,EAAE,GAAG,IAAI;IACpB,eAAe,EAAE,CAAC;IAClB,mBAAmB,EAAE,IAAI;IACzB,kBAAkB,EAAE,CAAC;IACrB,oBAAoB,EAAE,CAAC;CACxB,CAAA;AAED;;;;GAIG;AACH,MAAa,cAAc;IAYzB,YAAa,MAA4B;;QAFjC,YAAO,GAAG,KAAK,CAAA;QAGrB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAA;QAC7B,IAAI,CAAC,UAAU,GAAG,EAAE,GAAG,iBAAiB,EAAE,GAAG,MAAM,CAAC,UAAU,EAAE,CAAA;QAChE,8EAA8E;QAC9E,wEAAwE;QACxE,IAAI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E,KAAK;YACZ,SAAS,EAAE,IAAI;YACf,WAAW,EAAE,MAAM,CAAC,WAAW;YAC/B,IAAI,EAAE,MAAM,CAAC,IAAI;SAClB,CAAC,CAAA;IACJ,CAAC;AACH,CAAC;AAED,SAAS,eAAe,CAAE,KAAc;IACtC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,SAAS,CAAA;IAC3C,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,GAAG,CAAC;QAAE,OAAO,SAAS,CAAA;IAC9F,OAAO,KAAK,CAAA;AACd,CAAC"}
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ /**
3
+ * Consumes the go-chaintracks (Arcade) reorg SSE stream (`GET /v2/reorg/stream`)
4
+ * and normalizes each `ReorgEvent` into the overlay engine's `handleReorg` input.
5
+ *
6
+ * The stream emits `data: <JSON>\n\n` frames (no `event:`/`id:` lines) with
7
+ * `: keepalive` comment frames in between. Because there are no event ids, a
8
+ * reconnect cannot replay events missed while disconnected — so every (re)connect
9
+ * triggers an `onConnect` catch-up (the engine's revalidation sweep).
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ReorgSseAdapter = void 0;
13
+ exports.parseReorgEvent = parseReorgEvent;
14
+ exports.extractSseFrames = extractSseFrames;
15
+ /**
16
+ * Parses a single SSE data frame (a go-chaintracks `ReorgEvent` JSON document)
17
+ * into `handleReorg` input. Returns `null` for malformed frames.
18
+ *
19
+ * `ReorgEvent` = { orphanedHashes: string[], commonAncestor: BlockHeader|null,
20
+ * newTip: BlockHeader, depth: number }. Block hashes are go-sdk `chainhash.Hash`
21
+ * values marshaled as reversed (display) hex; they are lower-cased here to match
22
+ * the overlay's stored block hashes.
23
+ */
24
+ function parseReorgEvent(frame) {
25
+ var _a, _b;
26
+ let event;
27
+ try {
28
+ event = JSON.parse(frame);
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ const newTipHeight = (_a = event === null || event === void 0 ? void 0 : event.newTip) === null || _a === void 0 ? void 0 : _a.height;
34
+ if (typeof newTipHeight !== 'number') {
35
+ return null;
36
+ }
37
+ const orphanedBlockHashes = Array.isArray(event.orphanedHashes)
38
+ ? event.orphanedHashes
39
+ .filter((hash) => typeof hash === 'string')
40
+ .map((hash) => hash.toLowerCase())
41
+ : [];
42
+ const ancestorHeight = (_b = event === null || event === void 0 ? void 0 : event.commonAncestor) === null || _b === void 0 ? void 0 : _b.height;
43
+ const depth = event === null || event === void 0 ? void 0 : event.depth;
44
+ let rebuildFromHeight;
45
+ if (typeof ancestorHeight === 'number') {
46
+ rebuildFromHeight = ancestorHeight + 1;
47
+ }
48
+ else if (typeof depth === 'number') {
49
+ // No common ancestor (e.g. reorg deeper than retained history): fall back to
50
+ // the reported depth from the new tip.
51
+ rebuildFromHeight = Math.max(0, newTipHeight - depth + 1);
52
+ }
53
+ else {
54
+ return null;
55
+ }
56
+ return { orphanedBlockHashes, rebuildFromHeight, newTipHeight };
57
+ }
58
+ /**
59
+ * Splits an SSE byte buffer into complete event payloads. Frames are delimited by
60
+ * a blank line (`\n\n`); within a frame, `data:` lines are concatenated and
61
+ * comment lines (starting with `:`) are ignored. Any trailing partial frame is
62
+ * returned in `rest` for the next read.
63
+ */
64
+ function extractSseFrames(buffer) {
65
+ const events = [];
66
+ let working = buffer;
67
+ let boundary = working.indexOf('\n\n');
68
+ while (boundary !== -1) {
69
+ const block = working.slice(0, boundary);
70
+ working = working.slice(boundary + 2);
71
+ const dataLines = [];
72
+ for (const line of block.split('\n')) {
73
+ if (line.startsWith(':')) {
74
+ continue;
75
+ }
76
+ if (line.startsWith('data:')) {
77
+ dataLines.push(line.slice(5).replace(/^ /, ''));
78
+ }
79
+ }
80
+ if (dataLines.length > 0) {
81
+ events.push(dataLines.join(''));
82
+ }
83
+ boundary = working.indexOf('\n\n');
84
+ }
85
+ return { events, rest: working };
86
+ }
87
+ /**
88
+ * Long-lived SSE client that keeps the overlay's BASM anchors reconciled with
89
+ * chain reorgs. Auto-reconnects with a fixed delay and runs a catch-up on connect.
90
+ */
91
+ class ReorgSseAdapter {
92
+ constructor(options) {
93
+ var _a, _b, _c;
94
+ this.stopped = false;
95
+ this.url = options.url;
96
+ this.onReorg = options.onReorg;
97
+ this.onConnect = options.onConnect;
98
+ this.logger = (_a = options.logger) !== null && _a !== void 0 ? _a : console;
99
+ this.reconnectDelayMs = (_b = options.reconnectDelayMs) !== null && _b !== void 0 ? _b : 5000;
100
+ this.fetchImpl = (_c = options.fetchImpl) !== null && _c !== void 0 ? _c : fetch;
101
+ }
102
+ /** Begins consuming the stream in the background. */
103
+ start() {
104
+ if (this.stopped) {
105
+ return;
106
+ }
107
+ void this.runLoop();
108
+ }
109
+ /** Stops consuming and aborts any in-flight connection. */
110
+ stop() {
111
+ var _a;
112
+ this.stopped = true;
113
+ (_a = this.controller) === null || _a === void 0 ? void 0 : _a.abort();
114
+ }
115
+ async runLoop() {
116
+ while (!this.stopped) {
117
+ try {
118
+ await this.connectOnce();
119
+ }
120
+ catch (error) {
121
+ if (!this.stopped) {
122
+ this.logger.warn(`[BASM] reorg stream error: ${error instanceof Error ? error.message : String(error)}`);
123
+ }
124
+ }
125
+ if (this.stopped) {
126
+ break;
127
+ }
128
+ await this.delay(this.reconnectDelayMs);
129
+ }
130
+ }
131
+ async connectOnce() {
132
+ this.controller = new AbortController();
133
+ const response = await this.fetchImpl(this.url, {
134
+ headers: { Accept: 'text/event-stream' },
135
+ signal: this.controller.signal
136
+ });
137
+ if (!response.ok || response.body == null) {
138
+ throw new Error(`reorg stream responded ${response.status}`);
139
+ }
140
+ // No event-id replay on this stream: catch up on (re)connect.
141
+ await this.runCatchUp();
142
+ await this.pumpEvents(response.body.getReader());
143
+ }
144
+ async runCatchUp() {
145
+ if (this.onConnect === undefined) {
146
+ return;
147
+ }
148
+ try {
149
+ await this.onConnect();
150
+ }
151
+ catch (error) {
152
+ this.logger.warn(`[BASM] reorg catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
153
+ }
154
+ }
155
+ async pumpEvents(reader) {
156
+ const decoder = new TextDecoder();
157
+ let buffer = '';
158
+ while (!this.stopped) {
159
+ const { value, done } = await reader.read();
160
+ if (done) {
161
+ break;
162
+ }
163
+ buffer += decoder.decode(value, { stream: true });
164
+ const { events, rest } = extractSseFrames(buffer);
165
+ buffer = rest;
166
+ for (const frame of events) {
167
+ await this.processReorgFrame(frame);
168
+ }
169
+ }
170
+ }
171
+ async processReorgFrame(frame) {
172
+ const input = parseReorgEvent(frame);
173
+ if (input === null) {
174
+ this.logger.warn('[BASM] skipping malformed reorg frame');
175
+ return;
176
+ }
177
+ try {
178
+ await this.onReorg(input);
179
+ }
180
+ catch (error) {
181
+ this.logger.error(`[BASM] handleReorg failed: ${error instanceof Error ? error.message : String(error)}`);
182
+ }
183
+ }
184
+ async delay(ms) {
185
+ await new Promise(resolve => {
186
+ var _a;
187
+ const timer = setTimeout(resolve, ms);
188
+ (_a = timer.unref) === null || _a === void 0 ? void 0 : _a.call(timer);
189
+ });
190
+ }
191
+ }
192
+ exports.ReorgSseAdapter = ReorgSseAdapter;
193
+ //# sourceMappingURL=ReorgStream.js.map