@odatano/core 1.10.0 → 2.0.0-rc.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.
- package/@cds-models/CardanoIndexerService/index.d.ts +142 -0
- package/@cds-models/CardanoIndexerService/index.js +23 -0
- package/@cds-models/CardanoODataService/index.d.ts +693 -2172
- package/@cds-models/CardanoODataService/index.js +88 -390
- package/@cds-models/CardanoSignService/index.d.ts +443 -1574
- package/@cds-models/CardanoSignService/index.js +62 -293
- package/@cds-models/CardanoTransactionService/index.d.ts +431 -1488
- package/@cds-models/CardanoTransactionService/index.js +60 -271
- package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
- package/@cds-models/CardanoWorkerService/index.js +32 -0
- package/@cds-models/_/index.d.ts +70 -40
- package/@cds-models/_/index.js +17 -32
- package/@cds-models/cds/outbox/index.d.ts +28 -0
- package/@cds-models/index.d.ts +225 -522
- package/@cds-models/index.js +35 -218
- package/@cds-models/odatano/cardano/index.d.ts +896 -2947
- package/@cds-models/odatano/cardano/index.js +109 -536
- package/@cds-models/sap/common/index.d.ts +196 -600
- package/@cds-models/sap/common/index.js +28 -269
- package/README.md +136 -102
- package/db/schema.cds +283 -1
- package/db/types.cds +48 -0
- package/package.json +43 -34
- package/src/index.d.ts +1 -1
- package/src/index.js +10 -2
- package/src/plugin.js +12 -2
- package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
- package/srv/blockchain/backends/blockfrost-backend.js +68 -15
- package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
- package/srv/blockchain/backends/cardano-backend.js +13 -0
- package/srv/blockchain/backends/koios-backend.d.ts +26 -2
- package/srv/blockchain/backends/koios-backend.js +147 -15
- package/srv/blockchain/backends/ogmios-backend.d.ts +37 -6
- package/srv/blockchain/backends/ogmios-backend.js +254 -5
- package/srv/blockchain/cardano-client.d.ts +19 -0
- package/srv/blockchain/cardano-client.js +36 -0
- package/srv/blockchain/cardano-indexer.d.ts +50 -1
- package/srv/blockchain/cardano-indexer.js +191 -0
- package/srv/blockchain/crawler/crawler.d.ts +151 -0
- package/srv/blockchain/crawler/crawler.js +677 -0
- package/srv/blockchain/crawler/hooks.d.ts +43 -0
- package/srv/blockchain/crawler/hooks.js +62 -0
- package/srv/blockchain/crawler/index.d.ts +26 -0
- package/srv/blockchain/crawler/index.js +135 -0
- package/srv/blockchain/crawler/sync-state.d.ts +94 -0
- package/srv/blockchain/crawler/sync-state.js +265 -0
- package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
- package/srv/blockchain/signing/hsm-signer.js +8 -1
- package/srv/blockchain/signing/signature-verifier.js +4 -5
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +7 -10
- package/srv/blockchain/transaction-building/buildooor-tx.js +12 -15
- package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
- package/srv/blockchain/wallet-worker/build-request.js +341 -0
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +86 -0
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +228 -0
- package/srv/blockchain/wallet-worker/index.d.ts +14 -0
- package/srv/blockchain/wallet-worker/index.js +80 -0
- package/srv/blockchain/wallet-worker/job-store.d.ts +261 -0
- package/srv/blockchain/wallet-worker/job-store.js +564 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
- package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
- package/srv/blockchain/wallet-worker/signers.js +131 -0
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
- package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
- package/srv/cardano-indexer-service.cds +73 -0
- package/srv/cardano-indexer-service.d.ts +2 -0
- package/srv/cardano-indexer-service.js +76 -0
- package/srv/cardano-service.js +22 -1
- package/srv/cardano-tx-service.d.ts +1 -11
- package/srv/cardano-tx-service.js +11 -162
- package/srv/cardano-worker-service.cds +125 -0
- package/srv/cardano-worker-service.d.ts +2 -0
- package/srv/cardano-worker-service.js +199 -0
- package/srv/server.d.ts +32 -1
- package/srv/server.js +228 -2
- package/srv/utils/collections.d.ts +13 -0
- package/srv/utils/collections.js +24 -0
- package/srv/utils/crypto.d.ts +16 -0
- package/srv/utils/crypto.js +75 -0
- package/srv/utils/error-codes.d.ts +6 -0
- package/srv/utils/error-codes.js +6 -0
- package/srv/utils/errors.d.ts +12 -0
- package/srv/utils/errors.js +45 -0
- package/srv/utils/mappers.js +13 -3
- package/srv/utils/service-events.d.ts +26 -0
- package/srv/utils/service-events.js +46 -0
- package/srv/utils/tx-build-helper.d.ts +1 -2
- package/srv/utils/tx-build-helper.js +3 -5
- package/srv/utils/tx-request-parsers.d.ts +58 -0
- package/srv/utils/tx-request-parsers.js +170 -0
- package/srv/utils/tx-utils.d.ts +2 -1
- package/srv/utils/tx-utils.js +3 -2
- package/srv/utils/types.d.ts +2 -1
- package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
- package/@cds-models/CardanoODataService/index.js.map +0 -1
- package/@cds-models/CardanoODataService/index.ts +0 -776
- package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
- package/@cds-models/CardanoSignService/index.js.map +0 -1
- package/@cds-models/CardanoSignService/index.ts +0 -569
- package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
- package/@cds-models/CardanoTransactionService/index.js.map +0 -1
- package/@cds-models/CardanoTransactionService/index.ts +0 -526
- package/@cds-models/_/index.d.ts.map +0 -1
- package/@cds-models/_/index.js.map +0 -1
- package/@cds-models/_/index.ts +0 -96
- package/@cds-models/cds/outbox/index.ts +0 -27
- package/@cds-models/index.d.ts.map +0 -1
- package/@cds-models/index.js.map +0 -1
- package/@cds-models/index.ts +0 -245
- package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
- package/@cds-models/odatano/cardano/index.js.map +0 -1
- package/@cds-models/odatano/cardano/index.ts +0 -789
- package/@cds-models/sap/common/index.d.ts.map +0 -1
- package/@cds-models/sap/common/index.js.map +0 -1
- package/@cds-models/sap/common/index.ts +0 -249
- package/srv/blockchain/transaction-building/keep-relevant.d.ts +0 -29
- package/srv/blockchain/transaction-building/keep-relevant.js +0 -116
|
@@ -0,0 +1,677 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.CardanoCrawler = void 0;
|
|
7
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
8
|
+
const errors_1 = require("../../utils/errors");
|
|
9
|
+
const collections_1 = require("../../utils/collections");
|
|
10
|
+
const hooks_1 = require("./hooks");
|
|
11
|
+
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
12
|
+
const sync_state_1 = require("./sync-state");
|
|
13
|
+
const { SELECT, DELETE, INSERT } = cds_1.default.ql;
|
|
14
|
+
const logger = cds_1.default.log('CardanoCrawler');
|
|
15
|
+
const CHAIN_POINT_MISMATCH_PREFIX = 'CHAIN_POINT_MISMATCH:';
|
|
16
|
+
class CrawlerStoppedError extends Error {
|
|
17
|
+
constructor() { super('Crawler stopped'); this.name = 'CrawlerStoppedError'; }
|
|
18
|
+
}
|
|
19
|
+
class CrawlerLeaseLostError extends Error {
|
|
20
|
+
constructor() { super('Crawler DB lease lost'); this.name = 'CrawlerLeaseLostError'; }
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* CardanoCrawler — pre-sync engine (v2.0). Streams the chain forward from a configured
|
|
24
|
+
* start block and bulk-indexes Blocks + Transactions (+ inputs/outputs/assets) into the
|
|
25
|
+
* DB, so consumers can query local data instead of hitting a backend per request.
|
|
26
|
+
*
|
|
27
|
+
* Two sources (see CRAWLER_DESIGN.md):
|
|
28
|
+
* - **Ogmios chain-sync** (primary): ordered rollForward + native rollBackward (reorg).
|
|
29
|
+
* - **Blockfrost/Koios pagination** (fallback): forward walk + parent-hash reorg recovery.
|
|
30
|
+
*
|
|
31
|
+
* Lifecycle: start() launches the ingest pipeline detached so the HTTP server binds
|
|
32
|
+
* immediately, but the pipeline promise is retained — stop() halts the loops (waking
|
|
33
|
+
* any pending poll sleep) and AWAITS the pipeline, so shutdown never races in-flight
|
|
34
|
+
* block writes. All per-block writes are atomic. The crawler NEVER crawls from genesis
|
|
35
|
+
* implicitly — it requires an explicit configured start point or an existing cursor.
|
|
36
|
+
*/
|
|
37
|
+
class CardanoCrawler {
|
|
38
|
+
client;
|
|
39
|
+
indexer;
|
|
40
|
+
network;
|
|
41
|
+
config;
|
|
42
|
+
leaseOwner;
|
|
43
|
+
/** Transient-failure retries per block before giving up. */
|
|
44
|
+
static PERSIST_RETRIES = 3;
|
|
45
|
+
/** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
|
|
46
|
+
static CALL_TIMEOUT_MS = 60_000;
|
|
47
|
+
running = false;
|
|
48
|
+
chainSyncHandle = null;
|
|
49
|
+
/** The detached ingest pipeline — awaited by stop() so teardown never races it. */
|
|
50
|
+
pipeline = null;
|
|
51
|
+
/** Resolver that cancels a pending poll sleep (set while sleeping). */
|
|
52
|
+
wake = null;
|
|
53
|
+
/** Cancellers for backend waits, so shutdown is not held hostage by their timeout. */
|
|
54
|
+
callCancels = new Set();
|
|
55
|
+
/** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
|
|
56
|
+
inFlightCallbacks = new Set();
|
|
57
|
+
haltPromise = null;
|
|
58
|
+
finalStatus = 'stopped';
|
|
59
|
+
/** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
|
|
60
|
+
latchOnHalt = false;
|
|
61
|
+
leaseHeld = false;
|
|
62
|
+
leaseHeartbeat = null;
|
|
63
|
+
leaseWake = null;
|
|
64
|
+
constructor(client, indexer, network, config,
|
|
65
|
+
/** Present for production instances created by index.ts; omitted in engine unit tests. */
|
|
66
|
+
leaseOwner) {
|
|
67
|
+
this.client = client;
|
|
68
|
+
this.indexer = indexer;
|
|
69
|
+
this.network = network;
|
|
70
|
+
this.config = config;
|
|
71
|
+
this.leaseOwner = leaseOwner;
|
|
72
|
+
}
|
|
73
|
+
isRunning() {
|
|
74
|
+
return this.running;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
|
|
78
|
+
* Refuses to start without a resume point: an explicit configured start block or an
|
|
79
|
+
* existing cursor — never an implicit full-chain sync from genesis.
|
|
80
|
+
*/
|
|
81
|
+
async start() {
|
|
82
|
+
if (this.running)
|
|
83
|
+
return;
|
|
84
|
+
if (this.haltPromise)
|
|
85
|
+
await this.haltPromise;
|
|
86
|
+
const start = this.config.startSlot != null && this.config.startBlockHash
|
|
87
|
+
? { slot: this.config.startSlot, hash: this.config.startBlockHash, height: this.config.startHeight }
|
|
88
|
+
: undefined;
|
|
89
|
+
// Keep running=false until every DB guard succeeds. A cursor read/config error
|
|
90
|
+
// must never leave a healthy-looking crawler behind.
|
|
91
|
+
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.ensureSyncStateSingleton)(tx, this.network, start));
|
|
92
|
+
if (!cursor.lastBlockHash && !start) {
|
|
93
|
+
logger.error('Crawler start refused: no start block configured and no existing cursor — set crawler.startSlot + crawler.startBlockHash.');
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (this.leaseOwner) {
|
|
97
|
+
const leaseOwner = this.leaseOwner;
|
|
98
|
+
this.leaseHeld = await cds_1.default.tx((tx) => (0, sync_state_1.tryAcquireCrawlerLease)(tx, leaseOwner));
|
|
99
|
+
if (!this.leaseHeld) {
|
|
100
|
+
logger.info('Crawler start skipped: another instance owns the DB lease or the cluster is paused.');
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
this.running = true;
|
|
105
|
+
this.startLeaseHeartbeat();
|
|
106
|
+
// A pipeline crash (e.g. chain-sync intersection not found after downtime) must
|
|
107
|
+
// surface on the cursor — otherwise the crawler looks healthy while doing nothing.
|
|
108
|
+
this.pipeline = this.runIngestPipeline().catch(async (err) => {
|
|
109
|
+
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
|
|
110
|
+
await this.halt('stopped');
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
logger.error('Ingest pipeline crashed:', err);
|
|
114
|
+
const streak = await this.recordCrawlerError(err);
|
|
115
|
+
await this.halt(streak < 0 ? 'stopped' : 'error');
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Stop crawling and WAIT for the pipeline to finish its in-flight step: halts the
|
|
120
|
+
* loops (waking any pending poll sleep), closes the chain-sync stream, records the
|
|
121
|
+
* final status, then awaits the detached pipeline so callers (shutdownAppContext)
|
|
122
|
+
* can safely tear down backends/DB afterwards.
|
|
123
|
+
*/
|
|
124
|
+
async stop(finalStatus = 'stopped') {
|
|
125
|
+
this.beginHalt(finalStatus);
|
|
126
|
+
if (this.haltPromise)
|
|
127
|
+
await this.haltPromise;
|
|
128
|
+
this.pipeline = null;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Halt without awaiting the pipeline — the variant safe to call FROM INSIDE the
|
|
132
|
+
* pipeline (persistBlock failure, stream onError), where awaiting the pipeline
|
|
133
|
+
* would deadlock.
|
|
134
|
+
*/
|
|
135
|
+
/**
|
|
136
|
+
* @param latch clears `desiredRunning`, so NO restart brings the crawler back —
|
|
137
|
+
* only an operator's resumeCrawler does. Reserved for failures a restart cannot
|
|
138
|
+
* fix (misconfiguration, missing resume point). Runtime failures — a dropped
|
|
139
|
+
* chain-sync socket, a provider outage, a node restart — must leave it false,
|
|
140
|
+
* otherwise a routine node restart silently disables the pre-sync for good.
|
|
141
|
+
*/
|
|
142
|
+
async halt(finalStatus = 'stopped', latch = false) {
|
|
143
|
+
this.beginHalt(finalStatus, latch);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Start teardown without awaiting it. Internal callers can therefore halt from
|
|
147
|
+
* inside a tracked callback/pipeline without waiting on their own promise.
|
|
148
|
+
*/
|
|
149
|
+
beginHalt(finalStatus, latch = false) {
|
|
150
|
+
if (latch)
|
|
151
|
+
this.latchOnHalt = true;
|
|
152
|
+
// Once a real failure was observed, a concurrent shutdown must not hide it.
|
|
153
|
+
if (this.finalStatus !== 'error' || finalStatus === 'error')
|
|
154
|
+
this.finalStatus = finalStatus;
|
|
155
|
+
this.running = false;
|
|
156
|
+
this.wake?.(); // cancel a pending poll sleep so the loop exits now
|
|
157
|
+
this.leaseWake?.();
|
|
158
|
+
for (const cancel of [...this.callCancels])
|
|
159
|
+
cancel();
|
|
160
|
+
if (this.haltPromise)
|
|
161
|
+
return;
|
|
162
|
+
this.haltPromise = Promise.resolve().then(async () => {
|
|
163
|
+
const handle = this.chainSyncHandle;
|
|
164
|
+
this.chainSyncHandle = null;
|
|
165
|
+
if (handle) {
|
|
166
|
+
try {
|
|
167
|
+
await handle.close();
|
|
168
|
+
}
|
|
169
|
+
catch (e) {
|
|
170
|
+
logger.warn('chain-sync close failed:', e);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
// Pagination work lives in pipeline; streamed work lives in callback promises.
|
|
174
|
+
// Drain both before releasing the lease or reporting the terminal state.
|
|
175
|
+
const pipeline = this.pipeline;
|
|
176
|
+
if (pipeline)
|
|
177
|
+
await pipeline.catch(() => undefined);
|
|
178
|
+
while (this.inFlightCallbacks.size) {
|
|
179
|
+
await Promise.allSettled([...this.inFlightCallbacks]);
|
|
180
|
+
}
|
|
181
|
+
if (this.leaseHeartbeat)
|
|
182
|
+
await this.leaseHeartbeat.catch(() => undefined);
|
|
183
|
+
try {
|
|
184
|
+
if (this.leaseOwner && this.leaseHeld) {
|
|
185
|
+
await cds_1.default.tx((tx) => (0, sync_state_1.releaseCrawlerLease)(tx, this.leaseOwner, this.finalStatus, this.latchOnHalt));
|
|
186
|
+
this.leaseHeld = false;
|
|
187
|
+
}
|
|
188
|
+
else if (!this.leaseOwner) {
|
|
189
|
+
await cds_1.default.tx((tx) => (0, sync_state_1.setSyncStatus)(tx, this.finalStatus, this.latchOnHalt));
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
catch { /* best effort during teardown */ }
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
async runIngestPipeline() {
|
|
196
|
+
const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
|
|
197
|
+
if (chainSync) {
|
|
198
|
+
await this.runChainSync(chainSync);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (this.config.source === 'ogmios') {
|
|
202
|
+
// 'ogmios' means chain-sync ONLY — never silently degrade to the weaker
|
|
203
|
+
// pagination reorg handling the operator explicitly opted out of.
|
|
204
|
+
logger.error("Crawler source is 'ogmios' but no chain-sync backend is available — crawler not started (use source 'auto' to allow pagination fallback).");
|
|
205
|
+
await this.halt('error', true); // config error: a restart cannot fix it
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
await this.runPagination();
|
|
209
|
+
}
|
|
210
|
+
/** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
|
|
211
|
+
withTimeout(p, label, ms = CardanoCrawler.CALL_TIMEOUT_MS) {
|
|
212
|
+
return new Promise((resolve, reject) => {
|
|
213
|
+
let settled = false;
|
|
214
|
+
let timer;
|
|
215
|
+
let cancel;
|
|
216
|
+
const finish = (cb) => {
|
|
217
|
+
if (settled)
|
|
218
|
+
return;
|
|
219
|
+
settled = true;
|
|
220
|
+
clearTimeout(timer);
|
|
221
|
+
this.callCancels.delete(cancel);
|
|
222
|
+
cb();
|
|
223
|
+
};
|
|
224
|
+
timer = setTimeout(() => finish(() => reject(new errors_1.ProviderUnavailableError(`${label} timed out`, 'crawler', ms))), ms);
|
|
225
|
+
timer.unref?.(); // never keep the process alive for a watchdog timer
|
|
226
|
+
cancel = () => finish(() => reject(new CrawlerStoppedError()));
|
|
227
|
+
this.callCancels.add(cancel);
|
|
228
|
+
p.then((v) => finish(() => resolve(v)), (e) => finish(() => reject(e)));
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
// ---------------------------------------------------------------------------
|
|
232
|
+
// Chain-sync (Ogmios) — primary, reorg-aware
|
|
233
|
+
// ---------------------------------------------------------------------------
|
|
234
|
+
async runChainSync(backend) {
|
|
235
|
+
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
236
|
+
const points = await this.buildIntersectionPoints(cursor);
|
|
237
|
+
if (!points.length) {
|
|
238
|
+
// Defense in depth — start() already refuses this state.
|
|
239
|
+
logger.error('Chain-sync refused: no resume point (configured start block or cursor) available.');
|
|
240
|
+
await this.halt('error', true); // config error: a restart cannot fix it
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
const handle = await backend.openChainSync(points, {
|
|
244
|
+
rollForward: (block, txs, tip) => this.trackCallback(async () => {
|
|
245
|
+
if (!this.running)
|
|
246
|
+
return;
|
|
247
|
+
await this.persistBlock(block, txs, tip);
|
|
248
|
+
}),
|
|
249
|
+
rollBackward: (point) => this.trackCallback(async () => {
|
|
250
|
+
if (!this.running)
|
|
251
|
+
return;
|
|
252
|
+
// Ogmios ALWAYS opens the stream with a rollBackward to the intersection
|
|
253
|
+
// point — that is the protocol handshake, not a reorg. Only roll back when
|
|
254
|
+
// the point differs from our cursor.
|
|
255
|
+
const current = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
256
|
+
if (point !== 'origin' && current?.lastBlockHash === point.hash) {
|
|
257
|
+
logger.debug(`chain-sync intersection acknowledged at slot ${point.slot} — no reorg`);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
await this.handleReorg(point);
|
|
261
|
+
}),
|
|
262
|
+
onError: (err) => this.trackCallback(async () => {
|
|
263
|
+
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
|
|
264
|
+
return;
|
|
265
|
+
// The stream is stalled (mapping/callback failure) — record and halt cleanly
|
|
266
|
+
// so the cursor status shows 'error' instead of a healthy-looking hang.
|
|
267
|
+
const streak = await this.recordCrawlerError(err);
|
|
268
|
+
logger.error('Chain-sync stream error — stopping crawler:', err);
|
|
269
|
+
await this.halt(streak < 0 ? 'stopped' : 'error');
|
|
270
|
+
}),
|
|
271
|
+
});
|
|
272
|
+
// stop() may have raced the async open — close the fresh socket instead of leaking it.
|
|
273
|
+
if (!this.running) {
|
|
274
|
+
try {
|
|
275
|
+
await handle.close();
|
|
276
|
+
}
|
|
277
|
+
catch { /* best effort */ }
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
this.chainSyncHandle = handle;
|
|
281
|
+
logger.info(`Crawler running (chain-sync) from ${points[0].hash} (+${points.length - 1} fallback intersection point(s))`);
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Candidate intersection points, NEWEST FIRST: the cursor, then an exponentially
|
|
285
|
+
* spaced ladder of our own already-crawled ancestors, then the configured start
|
|
286
|
+
* block as the deepest anchor.
|
|
287
|
+
*
|
|
288
|
+
* Why more than the cursor: if the cursor's block was orphaned while the crawler
|
|
289
|
+
* was down, a single-point intersection fails outright ("No intersection found")
|
|
290
|
+
* and the stream never opens. With ancestors on the list the node intersects at
|
|
291
|
+
* the last common block and reports it as a rollBackward — the ordinary reorg path
|
|
292
|
+
* that handleReorg already implements. Doubling offsets cover ~32k blocks with 16
|
|
293
|
+
* points; anything deeper is past any realistic rollback and should fail loudly.
|
|
294
|
+
*/
|
|
295
|
+
async buildIntersectionPoints(cursor) {
|
|
296
|
+
const points = [];
|
|
297
|
+
const seen = new Set();
|
|
298
|
+
const add = (p) => {
|
|
299
|
+
if (!p?.hash || seen.has(p.hash))
|
|
300
|
+
return;
|
|
301
|
+
seen.add(p.hash);
|
|
302
|
+
points.push(p);
|
|
303
|
+
};
|
|
304
|
+
if (cursor?.lastBlockHash) {
|
|
305
|
+
add({ slot: cursor.lastSlot, hash: cursor.lastBlockHash, height: cursor.lastHeight });
|
|
306
|
+
// Dense over the last DENSE_DEPTH blocks, doubling after that. Real rollbacks
|
|
307
|
+
// are a handful of blocks deep, and those must intersect EXACTLY — a gap in
|
|
308
|
+
// the ladder is not wrong (rolling back too far only re-crawls), but it costs
|
|
309
|
+
// needless work on the common case. The doubling tail keeps the deep-reorg
|
|
310
|
+
// reach without sending hundreds of points.
|
|
311
|
+
const DENSE_DEPTH = 10;
|
|
312
|
+
const heights = [];
|
|
313
|
+
const pushHeight = (height) => { if (height > 0 && !heights.includes(height))
|
|
314
|
+
heights.push(height); };
|
|
315
|
+
for (let step = 1; step <= DENSE_DEPTH; step++)
|
|
316
|
+
pushHeight(cursor.lastHeight - step);
|
|
317
|
+
for (let step = 16; step <= 1 << 14; step *= 2)
|
|
318
|
+
pushHeight(cursor.lastHeight - step);
|
|
319
|
+
if (heights.length) {
|
|
320
|
+
const rows = await cds_1.default.tx((tx) => tx.run(SELECT.from(cardano_1.Blocks).columns('height', 'slot', 'hash').where({ height: { in: heights } })));
|
|
321
|
+
for (const row of (rows ?? []).sort((a, b) => Number(b.height ?? 0) - Number(a.height ?? 0))) {
|
|
322
|
+
if (row.hash && row.slot != null)
|
|
323
|
+
add({ slot: Number(row.slot), hash: row.hash, height: Number(row.height) });
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
if (this.config.startBlockHash && this.config.startSlot != null) {
|
|
328
|
+
add({ slot: this.config.startSlot, hash: this.config.startBlockHash, height: this.config.startHeight });
|
|
329
|
+
}
|
|
330
|
+
return points;
|
|
331
|
+
}
|
|
332
|
+
/** Track streamed callbacks because closing a socket does not imply DB callbacks finished. */
|
|
333
|
+
trackCallback(callback) {
|
|
334
|
+
const promise = Promise.resolve().then(callback);
|
|
335
|
+
this.inFlightCallbacks.add(promise);
|
|
336
|
+
void promise.then(() => this.inFlightCallbacks.delete(promise), () => this.inFlightCallbacks.delete(promise));
|
|
337
|
+
return promise;
|
|
338
|
+
}
|
|
339
|
+
// ---------------------------------------------------------------------------
|
|
340
|
+
// Pagination (Blockfrost/Koios) — fallback
|
|
341
|
+
// ---------------------------------------------------------------------------
|
|
342
|
+
async runPagination() {
|
|
343
|
+
const backend = this.client.getPaginatingBackend();
|
|
344
|
+
if (!backend) {
|
|
345
|
+
logger.error('No paginating backend available — cannot crawl without Ogmios or Blockfrost/Koios');
|
|
346
|
+
await this.halt('error', true); // config error: a restart cannot fix it
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
logger.info('Crawler running (pagination)');
|
|
350
|
+
// Tip cache: during deep catch-up the exact tip is irrelevant (only "am I still
|
|
351
|
+
// behind the target" matters) — refetching it every round wasted one HTTP call
|
|
352
|
+
// per batch. Refresh only when the cursor reaches the cached target.
|
|
353
|
+
let tip = null;
|
|
354
|
+
let target = Number.NEGATIVE_INFINITY;
|
|
355
|
+
while (this.running) {
|
|
356
|
+
try {
|
|
357
|
+
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
358
|
+
if (!cursor?.lastBlockHash) {
|
|
359
|
+
logger.error('Pagination refused: cursor has no resume block hash.');
|
|
360
|
+
await this.halt('error', true); // broken precondition: a restart cannot fix it
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
if (!tip || cursor.lastHeight >= target) {
|
|
364
|
+
tip = await this.withTimeout(this.client.getLatestBlock(), 'getLatestBlock');
|
|
365
|
+
target = (tip.height ?? 0) - this.config.confirmationDepth;
|
|
366
|
+
}
|
|
367
|
+
const tipHeight = tip.height ?? 0;
|
|
368
|
+
// Unknown tip slot must mean "NOT at tip" — a 0-fallback would mark every
|
|
369
|
+
// block 'synced' (block.slot >= 0 is always true).
|
|
370
|
+
const tipPoint = tip.slot != null
|
|
371
|
+
? { slot: tip.slot, hash: tip.hash, height: tipHeight }
|
|
372
|
+
: undefined;
|
|
373
|
+
if (cursor.lastHeight >= target) {
|
|
374
|
+
const statusWritten = await cds_1.default.tx(async (tx) => {
|
|
375
|
+
if (this.leaseOwner && !(await (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner)))
|
|
376
|
+
return false;
|
|
377
|
+
await (0, sync_state_1.setSyncStatus)(tx, 'synced');
|
|
378
|
+
return true;
|
|
379
|
+
});
|
|
380
|
+
if (!statusWritten) {
|
|
381
|
+
await this.halt('stopped');
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
await this.sleep(this.config.pollIntervalMs);
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
const blocks = await this.withTimeout(
|
|
388
|
+
// pass the cursor height as anchor hint (>0 only — 0 can mean "unknown"
|
|
389
|
+
// on a fresh start without configured startHeight)
|
|
390
|
+
backend.getNextBlocks(cursor.lastBlockHash, this.config.batchSize, cursor.lastHeight > 0 ? cursor.lastHeight : undefined), 'getNextBlocks');
|
|
391
|
+
if (!blocks.length) {
|
|
392
|
+
await this.sleep(this.config.pollIntervalMs);
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
for (const block of blocks) {
|
|
396
|
+
if (!this.running)
|
|
397
|
+
break;
|
|
398
|
+
if ((block.height ?? 0) > target)
|
|
399
|
+
break; // stay behind the confirmation window
|
|
400
|
+
const txs = await this.withTimeout(backend.getBlockTransactions(block.hash), 'getBlockTransactions');
|
|
401
|
+
const ok = await this.persistBlock(block, txs, tipPoint);
|
|
402
|
+
if (!ok)
|
|
403
|
+
return; // persistBlock already recorded + halted
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
catch (err) {
|
|
407
|
+
if (!this.running || err instanceof CrawlerStoppedError)
|
|
408
|
+
return;
|
|
409
|
+
// Only the backend's explicit anchor/hash mismatch proves that our cursor may
|
|
410
|
+
// be orphaned. Provider outages and partial tx responses must back off instead
|
|
411
|
+
// of launching up to 100 additional provider calls.
|
|
412
|
+
if (err instanceof Error && err.message.startsWith(CHAIN_POINT_MISMATCH_PREFIX)) {
|
|
413
|
+
const recovered = await this.tryReorgRecovery(backend).catch(() => false);
|
|
414
|
+
if (recovered)
|
|
415
|
+
continue;
|
|
416
|
+
if (!this.running)
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
const streak = await this.recordCrawlerError(err);
|
|
420
|
+
if (streak < 0) {
|
|
421
|
+
await this.halt('stopped');
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
logger.error(`pagination round failed (error streak ${streak}):`, err);
|
|
425
|
+
if (streak >= sync_state_1.MAX_CONSECUTIVE_ERRORS) {
|
|
426
|
+
await this.halt('error');
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
await this.sleep(this.config.pollIntervalMs);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Pagination reorg recovery: walk back by height comparing the on-chain block hash with
|
|
435
|
+
* our stored one until they agree — that height is the fork point. If the last-indexed
|
|
436
|
+
* block still matches on-chain, there is no reorg (returns false → treat as transient).
|
|
437
|
+
*/
|
|
438
|
+
async tryReorgRecovery(backend) {
|
|
439
|
+
if (!this.running)
|
|
440
|
+
return false;
|
|
441
|
+
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
442
|
+
if (!cursor || !cursor.lastBlockHash)
|
|
443
|
+
return false;
|
|
444
|
+
const MAX_DEPTH = 100;
|
|
445
|
+
const floor = Math.max(0, cursor.lastHeight - MAX_DEPTH);
|
|
446
|
+
for (let h = cursor.lastHeight; h > floor; h--) {
|
|
447
|
+
if (!this.running)
|
|
448
|
+
return false;
|
|
449
|
+
let onChain;
|
|
450
|
+
try {
|
|
451
|
+
onChain = await this.withTimeout(backend.getBlockByHeight(h), `getBlockByHeight(${h})`);
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
// One unavailable height means the provider cannot currently prove a fork.
|
|
455
|
+
// Abort this recovery round instead of multiplying a provider outage by 100.
|
|
456
|
+
return false;
|
|
457
|
+
}
|
|
458
|
+
if (!this.running)
|
|
459
|
+
return false;
|
|
460
|
+
const ours = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.Blocks).where({ height: h })));
|
|
461
|
+
if (ours?.hash && onChain.hash === ours.hash) {
|
|
462
|
+
if (h === cursor.lastHeight)
|
|
463
|
+
return false; // tip still matches → not a reorg
|
|
464
|
+
// handleReorg deletes everything with slot > forkSlot. A null provider slot
|
|
465
|
+
// (BlockData.slot is nullable) would make forkSlot 0 and wipe the ENTIRE
|
|
466
|
+
// crawled dataset — abort this round instead; the next round can retry with
|
|
467
|
+
// a healthy provider response. (Same guard philosophy as the height axis.)
|
|
468
|
+
if (onChain.slot == null)
|
|
469
|
+
return false;
|
|
470
|
+
await this.handleReorg({ slot: onChain.slot, hash: onChain.hash, height: h });
|
|
471
|
+
return true;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return false;
|
|
475
|
+
}
|
|
476
|
+
// ---------------------------------------------------------------------------
|
|
477
|
+
// Persist + reorg (shared)
|
|
478
|
+
// ---------------------------------------------------------------------------
|
|
479
|
+
/**
|
|
480
|
+
* Persist one block atomically and advance the cursor. Transient failures are retried
|
|
481
|
+
* a few times (recording the error streak); only repeated failure stops the crawler —
|
|
482
|
+
* the cursor is not advanced on failure, so a resume re-syncs cleanly from it.
|
|
483
|
+
* Marks the cursor 'synced' when the block is at the reported tip.
|
|
484
|
+
* @returns true when the block was persisted, false when the crawler was stopped
|
|
485
|
+
*/
|
|
486
|
+
async persistBlock(block, txs, tip) {
|
|
487
|
+
if (txs.length !== block.txCount) {
|
|
488
|
+
throw new errors_1.ProviderUnavailableError(`Incomplete block ${block.hash}: backend returned ${txs.length}/${block.txCount} transactions`, 'crawler');
|
|
489
|
+
}
|
|
490
|
+
const isAtTip = tip != null && block.slot != null && block.slot >= tip.slot;
|
|
491
|
+
// Epoch enrichment needs a backend round-trip on epoch boundaries — do it BEFORE
|
|
492
|
+
// opening the write transaction so the DB lock is never held across network I/O.
|
|
493
|
+
if (block.epoch != null) {
|
|
494
|
+
await this.indexer.prefetchCrawlEpoch(block.epoch);
|
|
495
|
+
}
|
|
496
|
+
for (let attempt = 1;; attempt++) {
|
|
497
|
+
if (!this.running)
|
|
498
|
+
return false;
|
|
499
|
+
try {
|
|
500
|
+
await cds_1.default.tx(async (tx) => {
|
|
501
|
+
if (this.leaseOwner) {
|
|
502
|
+
const renewed = await (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner);
|
|
503
|
+
if (!renewed)
|
|
504
|
+
throw new CrawlerLeaseLostError();
|
|
505
|
+
}
|
|
506
|
+
await this.indexer.indexBlockFull(tx, block, txs);
|
|
507
|
+
await (0, sync_state_1.advanceCursor)(tx, { slot: block.slot ?? 0, hash: block.hash, height: block.height ?? 0 }, tip ? { slot: tip.slot, height: tip.height } : undefined, isAtTip ? 'synced' : 'syncing');
|
|
508
|
+
});
|
|
509
|
+
// Notify observers (wallet-worker confirmation tracker) AFTER the commit —
|
|
510
|
+
// listener failures are swallowed inside emitBlockIndexed.
|
|
511
|
+
(0, hooks_1.emitBlockIndexed)({
|
|
512
|
+
hash: block.hash,
|
|
513
|
+
slot: block.slot ?? null,
|
|
514
|
+
height: block.height ?? null,
|
|
515
|
+
txHashes: txs.map((t) => t.hash),
|
|
516
|
+
tipSlot: tip?.slot ?? null,
|
|
517
|
+
tipHeight: tip?.height ?? null,
|
|
518
|
+
});
|
|
519
|
+
return true;
|
|
520
|
+
}
|
|
521
|
+
catch (err) {
|
|
522
|
+
if (err instanceof CrawlerLeaseLostError) {
|
|
523
|
+
logger.warn('Crawler write fenced because its DB lease is no longer valid.');
|
|
524
|
+
await this.halt('stopped');
|
|
525
|
+
return false;
|
|
526
|
+
}
|
|
527
|
+
const streak = await this.recordCrawlerError(err);
|
|
528
|
+
if (streak < 0) {
|
|
529
|
+
await this.halt('stopped');
|
|
530
|
+
return false;
|
|
531
|
+
}
|
|
532
|
+
if (attempt < CardanoCrawler.PERSIST_RETRIES && streak < sync_state_1.MAX_CONSECUTIVE_ERRORS) {
|
|
533
|
+
logger.warn(`persistBlock ${block.hash} failed (attempt ${attempt}/${CardanoCrawler.PERSIST_RETRIES}, streak ${streak}) — retrying:`, err);
|
|
534
|
+
await this.sleep(1000 * attempt);
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts — stopping crawler (resume re-syncs from cursor):`, err);
|
|
538
|
+
await this.halt('error');
|
|
539
|
+
return false;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Handle a chain rollback: in one transaction, delete every block after the fork point
|
|
545
|
+
* and exactly the transactions belonging to those blocks (plus their child rows), reset
|
|
546
|
+
* the cursor to the fork, and write a CardanoReorgLog audit row.
|
|
547
|
+
*
|
|
548
|
+
* The cut runs on the absolute-slot axis of Blocks (same axis as the fork point), and
|
|
549
|
+
* transactions are resolved via their blockHash — so:
|
|
550
|
+
* - an unresolvable fork height can never widen the delete (no height-0 fallback), and
|
|
551
|
+
* - lazily-indexed transactions of blocks the crawler never wrote are left untouched.
|
|
552
|
+
*/
|
|
553
|
+
async handleReorg(point) {
|
|
554
|
+
const forkSlot = point === 'origin' ? (this.config.startSlot ?? 0) : point.slot;
|
|
555
|
+
let blocksRolledBack = 0;
|
|
556
|
+
let txsRolledBack = 0;
|
|
557
|
+
let emittedForkHeight = null;
|
|
558
|
+
try {
|
|
559
|
+
await cds_1.default.tx(async (tx) => {
|
|
560
|
+
if (this.leaseOwner) {
|
|
561
|
+
const renewed = await (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner);
|
|
562
|
+
if (!renewed)
|
|
563
|
+
throw new CrawlerLeaseLostError();
|
|
564
|
+
}
|
|
565
|
+
// Fork height is metrics/cursor info only — NEVER a delete axis.
|
|
566
|
+
let forkHeight = point === 'origin' ? 0 : point.height;
|
|
567
|
+
if (forkHeight == null && point !== 'origin') {
|
|
568
|
+
const fb = await tx.run(SELECT.one.from(cardano_1.Blocks).where({ hash: point.hash }));
|
|
569
|
+
forkHeight = fb ? Number(fb.height) : undefined;
|
|
570
|
+
}
|
|
571
|
+
emittedForkHeight = forkHeight ?? null;
|
|
572
|
+
// Blocks strictly after the fork, cut on the absolute-slot axis. Rows without a
|
|
573
|
+
// slot (pre-v2.0 lazily indexed blocks) are deliberately excluded.
|
|
574
|
+
const staleBlocks = await tx.run(SELECT.from(cardano_1.Blocks).columns('hash').where({ slot: { '>': forkSlot } }));
|
|
575
|
+
const blockHashes = staleBlocks.map((b) => b.hash);
|
|
576
|
+
blocksRolledBack = blockHashes.length;
|
|
577
|
+
for (const blockChunk of (0, collections_1.chunk)(blockHashes, collections_1.IN_CHUNK)) {
|
|
578
|
+
// Only transactions of the rolled-back blocks — resolved via blockHash, so
|
|
579
|
+
// lazily-indexed txs of unrelated blocks are not collateral damage.
|
|
580
|
+
const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash').where({ blockHash: { in: blockChunk } }));
|
|
581
|
+
const txHashes = staleTxs.map((t) => t.hash);
|
|
582
|
+
txsRolledBack += txHashes.length;
|
|
583
|
+
for (const txChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
|
|
584
|
+
// These denormalized/lazy indexes have no generated FK cascades. Remove
|
|
585
|
+
// them before their parent tx/output rows so orphan data cannot leak via OData.
|
|
586
|
+
await tx.run(DELETE.from(cardano_1.UTxOAssets).where({ utxo_hash: { in: txChunk } }));
|
|
587
|
+
await tx.run(DELETE.from(cardano_1.AddressUTxOs).where({ hash: { in: txChunk } }));
|
|
588
|
+
await tx.run(DELETE.from(cardano_1.AddressTransactions).where({ tx_hash: { in: txChunk } }));
|
|
589
|
+
await tx.run(DELETE.from(cardano_1.AssetHistory_).where({ txHash: { in: txChunk } }));
|
|
590
|
+
await tx.run(DELETE.from(cardano_1.TransactionInputAssets).where({ input_tx_hash: { in: txChunk } }));
|
|
591
|
+
await tx.run(DELETE.from(cardano_1.TransactionOutputAssets).where({ output_tx_hash: { in: txChunk } }));
|
|
592
|
+
await tx.run(DELETE.from(cardano_1.TransactionInputs).where({ tx_hash: { in: txChunk } }));
|
|
593
|
+
await tx.run(DELETE.from(cardano_1.TransactionOutputs).where({ tx_hash: { in: txChunk } }));
|
|
594
|
+
await tx.run(DELETE.from(cardano_1.TransactionMetadata_).where({ tx_hash: { in: txChunk } }));
|
|
595
|
+
await tx.run(DELETE.from(cardano_1.Transactions).where({ hash: { in: txChunk } }));
|
|
596
|
+
}
|
|
597
|
+
await tx.run(DELETE.from(cardano_1.Blocks).where({ hash: { in: blockChunk } }));
|
|
598
|
+
}
|
|
599
|
+
await (0, sync_state_1.resetCursorTo)(tx, point === 'origin'
|
|
600
|
+
? { slot: forkSlot, hash: this.config.startBlockHash ?? '', height: 0 }
|
|
601
|
+
: { slot: point.slot, hash: point.hash, height: forkHeight ?? 0 });
|
|
602
|
+
await tx.run(INSERT.into(cardano_1.CardanoReorgLog).entries({
|
|
603
|
+
ID: cds_1.default.utils.uuid(),
|
|
604
|
+
detectedAt: new Date().toISOString(),
|
|
605
|
+
forkSlot,
|
|
606
|
+
forkHeight: forkHeight ?? null,
|
|
607
|
+
oldTipHash: null,
|
|
608
|
+
newTipHash: point === 'origin' ? null : point.hash,
|
|
609
|
+
blocksRolledBack,
|
|
610
|
+
status: 'completed',
|
|
611
|
+
}));
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
catch (err) {
|
|
615
|
+
if (err instanceof CrawlerLeaseLostError) {
|
|
616
|
+
await this.halt('stopped');
|
|
617
|
+
throw new CrawlerStoppedError();
|
|
618
|
+
}
|
|
619
|
+
throw err;
|
|
620
|
+
}
|
|
621
|
+
// Notify observers (wallet-worker confirmation tracker + CAP subscribers) AFTER
|
|
622
|
+
// the rollback commit.
|
|
623
|
+
(0, hooks_1.emitReorg)({ forkSlot, forkHeight: emittedForkHeight, blocksRolledBack });
|
|
624
|
+
logger.warn(`Reorg handled: rolled back ${blocksRolledBack} blocks (${txsRolledBack} txs) to slot ${forkSlot}`);
|
|
625
|
+
}
|
|
626
|
+
/** Renew the lease while an Ogmios stream is idle; block writes renew it transactionally. */
|
|
627
|
+
startLeaseHeartbeat() {
|
|
628
|
+
if (!this.leaseOwner || this.leaseHeartbeat)
|
|
629
|
+
return;
|
|
630
|
+
const intervalMs = Math.max(1_000, Math.floor(sync_state_1.CRAWLER_LEASE_TTL_MS / 3));
|
|
631
|
+
this.leaseHeartbeat = (async () => {
|
|
632
|
+
while (this.running) {
|
|
633
|
+
await this.leaseSleep(intervalMs);
|
|
634
|
+
if (!this.running)
|
|
635
|
+
return;
|
|
636
|
+
try {
|
|
637
|
+
const renewed = await cds_1.default.tx((tx) => (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner));
|
|
638
|
+
if (!renewed) {
|
|
639
|
+
logger.warn('Crawler heartbeat lost the DB lease or observed a cluster pause.');
|
|
640
|
+
await this.halt('stopped');
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
catch (err) {
|
|
645
|
+
logger.error('Crawler lease heartbeat failed:', err);
|
|
646
|
+
const streak = await this.recordCrawlerError(err);
|
|
647
|
+
await this.halt(streak < 0 ? 'stopped' : 'error');
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
})();
|
|
652
|
+
}
|
|
653
|
+
/** Record state only while this instance still owns the lease. */
|
|
654
|
+
async recordCrawlerError(err) {
|
|
655
|
+
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
|
|
656
|
+
return -1;
|
|
657
|
+
}
|
|
658
|
+
return await cds_1.default.tx((tx) => (0, sync_state_1.recordError)(tx, err, this.leaseOwner)).catch(() => 0);
|
|
659
|
+
}
|
|
660
|
+
leaseSleep(ms) {
|
|
661
|
+
return new Promise((resolve) => {
|
|
662
|
+
const timer = setTimeout(() => { this.leaseWake = null; resolve(); }, ms);
|
|
663
|
+
timer.unref?.();
|
|
664
|
+
this.leaseWake = () => { clearTimeout(timer); this.leaseWake = null; resolve(); };
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
/** Cancellable, unref'd delay — halt() wakes it so shutdown never waits out a poll. */
|
|
668
|
+
sleep(ms) {
|
|
669
|
+
return new Promise((resolve) => {
|
|
670
|
+
const timer = setTimeout(() => { this.wake = null; resolve(); }, ms);
|
|
671
|
+
timer.unref?.();
|
|
672
|
+
this.wake = () => { clearTimeout(timer); this.wake = null; resolve(); };
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
exports.CardanoCrawler = CardanoCrawler;
|
|
677
|
+
//# sourceMappingURL=crawler.js.map
|