@odatano/core 2.0.0-rc.4 → 2.0.0-rc.40
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/CardanoBackendService/index.d.ts +357 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
- package/@cds-models/CardanoIndexerService/index.js +25 -0
- package/@cds-models/CardanoODataService/index.d.ts +305 -7
- package/@cds-models/CardanoODataService/index.js +34 -0
- package/@cds-models/CardanoSignService/index.d.ts +28 -3
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/index.d.ts +72 -0
- package/@cds-models/index.js +12 -0
- package/@cds-models/odatano/cardano/index.d.ts +408 -7
- package/@cds-models/odatano/cardano/index.js +42 -0
- package/README.md +64 -5
- package/db/schema.cds +2297 -1633
- package/db/types.cds +114 -0
- package/package.json +27 -6
- package/scripts/migrate-slot-leader.mjs +104 -0
- package/scripts/migrate-txseq.mjs +147 -0
- package/src/index.d.ts +18 -11
- package/src/index.js +44 -14
- package/src/plugin.js +42 -52
- package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
- package/srv/blockchain/backends/blockfrost-backend.js +53 -162
- package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
- package/srv/blockchain/backends/cardano-backend.js +19 -5
- package/srv/blockchain/backends/koios-backend.d.ts +126 -60
- package/srv/blockchain/backends/koios-backend.js +376 -235
- package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
- package/srv/blockchain/backends/odatano-backend.js +170 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
- package/srv/blockchain/backends/ogmios-backend.js +556 -201
- 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 +87 -202
- package/srv/blockchain/cardano-client.js +210 -240
- package/srv/blockchain/cardano-indexer.d.ts +311 -242
- package/srv/blockchain/cardano-indexer.js +1238 -362
- package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
- package/srv/blockchain/cardano-tx-builder.js +173 -132
- package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
- package/srv/blockchain/crawler/certificate-backfill.js +169 -0
- package/srv/blockchain/crawler/crawler.d.ts +139 -54
- package/srv/blockchain/crawler/crawler.js +478 -96
- 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 +46 -28
- package/srv/blockchain/crawler/sync-state.js +128 -43
- package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/transaction-backfill.js +283 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
- package/srv/blockchain/crawler/utxo-set-import.js +363 -0
- package/srv/blockchain/ledger-state.d.ts +101 -0
- package/srv/blockchain/ledger-state.js +432 -0
- package/srv/blockchain/pending-spends.d.ts +28 -0
- package/srv/blockchain/pending-spends.js +89 -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 +14 -45
- package/srv/blockchain/signing/signature-verifier.js +73 -76
- package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
- package/srv/blockchain/signing/submission-finalizer.js +16 -49
- package/srv/blockchain/stored-chain.d.ts +33 -0
- package/srv/blockchain/stored-chain.js +234 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
- package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
- package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
- package/srv/blockchain/transaction-building/caller-datums.js +139 -0
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +43 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
- package/srv/blockchain/wallet-worker/build-request.js +18 -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-backend-service.cds +52 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +244 -0
- package/srv/cardano-indexer-service.cds +201 -73
- package/srv/cardano-indexer-service.js +280 -11
- package/srv/cardano-service.cds +65 -2
- package/srv/cardano-service.js +170 -129
- package/srv/cardano-sign-service.cds +200 -180
- package/srv/cardano-sign-service.js +57 -184
- package/srv/cardano-tx-service.cds +439 -370
- package/srv/cardano-tx-service.js +231 -190
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.js +7 -15
- package/srv/cbor/index.d.ts +1 -1
- package/srv/cbor/parse.d.ts +27 -0
- package/srv/cbor/parse.js +63 -2
- package/srv/server.d.ts +28 -86
- package/srv/server.js +132 -135
- 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 +922 -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 +30 -67
- package/srv/utils/const.js +32 -72
- 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 +94 -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 +20 -0
- package/srv/utils/epoch-slots.js +43 -0
- package/srv/utils/error-codes.d.ts +20 -73
- package/srv/utils/error-codes.js +19 -70
- package/srv/utils/errors.d.ts +50 -177
- package/srv/utils/errors.js +94 -218
- package/srv/utils/legacy-service-paths.d.ts +11 -0
- package/srv/utils/legacy-service-paths.js +58 -0
- package/srv/utils/liveness.d.ts +16 -0
- package/srv/utils/liveness.js +40 -0
- package/srv/utils/mappers.d.ts +128 -214
- package/srv/utils/mappers.js +354 -299
- package/srv/utils/network-context.js +2 -11
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +62 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +56 -0
- package/srv/utils/plutus-placeholders.d.ts +23 -16
- package/srv/utils/plutus-placeholders.js +63 -27
- 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 +6 -16
- package/srv/utils/signing-helper.js +36 -60
- package/srv/utils/tx-build-helper.d.ts +28 -93
- package/srv/utils/tx-build-helper.js +75 -124
- package/srv/utils/tx-request-parsers.d.ts +101 -28
- package/srv/utils/tx-request-parsers.js +410 -43
- package/srv/utils/tx-utils.d.ts +4 -23
- package/srv/utils/tx-utils.js +12 -41
- package/srv/utils/types.d.ts +252 -179
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +24 -90
- package/srv/utils/validators.js +50 -147
|
@@ -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,11 +80,29 @@ class CardanoCrawler {
|
|
|
55
80
|
/** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
|
|
56
81
|
inFlightCallbacks = new Set();
|
|
57
82
|
haltPromise = null;
|
|
83
|
+
/** A block chain-sync cannot deliver; the ingest loop fetches it via pagination, then reopens chain-sync. */
|
|
84
|
+
frameFailure = null;
|
|
85
|
+
/** The stream closed after making progress; the ingest loop reopens chain-sync at the cursor. */
|
|
86
|
+
reopenStream = false;
|
|
87
|
+
/** Blocks persisted by the current chain-sync stream. */
|
|
88
|
+
blocksThisStream = 0;
|
|
89
|
+
/** Resolves the ingest loop's wait for the current chain-sync stream to end. */
|
|
90
|
+
streamEnded = null;
|
|
58
91
|
finalStatus = 'stopped';
|
|
59
92
|
/** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
|
|
60
93
|
latchOnHalt = false;
|
|
94
|
+
/** Distance to k at which a block no longer counts as acquirable (the tip moves on while we query). */
|
|
95
|
+
static SNAPSHOT_WINDOW_MARGIN = 10;
|
|
96
|
+
/** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
|
|
97
|
+
snapshotedEpoch = null;
|
|
98
|
+
snapshotInFlight = null;
|
|
99
|
+
/** Consecutive snapshot failures and the earliest time the next attempt may run. */
|
|
100
|
+
snapshotFailures = 0;
|
|
101
|
+
snapshotRetryAfter = 0;
|
|
61
102
|
leaseHeld = false;
|
|
62
103
|
leaseHeartbeat = null;
|
|
104
|
+
/** Last successful lease renewal by a block commit (epoch ms). */
|
|
105
|
+
leaseRenewedAt = 0;
|
|
63
106
|
leaseWake = null;
|
|
64
107
|
constructor(client, indexer, network, config,
|
|
65
108
|
/** Present for production instances created by index.ts; omitted in engine unit tests. */
|
|
@@ -73,6 +116,14 @@ class CardanoCrawler {
|
|
|
73
116
|
isRunning() {
|
|
74
117
|
return this.running;
|
|
75
118
|
}
|
|
119
|
+
/** True once the crawler halted because of a failure (not via stop() or a lost lease). */
|
|
120
|
+
haltedWithError() {
|
|
121
|
+
return !this.running && this.finalStatus === 'error';
|
|
122
|
+
}
|
|
123
|
+
/** Source ingested from right now, or null while not running (a crawl degraded to pagination still advances the cursor). */
|
|
124
|
+
getActiveSource() {
|
|
125
|
+
return this.running ? this.activeSource : null;
|
|
126
|
+
}
|
|
76
127
|
/**
|
|
77
128
|
* Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
|
|
78
129
|
* Refuses to start without a resume point: an explicit configured start block or an
|
|
@@ -102,6 +153,41 @@ class CardanoCrawler {
|
|
|
102
153
|
}
|
|
103
154
|
}
|
|
104
155
|
this.running = true;
|
|
156
|
+
// Hand the analytics coverage to the indexer before the first block is written.
|
|
157
|
+
this.indexer.configureCrawlCoverage({
|
|
158
|
+
assetHistory: this.config.assetHistory,
|
|
159
|
+
assetCatalogue: this.config.assetCatalogue,
|
|
160
|
+
assetEnrichRate: this.config.assetEnrichRate,
|
|
161
|
+
certificates: this.config.certificates,
|
|
162
|
+
utxoSet: this.config.utxoSet,
|
|
163
|
+
authoritative: this.config.authoritative ?? false,
|
|
164
|
+
});
|
|
165
|
+
// Ledger state is only ever applied from a known anchor — no snapshot, no writes.
|
|
166
|
+
if (this.config.utxoSet) {
|
|
167
|
+
const u = cursor.utxoSet;
|
|
168
|
+
// Blocks crawled while the mode was off never reached the ledger tables: the cursor is
|
|
169
|
+
// ahead of the last applied slot and the set cannot be caught up — invalidate it.
|
|
170
|
+
const lastApplied = u.appliedSlot ?? u.anchorSlot;
|
|
171
|
+
if (u.status === 'active' && lastApplied != null && cursor.lastSlot > lastApplied) {
|
|
172
|
+
const error = `cursor at slot ${cursor.lastSlot} is past the last ledger-applied slot ${lastApplied} — blocks were crawled without the set; re-import`;
|
|
173
|
+
await cds_1.default.tx((tx) => (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error }));
|
|
174
|
+
u.status = 'invalid';
|
|
175
|
+
u.error = error;
|
|
176
|
+
}
|
|
177
|
+
if (u.status === 'active' && u.anchorSlot != null && u.anchorHash) {
|
|
178
|
+
this.indexer.setUtxoAnchor({ slot: u.anchorSlot, hash: u.anchorHash });
|
|
179
|
+
void this.indexer.paymentCredentialsReady();
|
|
180
|
+
logger.info(`UTxO set active from anchor ${u.anchorSlot}/${u.anchorHash} — ledger tables are maintained`);
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
this.indexer.setUtxoAnchor(null);
|
|
184
|
+
logger.error(`crawler.utxoSet is enabled but the UTxO set is "${u.status}"${u.error ? ` (${u.error})` : ''} — ` +
|
|
185
|
+
'ledger tables are not maintained until importUtxoSet has run (pause the crawler first)');
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
this.indexer.setUtxoAnchor(null);
|
|
190
|
+
}
|
|
105
191
|
this.startLeaseHeartbeat();
|
|
106
192
|
// A pipeline crash (e.g. chain-sync intersection not found after downtime) must
|
|
107
193
|
// surface on the cursor — otherwise the crawler looks healthy while doing nothing.
|
|
@@ -116,10 +202,8 @@ class CardanoCrawler {
|
|
|
116
202
|
});
|
|
117
203
|
}
|
|
118
204
|
/**
|
|
119
|
-
* Stop crawling and
|
|
120
|
-
*
|
|
121
|
-
* final status, then awaits the detached pipeline so callers (shutdownAppContext)
|
|
122
|
-
* can safely tear down backends/DB afterwards.
|
|
205
|
+
* Stop crawling and await the pipeline's in-flight step, so callers can tear down
|
|
206
|
+
* backends/DB afterwards.
|
|
123
207
|
*/
|
|
124
208
|
async stop(finalStatus = 'stopped') {
|
|
125
209
|
this.beginHalt(finalStatus);
|
|
@@ -128,24 +212,14 @@ class CardanoCrawler {
|
|
|
128
212
|
this.pipeline = null;
|
|
129
213
|
}
|
|
130
214
|
/**
|
|
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.
|
|
215
|
+
* Halt without awaiting the pipeline — safe to call from inside it.
|
|
216
|
+
* @param latch clears `desiredRunning` so no restart brings the crawler back; only for failures
|
|
217
|
+
* a restart cannot fix (misconfiguration, missing resume point), never for runtime outages.
|
|
141
218
|
*/
|
|
142
219
|
async halt(finalStatus = 'stopped', latch = false) {
|
|
143
220
|
this.beginHalt(finalStatus, latch);
|
|
144
221
|
}
|
|
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
|
-
*/
|
|
222
|
+
/** Start teardown without awaiting it, so tracked callbacks can halt from inside themselves. */
|
|
149
223
|
beginHalt(finalStatus, latch = false) {
|
|
150
224
|
if (latch)
|
|
151
225
|
this.latchOnHalt = true;
|
|
@@ -153,7 +227,12 @@ class CardanoCrawler {
|
|
|
153
227
|
if (this.finalStatus !== 'error' || finalStatus === 'error')
|
|
154
228
|
this.finalStatus = finalStatus;
|
|
155
229
|
this.running = false;
|
|
230
|
+
this.activeSource = null;
|
|
231
|
+
// Background asset enrichment belongs to the crawl — it must not outlive it.
|
|
232
|
+
this.indexer.stopAssetEnrichment();
|
|
156
233
|
this.wake?.(); // cancel a pending poll sleep so the loop exits now
|
|
234
|
+
this.stopChainSyncProbing();
|
|
235
|
+
this.streamEnded?.(); // release the ingest loop — beginHalt awaits the pipeline below
|
|
157
236
|
this.leaseWake?.();
|
|
158
237
|
for (const cancel of [...this.callCancels])
|
|
159
238
|
cancel();
|
|
@@ -180,6 +259,8 @@ class CardanoCrawler {
|
|
|
180
259
|
}
|
|
181
260
|
if (this.leaseHeartbeat)
|
|
182
261
|
await this.leaseHeartbeat.catch(() => undefined);
|
|
262
|
+
if (this.chainSyncProbe)
|
|
263
|
+
await this.chainSyncProbe.catch(() => undefined);
|
|
183
264
|
try {
|
|
184
265
|
if (this.leaseOwner && this.leaseHeld) {
|
|
185
266
|
await cds_1.default.tx((tx) => (0, sync_state_1.releaseCrawlerLease)(tx, this.leaseOwner, this.finalStatus, this.latchOnHalt));
|
|
@@ -193,19 +274,87 @@ class CardanoCrawler {
|
|
|
193
274
|
});
|
|
194
275
|
}
|
|
195
276
|
async runIngestPipeline() {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
277
|
+
while (this.running) {
|
|
278
|
+
const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
|
|
279
|
+
if (chainSync) {
|
|
280
|
+
// One pass per chain-sync stream. An unparseable frame ends the stream, not the crawler:
|
|
281
|
+
// pagination fetches that block, then chain-sync takes over again. Other errors halt.
|
|
282
|
+
while (this.running) {
|
|
283
|
+
const streamEnd = new Promise((resolve) => { this.streamEnded = resolve; });
|
|
284
|
+
await this.runChainSync(chainSync);
|
|
285
|
+
if (!this.chainSyncHandle)
|
|
286
|
+
return; // open refused, halted, or stop() raced us
|
|
287
|
+
await streamEnd;
|
|
288
|
+
const failure = this.takeFrameFailure();
|
|
289
|
+
if (!this.running)
|
|
290
|
+
return;
|
|
291
|
+
if (this.reopenStream) {
|
|
292
|
+
this.reopenStream = false;
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
if (failure?.height == null)
|
|
296
|
+
return;
|
|
297
|
+
logger.warn(`chain-sync cannot deliver block ${failure.height} — switching to pagination until it is behind the cursor`);
|
|
298
|
+
await this.runPagination({ untilHeight: failure.height + 1 });
|
|
299
|
+
}
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (this.config.source === 'ogmios') {
|
|
303
|
+
// 'ogmios' means chain-sync ONLY — never silently degrade to the weaker
|
|
304
|
+
// pagination reorg handling the operator explicitly opted out of.
|
|
305
|
+
logger.error("Crawler source is 'ogmios' but no chain-sync backend is available — crawler not started (use source 'auto' to allow pagination fallback).");
|
|
306
|
+
await this.halt('error', true); // config error: a restart cannot fix it
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
if (this.config.source === 'pagination') {
|
|
310
|
+
await this.runPagination();
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
// 'auto' with no usable chain-sync backend (typical while the node still replays after a
|
|
314
|
+
// restart): crawl on pagination and keep retrying chain-sync.
|
|
315
|
+
logger.warn('No chain-sync backend usable — crawling on pagination and retrying chain-sync periodically');
|
|
316
|
+
await this.runPagination({ untilChainSync: true });
|
|
317
|
+
// Returned because chain-sync came back (or we stopped): the loop reopens it.
|
|
200
318
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Retry the init of a chain-sync backend on its own timer (a poll sleep can be an hour long),
|
|
322
|
+
* one probe at a time. On success `chainSyncRecovered` is set and a pending sleep is cut short;
|
|
323
|
+
* the pagination loop leaves at its next check and the ingest loop reopens chain-sync.
|
|
324
|
+
*/
|
|
325
|
+
startChainSyncProbing() {
|
|
326
|
+
this.chainSyncRecovered = false;
|
|
327
|
+
// The startup init has only just failed — give the node a full interval first.
|
|
328
|
+
this.scheduleChainSyncProbe();
|
|
329
|
+
}
|
|
330
|
+
scheduleChainSyncProbe() {
|
|
331
|
+
if (!this.running || this.chainSyncRecovered || this.chainSyncProbeTimer)
|
|
206
332
|
return;
|
|
207
|
-
|
|
208
|
-
|
|
333
|
+
const timer = setTimeout(() => {
|
|
334
|
+
this.chainSyncProbeTimer = null;
|
|
335
|
+
if (!this.running || this.chainSyncRecovered)
|
|
336
|
+
return;
|
|
337
|
+
this.chainSyncProbe = this.client.recoverChainSyncBackend()
|
|
338
|
+
.then((backend) => {
|
|
339
|
+
if (!backend || !this.running)
|
|
340
|
+
return;
|
|
341
|
+
this.chainSyncRecovered = true;
|
|
342
|
+
this.wake?.(); // a poll sleep must not hold the handover back
|
|
343
|
+
})
|
|
344
|
+
.catch((err) => logger.debug('chain-sync probe failed:', err))
|
|
345
|
+
.finally(() => {
|
|
346
|
+
this.chainSyncProbe = null;
|
|
347
|
+
this.scheduleChainSyncProbe();
|
|
348
|
+
});
|
|
349
|
+
}, CardanoCrawler.CHAIN_SYNC_RETRY_MS);
|
|
350
|
+
timer.unref?.(); // never keep the process alive for a probe
|
|
351
|
+
this.chainSyncProbeTimer = timer;
|
|
352
|
+
}
|
|
353
|
+
stopChainSyncProbing() {
|
|
354
|
+
if (!this.chainSyncProbeTimer)
|
|
355
|
+
return;
|
|
356
|
+
clearTimeout(this.chainSyncProbeTimer);
|
|
357
|
+
this.chainSyncProbeTimer = null;
|
|
209
358
|
}
|
|
210
359
|
/** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
|
|
211
360
|
withTimeout(p, label, ms = CardanoCrawler.CALL_TIMEOUT_MS) {
|
|
@@ -240,11 +389,13 @@ class CardanoCrawler {
|
|
|
240
389
|
await this.halt('error', true); // config error: a restart cannot fix it
|
|
241
390
|
return;
|
|
242
391
|
}
|
|
392
|
+
this.blocksThisStream = 0;
|
|
243
393
|
const handle = await backend.openChainSync(points, {
|
|
244
394
|
rollForward: (block, txs, tip) => this.trackCallback(async () => {
|
|
245
395
|
if (!this.running)
|
|
246
396
|
return;
|
|
247
|
-
await this.persistBlock(block, txs, tip)
|
|
397
|
+
if (await this.persistBlock(block, txs, tip))
|
|
398
|
+
this.blocksThisStream++;
|
|
248
399
|
}),
|
|
249
400
|
rollBackward: (point) => this.trackCallback(async () => {
|
|
250
401
|
if (!this.running)
|
|
@@ -262,6 +413,27 @@ class CardanoCrawler {
|
|
|
262
413
|
onError: (err) => this.trackCallback(async () => {
|
|
263
414
|
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
|
|
264
415
|
return;
|
|
416
|
+
// A frame the client's parser cannot handle is a fault of that one block, not of the
|
|
417
|
+
// crawler or the node — pagination can still fetch it, so degrade instead of halting.
|
|
418
|
+
if (err instanceof errors_1.ChainSyncFrameError && this.canDegradeToPagination(err)) {
|
|
419
|
+
await this.degradeToPagination(err);
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
// The server dropped the socket. After progress: reopen at the cursor. Without progress
|
|
423
|
+
// the server fails on the next block itself (e.g. a header it cannot decode): fetch that
|
|
424
|
+
// block over pagination, then chain-sync takes over again.
|
|
425
|
+
if (err instanceof errors_1.ChainSyncClosedError) {
|
|
426
|
+
if (this.blocksThisStream > 0) {
|
|
427
|
+
logger.warn(`${err.message} after ${this.blocksThisStream} block(s) — reopening chain-sync at the cursor`);
|
|
428
|
+
await this.endStream(() => { this.reopenStream = true; });
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
432
|
+
if (cursor && this.config.source !== 'ogmios' && this.client.getPaginatingBackend()) {
|
|
433
|
+
await this.degradeToPagination(new errors_1.ChainSyncStalledError(cursor.lastHeight + 1, err.message));
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
265
437
|
// The stream is stalled (mapping/callback failure) — record and halt cleanly
|
|
266
438
|
// so the cursor status shows 'error' instead of a healthy-looking hang.
|
|
267
439
|
const streak = await this.recordCrawlerError(err);
|
|
@@ -278,19 +450,56 @@ class CardanoCrawler {
|
|
|
278
450
|
return;
|
|
279
451
|
}
|
|
280
452
|
this.chainSyncHandle = handle;
|
|
453
|
+
this.activeSource = 'chain-sync';
|
|
281
454
|
logger.info(`Crawler running (chain-sync) from ${points[0].hash} (+${points.length - 1} fallback intersection point(s))`);
|
|
282
455
|
}
|
|
456
|
+
/** Read and clear the pending frame failure, so each stream starts from a clean slate. */
|
|
457
|
+
takeFrameFailure() {
|
|
458
|
+
const failure = this.frameFailure;
|
|
459
|
+
this.frameFailure = null;
|
|
460
|
+
return failure;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Whether an unparseable frame can be worked around over HTTP: needs a height, a paginating
|
|
464
|
+
* backend, and a source not pinned to 'ogmios' (chain-sync only).
|
|
465
|
+
*/
|
|
466
|
+
canDegradeToPagination(err) {
|
|
467
|
+
return err.height != null
|
|
468
|
+
&& this.config.source !== 'ogmios'
|
|
469
|
+
&& !!this.client.getPaginatingBackend();
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* End the chain-sync stream and hand back to the ingest loop, which continues on pagination
|
|
473
|
+
* past the offending block. The error is recorded first so `lastError` names the block.
|
|
474
|
+
*/
|
|
475
|
+
async degradeToPagination(err) {
|
|
476
|
+
const streak = await this.recordCrawlerError(err);
|
|
477
|
+
if (streak < 0) {
|
|
478
|
+
await this.halt('stopped');
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
logger.error('Chain-sync cannot deliver a block — continuing on pagination:', err.message);
|
|
482
|
+
await this.endStream(() => { this.frameFailure = err; });
|
|
483
|
+
}
|
|
484
|
+
/** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
|
|
485
|
+
async endStream(mark) {
|
|
486
|
+
mark();
|
|
487
|
+
const handle = this.chainSyncHandle;
|
|
488
|
+
this.chainSyncHandle = null;
|
|
489
|
+
if (handle) {
|
|
490
|
+
try {
|
|
491
|
+
await handle.close();
|
|
492
|
+
}
|
|
493
|
+
catch (e) {
|
|
494
|
+
logger.warn('chain-sync close failed:', e);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
this.streamEnded?.();
|
|
498
|
+
}
|
|
283
499
|
/**
|
|
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.
|
|
500
|
+
* Candidate intersection points, newest first: the cursor, a ladder of already-crawled
|
|
501
|
+
* ancestors, then the configured start block. If the cursor's block was orphaned while the
|
|
502
|
+
* crawler was down, the node intersects at the last common ancestor and reports a rollBackward.
|
|
294
503
|
*/
|
|
295
504
|
async buildIntersectionPoints(cursor) {
|
|
296
505
|
const points = [];
|
|
@@ -303,11 +512,8 @@ class CardanoCrawler {
|
|
|
303
512
|
};
|
|
304
513
|
if (cursor?.lastBlockHash) {
|
|
305
514
|
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.
|
|
515
|
+
// Dense over the last DENSE_DEPTH blocks (real rollbacks are shallow and must intersect
|
|
516
|
+
// exactly), doubling after that for deep-reorg reach without hundreds of points.
|
|
311
517
|
const DENSE_DEPTH = 10;
|
|
312
518
|
const heights = [];
|
|
313
519
|
const pushHeight = (height) => { if (height > 0 && !heights.includes(height))
|
|
@@ -339,27 +545,51 @@ class CardanoCrawler {
|
|
|
339
545
|
// ---------------------------------------------------------------------------
|
|
340
546
|
// Pagination (Blockfrost/Koios) — fallback
|
|
341
547
|
// ---------------------------------------------------------------------------
|
|
342
|
-
|
|
548
|
+
/**
|
|
549
|
+
* @param untilHeight return once the cursor reaches it — walks past a block chain-sync
|
|
550
|
+
* cannot deliver, then hands back.
|
|
551
|
+
* @param untilChainSync retry a chain-sync backend in the background; return once one is usable.
|
|
552
|
+
*/
|
|
553
|
+
async runPagination(opts = {}) {
|
|
554
|
+
if (opts.untilChainSync)
|
|
555
|
+
this.startChainSyncProbing();
|
|
556
|
+
try {
|
|
557
|
+
await this.paginate(opts);
|
|
558
|
+
}
|
|
559
|
+
finally {
|
|
560
|
+
this.stopChainSyncProbing();
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
async paginate({ untilHeight, untilChainSync = false }) {
|
|
343
564
|
const backend = this.client.getPaginatingBackend();
|
|
344
565
|
if (!backend) {
|
|
345
566
|
logger.error('No paginating backend available — cannot crawl without Ogmios or Blockfrost/Koios');
|
|
346
567
|
await this.halt('error', true); // config error: a restart cannot fix it
|
|
347
568
|
return;
|
|
348
569
|
}
|
|
570
|
+
backend.configureCrawl?.({ certificates: this.config.certificates });
|
|
571
|
+
this.activeSource = 'pagination';
|
|
349
572
|
logger.info('Crawler running (pagination)');
|
|
350
|
-
// Tip cache
|
|
351
|
-
//
|
|
352
|
-
// per batch. Refresh only when the cursor reaches the cached target.
|
|
573
|
+
// Tip cache, refreshed only when the cursor reaches the cached target; during catch-up
|
|
574
|
+
// the exact tip is irrelevant.
|
|
353
575
|
let tip = null;
|
|
354
576
|
let target = Number.NEGATIVE_INFINITY;
|
|
355
577
|
while (this.running) {
|
|
356
578
|
try {
|
|
579
|
+
if (untilChainSync && this.chainSyncRecovered) {
|
|
580
|
+
logger.info('chain-sync backend usable again — leaving pagination');
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
357
583
|
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
358
584
|
if (!cursor?.lastBlockHash) {
|
|
359
585
|
logger.error('Pagination refused: cursor has no resume block hash.');
|
|
360
586
|
await this.halt('error', true); // broken precondition: a restart cannot fix it
|
|
361
587
|
return;
|
|
362
588
|
}
|
|
589
|
+
if (untilHeight != null && cursor.lastHeight >= untilHeight) {
|
|
590
|
+
logger.info(`pagination reached block ${cursor.lastHeight} — handing back to chain-sync`);
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
363
593
|
if (!tip || cursor.lastHeight >= target) {
|
|
364
594
|
tip = await this.withTimeout(this.client.getLatestBlock(), 'getLatestBlock');
|
|
365
595
|
target = (tip.height ?? 0) - this.config.confirmationDepth;
|
|
@@ -381,7 +611,7 @@ class CardanoCrawler {
|
|
|
381
611
|
await this.halt('stopped');
|
|
382
612
|
return;
|
|
383
613
|
}
|
|
384
|
-
await this.
|
|
614
|
+
await this.pollPause(untilChainSync);
|
|
385
615
|
continue;
|
|
386
616
|
}
|
|
387
617
|
const blocks = await this.withTimeout(
|
|
@@ -389,7 +619,7 @@ class CardanoCrawler {
|
|
|
389
619
|
// on a fresh start without configured startHeight)
|
|
390
620
|
backend.getNextBlocks(cursor.lastBlockHash, this.config.batchSize, cursor.lastHeight > 0 ? cursor.lastHeight : undefined), 'getNextBlocks');
|
|
391
621
|
if (!blocks.length) {
|
|
392
|
-
await this.
|
|
622
|
+
await this.pollPause(untilChainSync);
|
|
393
623
|
continue;
|
|
394
624
|
}
|
|
395
625
|
for (const block of blocks) {
|
|
@@ -401,6 +631,10 @@ class CardanoCrawler {
|
|
|
401
631
|
const ok = await this.persistBlock(block, txs, tipPoint);
|
|
402
632
|
if (!ok)
|
|
403
633
|
return; // persistBlock already recorded + halted
|
|
634
|
+
// Chain-sync came back mid-batch: the block just written is complete and on the
|
|
635
|
+
// cursor, the rest of the batch is cheaper to stream than to fetch one by one.
|
|
636
|
+
if (untilChainSync && this.chainSyncRecovered)
|
|
637
|
+
break;
|
|
404
638
|
}
|
|
405
639
|
}
|
|
406
640
|
catch (err) {
|
|
@@ -426,10 +660,19 @@ class CardanoCrawler {
|
|
|
426
660
|
await this.halt('error');
|
|
427
661
|
return;
|
|
428
662
|
}
|
|
429
|
-
await this.
|
|
663
|
+
await this.pollPause(untilChainSync);
|
|
430
664
|
}
|
|
431
665
|
}
|
|
432
666
|
}
|
|
667
|
+
/**
|
|
668
|
+
* Poll pause between pagination rounds; skipped when a chain-sync handover is already due,
|
|
669
|
+
* since the probe's wake-up only reaches a sleep that has begun.
|
|
670
|
+
*/
|
|
671
|
+
async pollPause(untilChainSync) {
|
|
672
|
+
if (untilChainSync && this.chainSyncRecovered)
|
|
673
|
+
return;
|
|
674
|
+
await this.sleep(this.config.pollIntervalMs);
|
|
675
|
+
}
|
|
433
676
|
/**
|
|
434
677
|
* Pagination reorg recovery: walk back by height comparing the on-chain block hash with
|
|
435
678
|
* our stored one until they agree — that height is the fork point. If the last-indexed
|
|
@@ -461,10 +704,8 @@ class CardanoCrawler {
|
|
|
461
704
|
if (ours?.hash && onChain.hash === ours.hash) {
|
|
462
705
|
if (h === cursor.lastHeight)
|
|
463
706
|
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.)
|
|
707
|
+
// A null provider slot would make forkSlot 0 and wipe the entire crawled dataset —
|
|
708
|
+
// abort this round instead.
|
|
468
709
|
if (onChain.slot == null)
|
|
469
710
|
return false;
|
|
470
711
|
await this.handleReorg({ slot: onChain.slot, hash: onChain.hash, height: h });
|
|
@@ -477,10 +718,8 @@ class CardanoCrawler {
|
|
|
477
718
|
// Persist + reorg (shared)
|
|
478
719
|
// ---------------------------------------------------------------------------
|
|
479
720
|
/**
|
|
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.
|
|
721
|
+
* Persist one block atomically and advance the cursor. Transient failures are retried; the
|
|
722
|
+
* cursor is not advanced on failure, so a resume re-syncs from it. Marks 'synced' at the tip.
|
|
484
723
|
* @returns true when the block was persisted, false when the crawler was stopped
|
|
485
724
|
*/
|
|
486
725
|
async persistBlock(block, txs, tip) {
|
|
@@ -498,14 +737,26 @@ class CardanoCrawler {
|
|
|
498
737
|
return false;
|
|
499
738
|
try {
|
|
500
739
|
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
740
|
await this.indexer.indexBlockFull(tx, block, txs);
|
|
507
|
-
|
|
741
|
+
// Ledger progress marker: written in the same statement as the cursor, so "the
|
|
742
|
+
// cursor is ahead of the marker" always means blocks went by without the set.
|
|
743
|
+
const anchor = this.indexer.getUtxoAnchor();
|
|
744
|
+
const ledgerApplied = anchor != null && (block.slot ?? 0) > anchor.slot;
|
|
745
|
+
// The cursor UPDATE also renews and fences the lease; a lost lease rolls the block back.
|
|
746
|
+
const leaseHeld = 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, this.leaseOwner);
|
|
747
|
+
if (!leaseHeld)
|
|
748
|
+
throw new CrawlerLeaseLostError();
|
|
508
749
|
});
|
|
750
|
+
this.leaseRenewedAt = Date.now();
|
|
751
|
+
this.indexer.confirmBlockCommit();
|
|
752
|
+
if (CardanoCrawler.poison?.hash === block.hash)
|
|
753
|
+
CardanoCrawler.poison = null;
|
|
754
|
+
// A ledger invalidation decided inside the block transaction takes effect in memory
|
|
755
|
+
// only now, after the commit that carries it — a rolled-back attempt changes nothing.
|
|
756
|
+
const invalidation = this.indexer.takeLedgerInvalidation();
|
|
757
|
+
if (invalidation) {
|
|
758
|
+
logger.error(`UTxO set invalidated: ${invalidation} — ledger tables stop updating until importUtxoSet runs again`);
|
|
759
|
+
}
|
|
509
760
|
// Notify observers (wallet-worker confirmation tracker) AFTER the commit —
|
|
510
761
|
// listener failures are swallowed inside emitBlockIndexed.
|
|
511
762
|
(0, hooks_1.emitBlockIndexed)({
|
|
@@ -516,6 +767,7 @@ class CardanoCrawler {
|
|
|
516
767
|
tipSlot: tip?.slot ?? null,
|
|
517
768
|
tipHeight: tip?.height ?? null,
|
|
518
769
|
});
|
|
770
|
+
this.maybeSnapshotEpoch(block, tip);
|
|
519
771
|
return true;
|
|
520
772
|
}
|
|
521
773
|
catch (err) {
|
|
@@ -534,27 +786,110 @@ class CardanoCrawler {
|
|
|
534
786
|
await this.sleep(1000 * attempt);
|
|
535
787
|
continue;
|
|
536
788
|
}
|
|
537
|
-
|
|
789
|
+
const dataRejection = CardanoCrawler.isDataRejection(err);
|
|
790
|
+
const failures = dataRejection ? CardanoCrawler.notePersistFailure(block.hash) : 0;
|
|
791
|
+
if (failures >= CardanoCrawler.POISON_BLOCK_THRESHOLD) {
|
|
792
|
+
const cause = err instanceof Error ? err.message : String(err);
|
|
793
|
+
const message = `poison block ${block.hash} @${block.height ?? '?'} failed ${failures}x: ${cause}`;
|
|
794
|
+
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);
|
|
795
|
+
// Lease-independent on purpose (see latchPoisonBlock); the memory is only forgotten
|
|
796
|
+
// once the latch is durable, so a failed write is retried after the next restart.
|
|
797
|
+
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; });
|
|
798
|
+
if (latched)
|
|
799
|
+
CardanoCrawler.poison = null;
|
|
800
|
+
await this.halt('error', true);
|
|
801
|
+
return false;
|
|
802
|
+
}
|
|
803
|
+
const perBlock = dataRejection ? ` (${failures}/${CardanoCrawler.POISON_BLOCK_THRESHOLD} for this block)` : '';
|
|
804
|
+
logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts${perBlock} — stopping crawler (resume re-syncs from cursor):`, err);
|
|
538
805
|
await this.halt('error');
|
|
539
806
|
return false;
|
|
540
807
|
}
|
|
541
808
|
}
|
|
542
809
|
}
|
|
810
|
+
/** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
|
|
811
|
+
epochOfSlot(slot) {
|
|
812
|
+
const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network]
|
|
813
|
+
?? const_1.EPOCH_CONFIG_BY_NETWORK.preview;
|
|
814
|
+
return cfg.shelleyStartEpoch + Math.floor((slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
|
|
815
|
+
}
|
|
543
816
|
/**
|
|
544
|
-
*
|
|
545
|
-
*
|
|
546
|
-
*
|
|
547
|
-
*
|
|
548
|
-
*
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
817
|
+
* Pool/DRep snapshot once per epoch, detached from the triggering block. With Ogmios the ledger
|
|
818
|
+
* state is read AT the block, which works while the block is inside the node's volatile window
|
|
819
|
+
* (k blocks behind the tip). Koios reports current state only, so there the crawl must be in the
|
|
820
|
+
* tip's epoch. Epochs passed outside those bounds are skipped. Authority is the marker row in
|
|
821
|
+
* `EpochLedgerSnapshots` (or a pool row written before the marker existed).
|
|
822
|
+
*/
|
|
823
|
+
maybeSnapshotEpoch(block, tip) {
|
|
824
|
+
if (!this.config.epochSnapshots || block.epoch == null)
|
|
825
|
+
return;
|
|
826
|
+
if (this.snapshotedEpoch === block.epoch || this.snapshotInFlight)
|
|
827
|
+
return;
|
|
828
|
+
// No tip reported = we cannot prove we are live, so we do not pretend to be.
|
|
829
|
+
if (tip == null) {
|
|
830
|
+
logger.debug(`epoch ${block.epoch} snapshot skipped: no chain tip reported for this block`);
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
const fromLedger = this.client.getEpochStateBackend() != null && !!block.hash;
|
|
834
|
+
if (fromLedger) {
|
|
835
|
+
const k = const_1.EPOCH_CONFIG_BY_NETWORK[this.network]?.securityParam
|
|
836
|
+
?? const_1.EPOCH_CONFIG_BY_NETWORK.mainnet.securityParam;
|
|
837
|
+
const behind = tip.height != null && block.height != null ? tip.height - block.height : null;
|
|
838
|
+
if (behind == null || behind >= k - CardanoCrawler.SNAPSHOT_WINDOW_MARGIN) {
|
|
839
|
+
logger.debug(`epoch ${block.epoch} snapshot skipped at height ${block.height}: ${behind ?? '?'} blocks behind the tip, outside the node's volatile window (k=${k})`);
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
else {
|
|
844
|
+
const tipEpoch = this.epochOfSlot(tip.slot);
|
|
845
|
+
if (block.epoch !== tipEpoch) {
|
|
846
|
+
logger.debug(`epoch ${block.epoch} snapshot skipped: still backfilling (tip is in epoch ${tipEpoch}) — ` +
|
|
847
|
+
`the provider reports the pool/DRep set as it is now, never as it was`);
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
if (Date.now() < this.snapshotRetryAfter)
|
|
852
|
+
return;
|
|
853
|
+
const epoch = block.epoch;
|
|
854
|
+
const at = { slot: block.slot ?? 0, time: block.time ?? 0, hash: fromLedger ? block.hash : null };
|
|
855
|
+
this.snapshotInFlight = this.trackCallback(async () => {
|
|
856
|
+
const existing = await cds_1.default.tx(async (tx) => (await tx.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('epoch').where({ epoch })))
|
|
857
|
+
?? (await tx.run(SELECT.one.from(cardano_1.PoolEpochSnapshots).columns('epoch').where({ epoch }))));
|
|
858
|
+
if (!existing) {
|
|
859
|
+
await this.withTimeout(this.indexer.snapshotEpoch(epoch, at), `snapshotEpoch(${epoch})`, CardanoCrawler.SNAPSHOT_TIMEOUT_MS);
|
|
860
|
+
const previous = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('max(epoch) as e').where({ epoch: { '<': epoch } })));
|
|
861
|
+
const last = previous?.e == null ? null : Number(previous.e);
|
|
862
|
+
if (last != null && epoch > last + 1) {
|
|
863
|
+
logger.warn(`epoch snapshots missing for epochs ${last + 1}..${epoch - 1} — passed outside the snapshot window`);
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
this.snapshotedEpoch = epoch;
|
|
867
|
+
this.snapshotFailures = 0;
|
|
868
|
+
this.snapshotRetryAfter = 0;
|
|
869
|
+
})
|
|
870
|
+
.catch((err) => {
|
|
871
|
+
// Never fatal: the crawl keeps its data, the epoch is retried on a later block —
|
|
872
|
+
// but not on the very next one, or an outage would re-enumerate per block.
|
|
873
|
+
this.snapshotFailures++;
|
|
874
|
+
const backoff = Math.min(CardanoCrawler.SNAPSHOT_RETRY_BASE_MS * 2 ** (this.snapshotFailures - 1), CardanoCrawler.SNAPSHOT_RETRY_MAX_MS);
|
|
875
|
+
this.snapshotRetryAfter = Date.now() + backoff;
|
|
876
|
+
if (this.running)
|
|
877
|
+
logger.error(`epoch ${epoch} snapshot failed (retry in ${backoff} ms):`, err);
|
|
878
|
+
})
|
|
879
|
+
.finally(() => { this.snapshotInFlight = null; });
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* Chain rollback in one transaction: delete blocks with slot > fork (absolute-slot axis, never
|
|
883
|
+
* height), their transactions resolved via blockHash (lazily indexed txs of other blocks are
|
|
884
|
+
* untouched), reset the cursor to the fork and write a CardanoReorgLog row.
|
|
552
885
|
*/
|
|
553
886
|
async handleReorg(point) {
|
|
554
887
|
const forkSlot = point === 'origin' ? (this.config.startSlot ?? 0) : point.slot;
|
|
555
888
|
let blocksRolledBack = 0;
|
|
556
889
|
let txsRolledBack = 0;
|
|
557
890
|
let emittedForkHeight = null;
|
|
891
|
+
const rolledBackTxHashes = [];
|
|
892
|
+
let ledgerInvalidated = false;
|
|
558
893
|
try {
|
|
559
894
|
await cds_1.default.tx(async (tx) => {
|
|
560
895
|
if (this.leaseOwner) {
|
|
@@ -577,9 +912,10 @@ class CardanoCrawler {
|
|
|
577
912
|
for (const blockChunk of (0, collections_1.chunk)(blockHashes, collections_1.IN_CHUNK)) {
|
|
578
913
|
// Only transactions of the rolled-back blocks — resolved via blockHash, so
|
|
579
914
|
// 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 } }));
|
|
915
|
+
const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ blockHash: { in: blockChunk } }));
|
|
581
916
|
const txHashes = staleTxs.map((t) => t.hash);
|
|
582
917
|
txsRolledBack += txHashes.length;
|
|
918
|
+
rolledBackTxHashes.push(...txHashes);
|
|
583
919
|
for (const txChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
|
|
584
920
|
// These denormalized/lazy indexes have no generated FK cascades. Remove
|
|
585
921
|
// them before their parent tx/output rows so orphan data cannot leak via OData.
|
|
@@ -587,15 +923,34 @@ class CardanoCrawler {
|
|
|
587
923
|
await tx.run(DELETE.from(cardano_1.AddressUTxOs).where({ hash: { in: txChunk } }));
|
|
588
924
|
await tx.run(DELETE.from(cardano_1.AddressTransactions).where({ tx_hash: { in: txChunk } }));
|
|
589
925
|
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
926
|
}
|
|
927
|
+
await (0, transaction_rows_1.deleteTransactionRows)(tx, staleTxs);
|
|
597
928
|
await tx.run(DELETE.from(cardano_1.Blocks).where({ hash: { in: blockChunk } }));
|
|
598
929
|
}
|
|
930
|
+
// Epoch snapshots read at a rolled-back block describe a chain that no longer exists.
|
|
931
|
+
if (blocksRolledBack > 0) {
|
|
932
|
+
for (const entity of [cardano_1.PoolEpochSnapshots, cardano_1.DrepEpochSnapshots, cardano_1.EpochLedgerSnapshots]) {
|
|
933
|
+
await tx.run(DELETE.from(entity).where({ snapshotSlot: { '>': forkSlot } }));
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
// Ledger state, driven by the PERSISTED status: a fork after the anchor is undone and the
|
|
937
|
+
// progress marker follows the cursor back; a fork before the anchor invalidates the set.
|
|
938
|
+
const persisted = (await (0, sync_state_1.readCursor)(tx))?.utxoSet;
|
|
939
|
+
if (persisted?.status === 'active' && persisted.anchorSlot != null) {
|
|
940
|
+
if (forkSlot < persisted.anchorSlot) {
|
|
941
|
+
await (0, sync_state_1.setUtxoSetState)(tx, {
|
|
942
|
+
status: 'invalid',
|
|
943
|
+
error: `reorg to slot ${forkSlot} before the UTxO set anchor ${persisted.anchorSlot} — re-import the set`,
|
|
944
|
+
});
|
|
945
|
+
ledgerInvalidated = true;
|
|
946
|
+
}
|
|
947
|
+
else {
|
|
948
|
+
await (0, ledger_state_1.undoLedgerForTransactions)(tx, rolledBackTxHashes);
|
|
949
|
+
if (persisted.appliedSlot != null && persisted.appliedSlot > forkSlot) {
|
|
950
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { appliedSlot: forkSlot });
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
}
|
|
599
954
|
await (0, sync_state_1.resetCursorTo)(tx, point === 'origin'
|
|
600
955
|
? { slot: forkSlot, hash: this.config.startBlockHash ?? '', height: 0 }
|
|
601
956
|
: { slot: point.slot, hash: point.hash, height: forkHeight ?? 0 });
|
|
@@ -618,12 +973,18 @@ class CardanoCrawler {
|
|
|
618
973
|
}
|
|
619
974
|
throw err;
|
|
620
975
|
}
|
|
976
|
+
if (ledgerInvalidated) {
|
|
977
|
+
this.indexer.setUtxoAnchor(null);
|
|
978
|
+
logger.error(`UTxO set invalidated: reorg to slot ${forkSlot} reaches behind the anchor — ledger tables stop updating until importUtxoSet runs again`);
|
|
979
|
+
}
|
|
621
980
|
// Notify observers (wallet-worker confirmation tracker + CAP subscribers) AFTER
|
|
622
981
|
// the rollback commit.
|
|
982
|
+
// The rollback may have removed this epoch's snapshot; the next block re-checks it.
|
|
983
|
+
this.snapshotedEpoch = null;
|
|
623
984
|
(0, hooks_1.emitReorg)({ forkSlot, forkHeight: emittedForkHeight, blocksRolledBack });
|
|
624
985
|
logger.warn(`Reorg handled: rolled back ${blocksRolledBack} blocks (${txsRolledBack} txs) to slot ${forkSlot}`);
|
|
625
986
|
}
|
|
626
|
-
/** Renew the lease while
|
|
987
|
+
/** Renew the lease while no block commits; block writes renew it transactionally. */
|
|
627
988
|
startLeaseHeartbeat() {
|
|
628
989
|
if (!this.leaseOwner || this.leaseHeartbeat)
|
|
629
990
|
return;
|
|
@@ -633,6 +994,9 @@ class CardanoCrawler {
|
|
|
633
994
|
await this.leaseSleep(intervalMs);
|
|
634
995
|
if (!this.running)
|
|
635
996
|
return;
|
|
997
|
+
// Block commits renew the lease; the heartbeat only covers idle stretches.
|
|
998
|
+
if (Date.now() - this.leaseRenewedAt < intervalMs)
|
|
999
|
+
continue;
|
|
636
1000
|
try {
|
|
637
1001
|
const renewed = await cds_1.default.tx((tx) => (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner));
|
|
638
1002
|
if (!renewed) {
|
|
@@ -650,6 +1014,24 @@ class CardanoCrawler {
|
|
|
650
1014
|
}
|
|
651
1015
|
})();
|
|
652
1016
|
}
|
|
1017
|
+
/** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
|
|
1018
|
+
static isDataRejection(err) {
|
|
1019
|
+
// RangeError: BigInt / number conversions in the mappers; SyntaxError: JSON of the block
|
|
1020
|
+
if (err instanceof RangeError || err instanceof SyntaxError)
|
|
1021
|
+
return true;
|
|
1022
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1023
|
+
return CardanoCrawler.DATA_REJECTION_PATTERNS.some((p) => p.test(message));
|
|
1024
|
+
}
|
|
1025
|
+
/** Count final persist failures per block hash (a different hash resets the count). */
|
|
1026
|
+
static notePersistFailure(hash) {
|
|
1027
|
+
const p = CardanoCrawler.poison;
|
|
1028
|
+
CardanoCrawler.poison = p && p.hash === hash ? { hash, failures: p.failures + 1 } : { hash, failures: 1 };
|
|
1029
|
+
return CardanoCrawler.poison.failures;
|
|
1030
|
+
}
|
|
1031
|
+
/** Test seam: forget the poison-block memory (process-wide state). */
|
|
1032
|
+
static resetPoisonMemory() {
|
|
1033
|
+
CardanoCrawler.poison = null;
|
|
1034
|
+
}
|
|
653
1035
|
/** Record state only while this instance still owns the lease. */
|
|
654
1036
|
async recordCrawlerError(err) {
|
|
655
1037
|
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
|