@odatano/core 2.0.0-rc.2 → 2.0.0-rc.21
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/CardanoAgentService/index.d.ts +251 -0
- package/@cds-models/CardanoAgentService/index.js +36 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
- package/@cds-models/CardanoIndexerService/index.js +18 -0
- package/@cds-models/CardanoODataService/index.d.ts +231 -6
- package/@cds-models/CardanoODataService/index.js +27 -0
- package/@cds-models/CardanoSignService/index.d.ts +5 -2
- package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
- package/@cds-models/odatano/cardano/index.d.ts +323 -6
- package/@cds-models/odatano/cardano/index.js +33 -0
- package/README.md +195 -136
- package/db/schema.cds +2133 -1633
- package/package.json +181 -173
- package/scripts/migrate-slot-leader.mjs +104 -0
- package/scripts/migrate-txseq.mjs +147 -0
- package/src/index.d.ts +10 -10
- package/src/index.js +24 -14
- package/src/plugin.js +39 -52
- package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
- package/srv/blockchain/backends/blockfrost-backend.js +45 -158
- package/srv/blockchain/backends/cardano-backend.d.ts +83 -158
- package/srv/blockchain/backends/cardano-backend.js +14 -5
- package/srv/blockchain/backends/koios-backend.d.ts +126 -60
- package/srv/blockchain/backends/koios-backend.js +293 -203
- package/srv/blockchain/backends/ogmios-backend.d.ts +69 -94
- package/srv/blockchain/backends/ogmios-backend.js +319 -185
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
- package/srv/blockchain/cardano-client.d.ts +57 -204
- package/srv/blockchain/cardano-client.js +94 -226
- package/srv/blockchain/cardano-indexer.d.ts +176 -240
- package/srv/blockchain/cardano-indexer.js +615 -338
- package/srv/blockchain/cardano-tx-builder.d.ts +29 -82
- package/srv/blockchain/cardano-tx-builder.js +88 -128
- package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
- package/srv/blockchain/crawler/certificate-backfill.js +150 -0
- package/srv/blockchain/crawler/crawler.d.ts +121 -53
- package/srv/blockchain/crawler/crawler.js +403 -89
- package/srv/blockchain/crawler/hooks.d.ts +3 -14
- package/srv/blockchain/crawler/index.d.ts +5 -0
- package/srv/blockchain/crawler/index.js +35 -7
- package/srv/blockchain/crawler/sync-state.d.ts +44 -28
- package/srv/blockchain/crawler/sync-state.js +115 -43
- package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
- package/srv/blockchain/crawler/utxo-set-import.js +269 -0
- package/srv/blockchain/ledger-state.d.ts +80 -0
- package/srv/blockchain/ledger-state.js +383 -0
- package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
- package/srv/blockchain/signing/cose-verifier.js +6 -12
- package/srv/blockchain/signing/external-signer.d.ts +16 -113
- package/srv/blockchain/signing/external-signer.js +19 -122
- package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
- package/srv/blockchain/signing/hsm-signer.js +23 -63
- package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
- package/srv/blockchain/signing/signature-verifier.js +13 -54
- package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
- package/srv/blockchain/signing/submission-finalizer.js +16 -48
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
- package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +42 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
- package/srv/blockchain/wallet-worker/build-request.js +39 -23
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
- package/srv/blockchain/wallet-worker/index.js +2 -8
- package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
- package/srv/blockchain/wallet-worker/job-store.js +0 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
- package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
- package/srv/blockchain/wallet-worker/signers.js +3 -8
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
- package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
- package/srv/cardano-agent-service.cds +146 -0
- package/srv/cardano-agent-service.d.ts +2 -0
- package/srv/cardano-agent-service.js +12 -0
- package/srv/cardano-indexer-service.cds +164 -73
- package/srv/cardano-indexer-service.js +156 -11
- package/srv/cardano-service.cds +45 -0
- package/srv/cardano-service.js +38 -96
- package/srv/cardano-sign-service.cds +200 -180
- package/srv/cardano-sign-service.js +55 -173
- package/srv/cardano-tx-service.cds +32 -26
- package/srv/cardano-tx-service.js +136 -196
- package/srv/cardano-worker-service.js +7 -15
- package/srv/server.d.ts +28 -86
- package/srv/server.js +95 -128
- package/srv/utils/agent-grants-config.d.ts +37 -0
- package/srv/utils/agent-grants-config.js +138 -0
- package/srv/utils/agent-grants.d.ts +262 -0
- package/srv/utils/agent-grants.js +914 -0
- package/srv/utils/agent-token-auth.d.ts +16 -0
- package/srv/utils/agent-token-auth.js +78 -0
- package/srv/utils/backend-request-handler.d.ts +2 -16
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +4 -8
- package/srv/utils/collections.js +4 -8
- package/srv/utils/const.d.ts +19 -68
- package/srv/utils/const.js +20 -69
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +5 -18
- package/srv/utils/db-indexes.d.ts +25 -0
- package/srv/utils/db-indexes.js +93 -0
- package/srv/utils/db-sanitize.d.ts +27 -0
- package/srv/utils/db-sanitize.js +85 -0
- package/srv/utils/epoch-slots.d.ts +13 -0
- package/srv/utils/epoch-slots.js +25 -0
- package/srv/utils/error-codes.d.ts +18 -73
- package/srv/utils/error-codes.js +17 -70
- package/srv/utils/errors.d.ts +36 -179
- package/srv/utils/errors.js +62 -220
- package/srv/utils/liveness.d.ts +16 -0
- package/srv/utils/liveness.js +41 -0
- package/srv/utils/mappers.d.ts +89 -214
- package/srv/utils/mappers.js +289 -301
- package/srv/utils/network-context.js +2 -11
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +57 -0
- package/srv/utils/plutus-placeholders.d.ts +6 -18
- package/srv/utils/plutus-placeholders.js +6 -20
- package/srv/utils/rate-limiter.d.ts +46 -0
- package/srv/utils/rate-limiter.js +116 -0
- package/srv/utils/service-events.d.ts +2 -22
- package/srv/utils/service-events.js +3 -23
- package/srv/utils/signing-helper.d.ts +3 -18
- package/srv/utils/signing-helper.js +10 -32
- package/srv/utils/tx-build-helper.d.ts +18 -92
- package/srv/utils/tx-build-helper.js +32 -123
- package/srv/utils/tx-request-parsers.d.ts +14 -20
- package/srv/utils/tx-request-parsers.js +33 -20
- package/srv/utils/tx-utils.d.ts +4 -23
- package/srv/utils/tx-utils.js +12 -41
- package/srv/utils/types.d.ts +114 -169
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +19 -89
- package/srv/utils/validators.js +31 -138
|
@@ -7,7 +7,10 @@ exports.CardanoCrawler = void 0;
|
|
|
7
7
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
8
8
|
const errors_1 = require("../../utils/errors");
|
|
9
9
|
const collections_1 = require("../../utils/collections");
|
|
10
|
+
const const_1 = require("../../utils/const");
|
|
10
11
|
const hooks_1 = require("./hooks");
|
|
12
|
+
const ledger_state_1 = require("../ledger-state");
|
|
13
|
+
const transaction_rows_1 = require("../transaction-rows");
|
|
11
14
|
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
12
15
|
const sync_state_1 = require("./sync-state");
|
|
13
16
|
const { SELECT, DELETE, INSERT } = cds_1.default.ql;
|
|
@@ -20,19 +23,9 @@ class CrawlerLeaseLostError extends Error {
|
|
|
20
23
|
constructor() { super('Crawler DB lease lost'); this.name = 'CrawlerLeaseLostError'; }
|
|
21
24
|
}
|
|
22
25
|
/**
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
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.
|
|
26
|
+
* Pre-sync engine: streams the chain forward from a start block and bulk-indexes it. Sources:
|
|
27
|
+
* Ogmios chain-sync (primary, native rollBackward) or Blockfrost/Koios pagination (fallback).
|
|
28
|
+
* Per-block writes are atomic; stop() awaits the detached pipeline; no implicit genesis crawl.
|
|
36
29
|
*/
|
|
37
30
|
class CardanoCrawler {
|
|
38
31
|
client;
|
|
@@ -42,10 +35,42 @@ class CardanoCrawler {
|
|
|
42
35
|
leaseOwner;
|
|
43
36
|
/** Transient-failure retries per block before giving up. */
|
|
44
37
|
static PERSIST_RETRIES = 3;
|
|
38
|
+
/** Final persist failures for the same block across restarts before the crawler latches off (poison block). */
|
|
39
|
+
static POISON_BLOCK_THRESHOLD = 5;
|
|
40
|
+
/** Process-wide, survives instance restarts: the block currently failing and how often. */
|
|
41
|
+
static poison = null;
|
|
42
|
+
/**
|
|
43
|
+
* Errors deterministic for the block's data — only these count towards the poison latch.
|
|
44
|
+
* Outages, statement timeouts and exhausted pools are fixed by a restart and must not latch.
|
|
45
|
+
*/
|
|
46
|
+
static DATA_REJECTION_PATTERNS = [
|
|
47
|
+
/unsupported unicode escape sequence/i, // PostgreSQL: U+0000 inside a JSON document
|
|
48
|
+
/invalid byte sequence for encoding/i, // PostgreSQL: bytes that are not valid UTF-8
|
|
49
|
+
/out of range for type/i, // PostgreSQL: bigint / integer overflow
|
|
50
|
+
/invalid input syntax for type/i, // PostgreSQL: NaN or text in a numeric column
|
|
51
|
+
/value too long for type/i, // PostgreSQL: varchar(n) exceeded
|
|
52
|
+
/numeric value out of range/i, // HANA / SQL-92
|
|
53
|
+
/inserted value too large for column/i, // HANA
|
|
54
|
+
/string or blob too big/i, // SQLite
|
|
55
|
+
/datatype mismatch/i, // SQLite
|
|
56
|
+
];
|
|
45
57
|
/** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
|
|
46
58
|
static CALL_TIMEOUT_MS = 60_000;
|
|
59
|
+
/** Epoch snapshots are ~100 batched provider requests on mainnet; wider bound, cancelled by beginHalt. */
|
|
60
|
+
static SNAPSHOT_TIMEOUT_MS = 5 * 60_000;
|
|
61
|
+
/** Backoff after a failed snapshot attempt, doubling up to the cap; the marker is only set on success. */
|
|
62
|
+
static SNAPSHOT_RETRY_BASE_MS = 30_000;
|
|
63
|
+
static SNAPSHOT_RETRY_MAX_MS = 10 * 60_000;
|
|
64
|
+
/** Retry cadence for a chain-sync backend's init while the crawl runs on pagination. */
|
|
65
|
+
static CHAIN_SYNC_RETRY_MS = 30_000;
|
|
47
66
|
running = false;
|
|
48
67
|
chainSyncHandle = null;
|
|
68
|
+
/** What the ingest loop is currently reading from; null while stopped. */
|
|
69
|
+
activeSource = null;
|
|
70
|
+
/** Chain-sync init retry while on pagination: own timer, in-flight probe, outcome. */
|
|
71
|
+
chainSyncProbeTimer = null;
|
|
72
|
+
chainSyncProbe = null;
|
|
73
|
+
chainSyncRecovered = false;
|
|
49
74
|
/** The detached ingest pipeline — awaited by stop() so teardown never races it. */
|
|
50
75
|
pipeline = null;
|
|
51
76
|
/** Resolver that cancels a pending poll sleep (set while sleeping). */
|
|
@@ -55,9 +80,19 @@ class CardanoCrawler {
|
|
|
55
80
|
/** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
|
|
56
81
|
inFlightCallbacks = new Set();
|
|
57
82
|
haltPromise = null;
|
|
83
|
+
/** An unparseable chain-sync frame; the ingest loop fetches that block via pagination, then reopens chain-sync. */
|
|
84
|
+
frameFailure = null;
|
|
85
|
+
/** Resolves the ingest loop's wait for the current chain-sync stream to end. */
|
|
86
|
+
streamEnded = null;
|
|
58
87
|
finalStatus = 'stopped';
|
|
59
88
|
/** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
|
|
60
89
|
latchOnHalt = false;
|
|
90
|
+
/** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
|
|
91
|
+
snapshotedEpoch = null;
|
|
92
|
+
snapshotInFlight = null;
|
|
93
|
+
/** Consecutive snapshot failures and the earliest time the next attempt may run. */
|
|
94
|
+
snapshotFailures = 0;
|
|
95
|
+
snapshotRetryAfter = 0;
|
|
61
96
|
leaseHeld = false;
|
|
62
97
|
leaseHeartbeat = null;
|
|
63
98
|
leaseWake = null;
|
|
@@ -73,6 +108,14 @@ class CardanoCrawler {
|
|
|
73
108
|
isRunning() {
|
|
74
109
|
return this.running;
|
|
75
110
|
}
|
|
111
|
+
/** True once the crawler halted because of a failure (not via stop() or a lost lease). */
|
|
112
|
+
haltedWithError() {
|
|
113
|
+
return !this.running && this.finalStatus === 'error';
|
|
114
|
+
}
|
|
115
|
+
/** Source ingested from right now, or null while not running (a crawl degraded to pagination still advances the cursor). */
|
|
116
|
+
getActiveSource() {
|
|
117
|
+
return this.running ? this.activeSource : null;
|
|
118
|
+
}
|
|
76
119
|
/**
|
|
77
120
|
* Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
|
|
78
121
|
* Refuses to start without a resume point: an explicit configured start block or an
|
|
@@ -102,6 +145,39 @@ class CardanoCrawler {
|
|
|
102
145
|
}
|
|
103
146
|
}
|
|
104
147
|
this.running = true;
|
|
148
|
+
// Hand the analytics coverage to the indexer before the first block is written.
|
|
149
|
+
this.indexer.configureCrawlCoverage({
|
|
150
|
+
assetHistory: this.config.assetHistory,
|
|
151
|
+
assetCatalogue: this.config.assetCatalogue,
|
|
152
|
+
assetEnrichRate: this.config.assetEnrichRate,
|
|
153
|
+
certificates: this.config.certificates,
|
|
154
|
+
utxoSet: this.config.utxoSet,
|
|
155
|
+
});
|
|
156
|
+
// Ledger state is only ever applied from a known anchor — no snapshot, no writes.
|
|
157
|
+
if (this.config.utxoSet) {
|
|
158
|
+
const u = cursor.utxoSet;
|
|
159
|
+
// Blocks crawled while the mode was off never reached the ledger tables: the cursor is
|
|
160
|
+
// ahead of the last applied slot and the set cannot be caught up — invalidate it.
|
|
161
|
+
const lastApplied = u.appliedSlot ?? u.anchorSlot;
|
|
162
|
+
if (u.status === 'active' && lastApplied != null && cursor.lastSlot > lastApplied) {
|
|
163
|
+
const error = `cursor at slot ${cursor.lastSlot} is past the last ledger-applied slot ${lastApplied} — blocks were crawled without the set; re-import`;
|
|
164
|
+
await cds_1.default.tx((tx) => (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error }));
|
|
165
|
+
u.status = 'invalid';
|
|
166
|
+
u.error = error;
|
|
167
|
+
}
|
|
168
|
+
if (u.status === 'active' && u.anchorSlot != null && u.anchorHash) {
|
|
169
|
+
this.indexer.setUtxoAnchor({ slot: u.anchorSlot, hash: u.anchorHash });
|
|
170
|
+
logger.info(`UTxO set active from anchor ${u.anchorSlot}/${u.anchorHash} — ledger tables are maintained`);
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
this.indexer.setUtxoAnchor(null);
|
|
174
|
+
logger.error(`crawler.utxoSet is enabled but the UTxO set is "${u.status}"${u.error ? ` (${u.error})` : ''} — ` +
|
|
175
|
+
'ledger tables are not maintained until importUtxoSet has run (pause the crawler first)');
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
this.indexer.setUtxoAnchor(null);
|
|
180
|
+
}
|
|
105
181
|
this.startLeaseHeartbeat();
|
|
106
182
|
// A pipeline crash (e.g. chain-sync intersection not found after downtime) must
|
|
107
183
|
// surface on the cursor — otherwise the crawler looks healthy while doing nothing.
|
|
@@ -116,10 +192,8 @@ class CardanoCrawler {
|
|
|
116
192
|
});
|
|
117
193
|
}
|
|
118
194
|
/**
|
|
119
|
-
* Stop crawling and
|
|
120
|
-
*
|
|
121
|
-
* final status, then awaits the detached pipeline so callers (shutdownAppContext)
|
|
122
|
-
* can safely tear down backends/DB afterwards.
|
|
195
|
+
* Stop crawling and await the pipeline's in-flight step, so callers can tear down
|
|
196
|
+
* backends/DB afterwards.
|
|
123
197
|
*/
|
|
124
198
|
async stop(finalStatus = 'stopped') {
|
|
125
199
|
this.beginHalt(finalStatus);
|
|
@@ -128,24 +202,14 @@ class CardanoCrawler {
|
|
|
128
202
|
this.pipeline = null;
|
|
129
203
|
}
|
|
130
204
|
/**
|
|
131
|
-
* Halt without awaiting the pipeline —
|
|
132
|
-
*
|
|
133
|
-
*
|
|
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.
|
|
205
|
+
* Halt without awaiting the pipeline — safe to call from inside it.
|
|
206
|
+
* @param latch clears `desiredRunning` so no restart brings the crawler back; only for failures
|
|
207
|
+
* a restart cannot fix (misconfiguration, missing resume point), never for runtime outages.
|
|
141
208
|
*/
|
|
142
209
|
async halt(finalStatus = 'stopped', latch = false) {
|
|
143
210
|
this.beginHalt(finalStatus, latch);
|
|
144
211
|
}
|
|
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
|
-
*/
|
|
212
|
+
/** Start teardown without awaiting it, so tracked callbacks can halt from inside themselves. */
|
|
149
213
|
beginHalt(finalStatus, latch = false) {
|
|
150
214
|
if (latch)
|
|
151
215
|
this.latchOnHalt = true;
|
|
@@ -153,7 +217,12 @@ class CardanoCrawler {
|
|
|
153
217
|
if (this.finalStatus !== 'error' || finalStatus === 'error')
|
|
154
218
|
this.finalStatus = finalStatus;
|
|
155
219
|
this.running = false;
|
|
220
|
+
this.activeSource = null;
|
|
221
|
+
// Background asset enrichment belongs to the crawl — it must not outlive it.
|
|
222
|
+
this.indexer.stopAssetEnrichment();
|
|
156
223
|
this.wake?.(); // cancel a pending poll sleep so the loop exits now
|
|
224
|
+
this.stopChainSyncProbing();
|
|
225
|
+
this.streamEnded?.(); // release the ingest loop — beginHalt awaits the pipeline below
|
|
157
226
|
this.leaseWake?.();
|
|
158
227
|
for (const cancel of [...this.callCancels])
|
|
159
228
|
cancel();
|
|
@@ -180,6 +249,8 @@ class CardanoCrawler {
|
|
|
180
249
|
}
|
|
181
250
|
if (this.leaseHeartbeat)
|
|
182
251
|
await this.leaseHeartbeat.catch(() => undefined);
|
|
252
|
+
if (this.chainSyncProbe)
|
|
253
|
+
await this.chainSyncProbe.catch(() => undefined);
|
|
183
254
|
try {
|
|
184
255
|
if (this.leaseOwner && this.leaseHeld) {
|
|
185
256
|
await cds_1.default.tx((tx) => (0, sync_state_1.releaseCrawlerLease)(tx, this.leaseOwner, this.finalStatus, this.latchOnHalt));
|
|
@@ -193,19 +264,81 @@ class CardanoCrawler {
|
|
|
193
264
|
});
|
|
194
265
|
}
|
|
195
266
|
async runIngestPipeline() {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
267
|
+
while (this.running) {
|
|
268
|
+
const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
|
|
269
|
+
if (chainSync) {
|
|
270
|
+
// One pass per chain-sync stream. An unparseable frame ends the stream, not the crawler:
|
|
271
|
+
// pagination fetches that block, then chain-sync takes over again. Other errors halt.
|
|
272
|
+
while (this.running) {
|
|
273
|
+
const streamEnd = new Promise((resolve) => { this.streamEnded = resolve; });
|
|
274
|
+
await this.runChainSync(chainSync);
|
|
275
|
+
if (!this.chainSyncHandle)
|
|
276
|
+
return; // open refused, halted, or stop() raced us
|
|
277
|
+
await streamEnd;
|
|
278
|
+
const failure = this.takeFrameFailure();
|
|
279
|
+
if (!this.running || failure?.height == null)
|
|
280
|
+
return;
|
|
281
|
+
logger.warn(`chain-sync cannot deliver block ${failure.height} — switching to pagination until it is behind the cursor`);
|
|
282
|
+
await this.runPagination({ untilHeight: failure.height + 1 });
|
|
283
|
+
}
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (this.config.source === 'ogmios') {
|
|
287
|
+
// 'ogmios' means chain-sync ONLY — never silently degrade to the weaker
|
|
288
|
+
// pagination reorg handling the operator explicitly opted out of.
|
|
289
|
+
logger.error("Crawler source is 'ogmios' but no chain-sync backend is available — crawler not started (use source 'auto' to allow pagination fallback).");
|
|
290
|
+
await this.halt('error', true); // config error: a restart cannot fix it
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (this.config.source === 'pagination') {
|
|
294
|
+
await this.runPagination();
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
// 'auto' with no usable chain-sync backend (typical while the node still replays after a
|
|
298
|
+
// restart): crawl on pagination and keep retrying chain-sync.
|
|
299
|
+
logger.warn('No chain-sync backend usable — crawling on pagination and retrying chain-sync periodically');
|
|
300
|
+
await this.runPagination({ untilChainSync: true });
|
|
301
|
+
// Returned because chain-sync came back (or we stopped): the loop reopens it.
|
|
200
302
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Retry the init of a chain-sync backend on its own timer (a poll sleep can be an hour long),
|
|
306
|
+
* one probe at a time. On success `chainSyncRecovered` is set and a pending sleep is cut short;
|
|
307
|
+
* the pagination loop leaves at its next check and the ingest loop reopens chain-sync.
|
|
308
|
+
*/
|
|
309
|
+
startChainSyncProbing() {
|
|
310
|
+
this.chainSyncRecovered = false;
|
|
311
|
+
// The startup init has only just failed — give the node a full interval first.
|
|
312
|
+
this.scheduleChainSyncProbe();
|
|
313
|
+
}
|
|
314
|
+
scheduleChainSyncProbe() {
|
|
315
|
+
if (!this.running || this.chainSyncRecovered || this.chainSyncProbeTimer)
|
|
206
316
|
return;
|
|
207
|
-
|
|
208
|
-
|
|
317
|
+
const timer = setTimeout(() => {
|
|
318
|
+
this.chainSyncProbeTimer = null;
|
|
319
|
+
if (!this.running || this.chainSyncRecovered)
|
|
320
|
+
return;
|
|
321
|
+
this.chainSyncProbe = this.client.recoverChainSyncBackend()
|
|
322
|
+
.then((backend) => {
|
|
323
|
+
if (!backend || !this.running)
|
|
324
|
+
return;
|
|
325
|
+
this.chainSyncRecovered = true;
|
|
326
|
+
this.wake?.(); // a poll sleep must not hold the handover back
|
|
327
|
+
})
|
|
328
|
+
.catch((err) => logger.debug('chain-sync probe failed:', err))
|
|
329
|
+
.finally(() => {
|
|
330
|
+
this.chainSyncProbe = null;
|
|
331
|
+
this.scheduleChainSyncProbe();
|
|
332
|
+
});
|
|
333
|
+
}, CardanoCrawler.CHAIN_SYNC_RETRY_MS);
|
|
334
|
+
timer.unref?.(); // never keep the process alive for a probe
|
|
335
|
+
this.chainSyncProbeTimer = timer;
|
|
336
|
+
}
|
|
337
|
+
stopChainSyncProbing() {
|
|
338
|
+
if (!this.chainSyncProbeTimer)
|
|
339
|
+
return;
|
|
340
|
+
clearTimeout(this.chainSyncProbeTimer);
|
|
341
|
+
this.chainSyncProbeTimer = null;
|
|
209
342
|
}
|
|
210
343
|
/** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
|
|
211
344
|
withTimeout(p, label, ms = CardanoCrawler.CALL_TIMEOUT_MS) {
|
|
@@ -262,6 +395,12 @@ class CardanoCrawler {
|
|
|
262
395
|
onError: (err) => this.trackCallback(async () => {
|
|
263
396
|
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
|
|
264
397
|
return;
|
|
398
|
+
// A frame the client's parser cannot handle is a fault of that one block, not of the
|
|
399
|
+
// crawler or the node — pagination can still fetch it, so degrade instead of halting.
|
|
400
|
+
if (err instanceof errors_1.ChainSyncFrameError && this.canDegradeToPagination(err)) {
|
|
401
|
+
await this.degradeToPagination(err);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
265
404
|
// The stream is stalled (mapping/callback failure) — record and halt cleanly
|
|
266
405
|
// so the cursor status shows 'error' instead of a healthy-looking hang.
|
|
267
406
|
const streak = await this.recordCrawlerError(err);
|
|
@@ -278,19 +417,52 @@ class CardanoCrawler {
|
|
|
278
417
|
return;
|
|
279
418
|
}
|
|
280
419
|
this.chainSyncHandle = handle;
|
|
420
|
+
this.activeSource = 'chain-sync';
|
|
281
421
|
logger.info(`Crawler running (chain-sync) from ${points[0].hash} (+${points.length - 1} fallback intersection point(s))`);
|
|
282
422
|
}
|
|
423
|
+
/** Read and clear the pending frame failure, so each stream starts from a clean slate. */
|
|
424
|
+
takeFrameFailure() {
|
|
425
|
+
const failure = this.frameFailure;
|
|
426
|
+
this.frameFailure = null;
|
|
427
|
+
return failure;
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Whether an unparseable frame can be worked around over HTTP: needs a height, a paginating
|
|
431
|
+
* backend, and a source not pinned to 'ogmios' (chain-sync only).
|
|
432
|
+
*/
|
|
433
|
+
canDegradeToPagination(err) {
|
|
434
|
+
return err.height != null
|
|
435
|
+
&& this.config.source !== 'ogmios'
|
|
436
|
+
&& !!this.client.getPaginatingBackend();
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* End the chain-sync stream and hand back to the ingest loop, which continues on pagination
|
|
440
|
+
* past the offending block. The error is recorded first so `lastError` names the block.
|
|
441
|
+
*/
|
|
442
|
+
async degradeToPagination(err) {
|
|
443
|
+
const streak = await this.recordCrawlerError(err);
|
|
444
|
+
if (streak < 0) {
|
|
445
|
+
await this.halt('stopped');
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
logger.error('Chain-sync frame unusable — continuing on pagination:', err.message);
|
|
449
|
+
this.frameFailure = err;
|
|
450
|
+
const handle = this.chainSyncHandle;
|
|
451
|
+
this.chainSyncHandle = null;
|
|
452
|
+
if (handle) {
|
|
453
|
+
try {
|
|
454
|
+
await handle.close();
|
|
455
|
+
}
|
|
456
|
+
catch (e) {
|
|
457
|
+
logger.warn('chain-sync close failed:', e);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
this.streamEnded?.();
|
|
461
|
+
}
|
|
283
462
|
/**
|
|
284
|
-
* Candidate intersection points,
|
|
285
|
-
*
|
|
286
|
-
*
|
|
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.
|
|
463
|
+
* Candidate intersection points, newest first: the cursor, a ladder of already-crawled
|
|
464
|
+
* ancestors, then the configured start block. If the cursor's block was orphaned while the
|
|
465
|
+
* crawler was down, the node intersects at the last common ancestor and reports a rollBackward.
|
|
294
466
|
*/
|
|
295
467
|
async buildIntersectionPoints(cursor) {
|
|
296
468
|
const points = [];
|
|
@@ -303,11 +475,8 @@ class CardanoCrawler {
|
|
|
303
475
|
};
|
|
304
476
|
if (cursor?.lastBlockHash) {
|
|
305
477
|
add({ slot: cursor.lastSlot, hash: cursor.lastBlockHash, height: cursor.lastHeight });
|
|
306
|
-
// Dense over the last DENSE_DEPTH blocks
|
|
307
|
-
//
|
|
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.
|
|
478
|
+
// Dense over the last DENSE_DEPTH blocks (real rollbacks are shallow and must intersect
|
|
479
|
+
// exactly), doubling after that for deep-reorg reach without hundreds of points.
|
|
311
480
|
const DENSE_DEPTH = 10;
|
|
312
481
|
const heights = [];
|
|
313
482
|
const pushHeight = (height) => { if (height > 0 && !heights.includes(height))
|
|
@@ -339,27 +508,51 @@ class CardanoCrawler {
|
|
|
339
508
|
// ---------------------------------------------------------------------------
|
|
340
509
|
// Pagination (Blockfrost/Koios) — fallback
|
|
341
510
|
// ---------------------------------------------------------------------------
|
|
342
|
-
|
|
511
|
+
/**
|
|
512
|
+
* @param untilHeight return once the cursor reaches it — walks past a block chain-sync
|
|
513
|
+
* cannot deliver, then hands back.
|
|
514
|
+
* @param untilChainSync retry a chain-sync backend in the background; return once one is usable.
|
|
515
|
+
*/
|
|
516
|
+
async runPagination(opts = {}) {
|
|
517
|
+
if (opts.untilChainSync)
|
|
518
|
+
this.startChainSyncProbing();
|
|
519
|
+
try {
|
|
520
|
+
await this.paginate(opts);
|
|
521
|
+
}
|
|
522
|
+
finally {
|
|
523
|
+
this.stopChainSyncProbing();
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
async paginate({ untilHeight, untilChainSync = false }) {
|
|
343
527
|
const backend = this.client.getPaginatingBackend();
|
|
344
528
|
if (!backend) {
|
|
345
529
|
logger.error('No paginating backend available — cannot crawl without Ogmios or Blockfrost/Koios');
|
|
346
530
|
await this.halt('error', true); // config error: a restart cannot fix it
|
|
347
531
|
return;
|
|
348
532
|
}
|
|
533
|
+
backend.configureCrawl?.({ certificates: this.config.certificates });
|
|
534
|
+
this.activeSource = 'pagination';
|
|
349
535
|
logger.info('Crawler running (pagination)');
|
|
350
|
-
// Tip cache
|
|
351
|
-
//
|
|
352
|
-
// per batch. Refresh only when the cursor reaches the cached target.
|
|
536
|
+
// Tip cache, refreshed only when the cursor reaches the cached target; during catch-up
|
|
537
|
+
// the exact tip is irrelevant.
|
|
353
538
|
let tip = null;
|
|
354
539
|
let target = Number.NEGATIVE_INFINITY;
|
|
355
540
|
while (this.running) {
|
|
356
541
|
try {
|
|
542
|
+
if (untilChainSync && this.chainSyncRecovered) {
|
|
543
|
+
logger.info('chain-sync backend usable again — leaving pagination');
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
357
546
|
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
358
547
|
if (!cursor?.lastBlockHash) {
|
|
359
548
|
logger.error('Pagination refused: cursor has no resume block hash.');
|
|
360
549
|
await this.halt('error', true); // broken precondition: a restart cannot fix it
|
|
361
550
|
return;
|
|
362
551
|
}
|
|
552
|
+
if (untilHeight != null && cursor.lastHeight >= untilHeight) {
|
|
553
|
+
logger.info(`pagination reached block ${cursor.lastHeight} — handing back to chain-sync`);
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
363
556
|
if (!tip || cursor.lastHeight >= target) {
|
|
364
557
|
tip = await this.withTimeout(this.client.getLatestBlock(), 'getLatestBlock');
|
|
365
558
|
target = (tip.height ?? 0) - this.config.confirmationDepth;
|
|
@@ -381,7 +574,7 @@ class CardanoCrawler {
|
|
|
381
574
|
await this.halt('stopped');
|
|
382
575
|
return;
|
|
383
576
|
}
|
|
384
|
-
await this.
|
|
577
|
+
await this.pollPause(untilChainSync);
|
|
385
578
|
continue;
|
|
386
579
|
}
|
|
387
580
|
const blocks = await this.withTimeout(
|
|
@@ -389,7 +582,7 @@ class CardanoCrawler {
|
|
|
389
582
|
// on a fresh start without configured startHeight)
|
|
390
583
|
backend.getNextBlocks(cursor.lastBlockHash, this.config.batchSize, cursor.lastHeight > 0 ? cursor.lastHeight : undefined), 'getNextBlocks');
|
|
391
584
|
if (!blocks.length) {
|
|
392
|
-
await this.
|
|
585
|
+
await this.pollPause(untilChainSync);
|
|
393
586
|
continue;
|
|
394
587
|
}
|
|
395
588
|
for (const block of blocks) {
|
|
@@ -401,6 +594,10 @@ class CardanoCrawler {
|
|
|
401
594
|
const ok = await this.persistBlock(block, txs, tipPoint);
|
|
402
595
|
if (!ok)
|
|
403
596
|
return; // persistBlock already recorded + halted
|
|
597
|
+
// Chain-sync came back mid-batch: the block just written is complete and on the
|
|
598
|
+
// cursor, the rest of the batch is cheaper to stream than to fetch one by one.
|
|
599
|
+
if (untilChainSync && this.chainSyncRecovered)
|
|
600
|
+
break;
|
|
404
601
|
}
|
|
405
602
|
}
|
|
406
603
|
catch (err) {
|
|
@@ -426,10 +623,19 @@ class CardanoCrawler {
|
|
|
426
623
|
await this.halt('error');
|
|
427
624
|
return;
|
|
428
625
|
}
|
|
429
|
-
await this.
|
|
626
|
+
await this.pollPause(untilChainSync);
|
|
430
627
|
}
|
|
431
628
|
}
|
|
432
629
|
}
|
|
630
|
+
/**
|
|
631
|
+
* Poll pause between pagination rounds; skipped when a chain-sync handover is already due,
|
|
632
|
+
* since the probe's wake-up only reaches a sleep that has begun.
|
|
633
|
+
*/
|
|
634
|
+
async pollPause(untilChainSync) {
|
|
635
|
+
if (untilChainSync && this.chainSyncRecovered)
|
|
636
|
+
return;
|
|
637
|
+
await this.sleep(this.config.pollIntervalMs);
|
|
638
|
+
}
|
|
433
639
|
/**
|
|
434
640
|
* Pagination reorg recovery: walk back by height comparing the on-chain block hash with
|
|
435
641
|
* our stored one until they agree — that height is the fork point. If the last-indexed
|
|
@@ -461,10 +667,8 @@ class CardanoCrawler {
|
|
|
461
667
|
if (ours?.hash && onChain.hash === ours.hash) {
|
|
462
668
|
if (h === cursor.lastHeight)
|
|
463
669
|
return false; // tip still matches → not a reorg
|
|
464
|
-
//
|
|
465
|
-
//
|
|
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.)
|
|
670
|
+
// A null provider slot would make forkSlot 0 and wipe the entire crawled dataset —
|
|
671
|
+
// abort this round instead.
|
|
468
672
|
if (onChain.slot == null)
|
|
469
673
|
return false;
|
|
470
674
|
await this.handleReorg({ slot: onChain.slot, hash: onChain.hash, height: h });
|
|
@@ -477,10 +681,8 @@ class CardanoCrawler {
|
|
|
477
681
|
// Persist + reorg (shared)
|
|
478
682
|
// ---------------------------------------------------------------------------
|
|
479
683
|
/**
|
|
480
|
-
* Persist one block atomically and advance the cursor. Transient failures are retried
|
|
481
|
-
*
|
|
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.
|
|
684
|
+
* Persist one block atomically and advance the cursor. Transient failures are retried; the
|
|
685
|
+
* cursor is not advanced on failure, so a resume re-syncs from it. Marks 'synced' at the tip.
|
|
484
686
|
* @returns true when the block was persisted, false when the crawler was stopped
|
|
485
687
|
*/
|
|
486
688
|
async persistBlock(block, txs, tip) {
|
|
@@ -504,8 +706,20 @@ class CardanoCrawler {
|
|
|
504
706
|
throw new CrawlerLeaseLostError();
|
|
505
707
|
}
|
|
506
708
|
await this.indexer.indexBlockFull(tx, block, txs);
|
|
507
|
-
|
|
709
|
+
// Ledger progress marker: written in the same statement as the cursor, so "the
|
|
710
|
+
// cursor is ahead of the marker" always means blocks went by without the set.
|
|
711
|
+
const anchor = this.indexer.getUtxoAnchor();
|
|
712
|
+
const ledgerApplied = anchor != null && (block.slot ?? 0) > anchor.slot;
|
|
713
|
+
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', ledgerApplied ? { utxoAppliedSlot: block.slot ?? 0 } : undefined);
|
|
508
714
|
});
|
|
715
|
+
if (CardanoCrawler.poison?.hash === block.hash)
|
|
716
|
+
CardanoCrawler.poison = null;
|
|
717
|
+
// A ledger invalidation decided inside the block transaction takes effect in memory
|
|
718
|
+
// only now, after the commit that carries it — a rolled-back attempt changes nothing.
|
|
719
|
+
const invalidation = this.indexer.takeLedgerInvalidation();
|
|
720
|
+
if (invalidation) {
|
|
721
|
+
logger.error(`UTxO set invalidated: ${invalidation} — ledger tables stop updating until importUtxoSet runs again`);
|
|
722
|
+
}
|
|
509
723
|
// Notify observers (wallet-worker confirmation tracker) AFTER the commit —
|
|
510
724
|
// listener failures are swallowed inside emitBlockIndexed.
|
|
511
725
|
(0, hooks_1.emitBlockIndexed)({
|
|
@@ -516,6 +730,7 @@ class CardanoCrawler {
|
|
|
516
730
|
tipSlot: tip?.slot ?? null,
|
|
517
731
|
tipHeight: tip?.height ?? null,
|
|
518
732
|
});
|
|
733
|
+
this.maybeSnapshotEpoch(block, tip);
|
|
519
734
|
return true;
|
|
520
735
|
}
|
|
521
736
|
catch (err) {
|
|
@@ -534,27 +749,90 @@ class CardanoCrawler {
|
|
|
534
749
|
await this.sleep(1000 * attempt);
|
|
535
750
|
continue;
|
|
536
751
|
}
|
|
537
|
-
|
|
752
|
+
const dataRejection = CardanoCrawler.isDataRejection(err);
|
|
753
|
+
const failures = dataRejection ? CardanoCrawler.notePersistFailure(block.hash) : 0;
|
|
754
|
+
if (failures >= CardanoCrawler.POISON_BLOCK_THRESHOLD) {
|
|
755
|
+
const cause = err instanceof Error ? err.message : String(err);
|
|
756
|
+
const message = `poison block ${block.hash} @${block.height ?? '?'} failed ${failures}x: ${cause}`;
|
|
757
|
+
logger.error(`persistBlock failed for ${block.hash} (height ${block.height}) ${failures}x across restarts — poison block, latching the crawler off. Fix the cause, then resumeCrawler():`, err);
|
|
758
|
+
// Lease-independent on purpose (see latchPoisonBlock); the memory is only forgotten
|
|
759
|
+
// once the latch is durable, so a failed write is retried after the next restart.
|
|
760
|
+
const latched = await cds_1.default.tx((tx) => (0, sync_state_1.latchPoisonBlock)(tx, message)).then(() => true, (e) => { logger.error('poison-block latch could not be written — retried after the next restart:', e); return false; });
|
|
761
|
+
if (latched)
|
|
762
|
+
CardanoCrawler.poison = null;
|
|
763
|
+
await this.halt('error', true);
|
|
764
|
+
return false;
|
|
765
|
+
}
|
|
766
|
+
const perBlock = dataRejection ? ` (${failures}/${CardanoCrawler.POISON_BLOCK_THRESHOLD} for this block)` : '';
|
|
767
|
+
logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts${perBlock} — stopping crawler (resume re-syncs from cursor):`, err);
|
|
538
768
|
await this.halt('error');
|
|
539
769
|
return false;
|
|
540
770
|
}
|
|
541
771
|
}
|
|
542
772
|
}
|
|
773
|
+
/** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
|
|
774
|
+
epochOfSlot(slot) {
|
|
775
|
+
const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network]
|
|
776
|
+
?? const_1.EPOCH_CONFIG_BY_NETWORK.preview;
|
|
777
|
+
return cfg.shelleyStartEpoch + Math.floor((slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* Pool/DRep snapshot once per epoch, detached from the triggering block and ONLY at the tip:
|
|
781
|
+
* the enumerating providers report current state (no epoch parameter), so epochs passed
|
|
782
|
+
* during a backfill are skipped permanently. Authority is the `PoolEpochSnapshots` row.
|
|
783
|
+
*/
|
|
784
|
+
maybeSnapshotEpoch(block, tip) {
|
|
785
|
+
if (!this.config.epochSnapshots || block.epoch == null)
|
|
786
|
+
return;
|
|
787
|
+
if (this.snapshotedEpoch === block.epoch || this.snapshotInFlight)
|
|
788
|
+
return;
|
|
789
|
+
// No tip reported = we cannot prove we are live, so we do not pretend to be.
|
|
790
|
+
if (tip == null) {
|
|
791
|
+
logger.debug(`epoch ${block.epoch} snapshot skipped: no chain tip reported for this block`);
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
const tipEpoch = this.epochOfSlot(tip.slot);
|
|
795
|
+
if (block.epoch !== tipEpoch) {
|
|
796
|
+
logger.debug(`epoch ${block.epoch} snapshot skipped: still backfilling (tip is in epoch ${tipEpoch}) — ` +
|
|
797
|
+
`the pool/DRep set can only be observed as it is now, never as it was`);
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
if (Date.now() < this.snapshotRetryAfter)
|
|
801
|
+
return;
|
|
802
|
+
const epoch = block.epoch;
|
|
803
|
+
const at = { slot: block.slot ?? 0, time: block.time ?? 0 };
|
|
804
|
+
this.snapshotInFlight = this.trackCallback(async () => {
|
|
805
|
+
const existing = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.PoolEpochSnapshots).columns('epoch').where({ epoch })));
|
|
806
|
+
if (!existing) {
|
|
807
|
+
await this.withTimeout(this.indexer.snapshotEpoch(epoch, at), `snapshotEpoch(${epoch})`, CardanoCrawler.SNAPSHOT_TIMEOUT_MS);
|
|
808
|
+
}
|
|
809
|
+
this.snapshotedEpoch = epoch;
|
|
810
|
+
this.snapshotFailures = 0;
|
|
811
|
+
this.snapshotRetryAfter = 0;
|
|
812
|
+
})
|
|
813
|
+
.catch((err) => {
|
|
814
|
+
// Never fatal: the crawl keeps its data, the epoch is retried on a later block —
|
|
815
|
+
// but not on the very next one, or an outage would re-enumerate per block.
|
|
816
|
+
this.snapshotFailures++;
|
|
817
|
+
const backoff = Math.min(CardanoCrawler.SNAPSHOT_RETRY_BASE_MS * 2 ** (this.snapshotFailures - 1), CardanoCrawler.SNAPSHOT_RETRY_MAX_MS);
|
|
818
|
+
this.snapshotRetryAfter = Date.now() + backoff;
|
|
819
|
+
if (this.running)
|
|
820
|
+
logger.error(`epoch ${epoch} snapshot failed (retry in ${backoff} ms):`, err);
|
|
821
|
+
})
|
|
822
|
+
.finally(() => { this.snapshotInFlight = null; });
|
|
823
|
+
}
|
|
543
824
|
/**
|
|
544
|
-
*
|
|
545
|
-
*
|
|
546
|
-
* the cursor to the fork
|
|
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.
|
|
825
|
+
* Chain rollback in one transaction: delete blocks with slot > fork (absolute-slot axis, never
|
|
826
|
+
* height), their transactions resolved via blockHash (lazily indexed txs of other blocks are
|
|
827
|
+
* untouched), reset the cursor to the fork and write a CardanoReorgLog row.
|
|
552
828
|
*/
|
|
553
829
|
async handleReorg(point) {
|
|
554
830
|
const forkSlot = point === 'origin' ? (this.config.startSlot ?? 0) : point.slot;
|
|
555
831
|
let blocksRolledBack = 0;
|
|
556
832
|
let txsRolledBack = 0;
|
|
557
833
|
let emittedForkHeight = null;
|
|
834
|
+
const rolledBackTxHashes = [];
|
|
835
|
+
let ledgerInvalidated = false;
|
|
558
836
|
try {
|
|
559
837
|
await cds_1.default.tx(async (tx) => {
|
|
560
838
|
if (this.leaseOwner) {
|
|
@@ -577,9 +855,10 @@ class CardanoCrawler {
|
|
|
577
855
|
for (const blockChunk of (0, collections_1.chunk)(blockHashes, collections_1.IN_CHUNK)) {
|
|
578
856
|
// Only transactions of the rolled-back blocks — resolved via blockHash, so
|
|
579
857
|
// 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 } }));
|
|
858
|
+
const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ blockHash: { in: blockChunk } }));
|
|
581
859
|
const txHashes = staleTxs.map((t) => t.hash);
|
|
582
860
|
txsRolledBack += txHashes.length;
|
|
861
|
+
rolledBackTxHashes.push(...txHashes);
|
|
583
862
|
for (const txChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
|
|
584
863
|
// These denormalized/lazy indexes have no generated FK cascades. Remove
|
|
585
864
|
// them before their parent tx/output rows so orphan data cannot leak via OData.
|
|
@@ -587,15 +866,28 @@ class CardanoCrawler {
|
|
|
587
866
|
await tx.run(DELETE.from(cardano_1.AddressUTxOs).where({ hash: { in: txChunk } }));
|
|
588
867
|
await tx.run(DELETE.from(cardano_1.AddressTransactions).where({ tx_hash: { in: txChunk } }));
|
|
589
868
|
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
869
|
}
|
|
870
|
+
await (0, transaction_rows_1.deleteTransactionRows)(tx, staleTxs);
|
|
597
871
|
await tx.run(DELETE.from(cardano_1.Blocks).where({ hash: { in: blockChunk } }));
|
|
598
872
|
}
|
|
873
|
+
// Ledger state, driven by the PERSISTED status: a fork after the anchor is undone and the
|
|
874
|
+
// progress marker follows the cursor back; a fork before the anchor invalidates the set.
|
|
875
|
+
const persisted = (await (0, sync_state_1.readCursor)(tx))?.utxoSet;
|
|
876
|
+
if (persisted?.status === 'active' && persisted.anchorSlot != null) {
|
|
877
|
+
if (forkSlot < persisted.anchorSlot) {
|
|
878
|
+
await (0, sync_state_1.setUtxoSetState)(tx, {
|
|
879
|
+
status: 'invalid',
|
|
880
|
+
error: `reorg to slot ${forkSlot} before the UTxO set anchor ${persisted.anchorSlot} — re-import the set`,
|
|
881
|
+
});
|
|
882
|
+
ledgerInvalidated = true;
|
|
883
|
+
}
|
|
884
|
+
else {
|
|
885
|
+
await (0, ledger_state_1.undoLedgerForTransactions)(tx, rolledBackTxHashes);
|
|
886
|
+
if (persisted.appliedSlot != null && persisted.appliedSlot > forkSlot) {
|
|
887
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { appliedSlot: forkSlot });
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
}
|
|
599
891
|
await (0, sync_state_1.resetCursorTo)(tx, point === 'origin'
|
|
600
892
|
? { slot: forkSlot, hash: this.config.startBlockHash ?? '', height: 0 }
|
|
601
893
|
: { slot: point.slot, hash: point.hash, height: forkHeight ?? 0 });
|
|
@@ -618,6 +910,10 @@ class CardanoCrawler {
|
|
|
618
910
|
}
|
|
619
911
|
throw err;
|
|
620
912
|
}
|
|
913
|
+
if (ledgerInvalidated) {
|
|
914
|
+
this.indexer.setUtxoAnchor(null);
|
|
915
|
+
logger.error(`UTxO set invalidated: reorg to slot ${forkSlot} reaches behind the anchor — ledger tables stop updating until importUtxoSet runs again`);
|
|
916
|
+
}
|
|
621
917
|
// Notify observers (wallet-worker confirmation tracker + CAP subscribers) AFTER
|
|
622
918
|
// the rollback commit.
|
|
623
919
|
(0, hooks_1.emitReorg)({ forkSlot, forkHeight: emittedForkHeight, blocksRolledBack });
|
|
@@ -650,6 +946,24 @@ class CardanoCrawler {
|
|
|
650
946
|
}
|
|
651
947
|
})();
|
|
652
948
|
}
|
|
949
|
+
/** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
|
|
950
|
+
static isDataRejection(err) {
|
|
951
|
+
// RangeError: BigInt / number conversions in the mappers; SyntaxError: JSON of the block
|
|
952
|
+
if (err instanceof RangeError || err instanceof SyntaxError)
|
|
953
|
+
return true;
|
|
954
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
955
|
+
return CardanoCrawler.DATA_REJECTION_PATTERNS.some((p) => p.test(message));
|
|
956
|
+
}
|
|
957
|
+
/** Count final persist failures per block hash (a different hash resets the count). */
|
|
958
|
+
static notePersistFailure(hash) {
|
|
959
|
+
const p = CardanoCrawler.poison;
|
|
960
|
+
CardanoCrawler.poison = p && p.hash === hash ? { hash, failures: p.failures + 1 } : { hash, failures: 1 };
|
|
961
|
+
return CardanoCrawler.poison.failures;
|
|
962
|
+
}
|
|
963
|
+
/** Test seam: forget the poison-block memory (process-wide state). */
|
|
964
|
+
static resetPoisonMemory() {
|
|
965
|
+
CardanoCrawler.poison = null;
|
|
966
|
+
}
|
|
653
967
|
/** Record state only while this instance still owns the lease. */
|
|
654
968
|
async recordCrawlerError(err) {
|
|
655
969
|
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
|