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