@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50
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 +99 -51
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoBackendService/index.d.ts +347 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
- package/@cds-models/CardanoIndexerService/index.js +64 -0
- package/@cds-models/CardanoODataService/index.d.ts +414 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +32 -19
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
- package/@cds-models/index.d.ts +101 -1
- package/@cds-models/index.js +16 -1
- package/@cds-models/odatano/cardano/index.d.ts +437 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +207 -167
- package/db/schema.cds +2402 -1705
- package/db/types.cds +446 -295
- package/package.json +41 -16
- package/scripts/migrate-schema.mjs +334 -0
- package/scripts/migrate-slot-leader.mjs +96 -0
- package/src/index.d.ts +20 -21
- package/src/index.js +45 -31
- package/src/plugin.js +17 -35
- package/srv/blockchain/asset-decimals.d.ts +7 -0
- package/srv/blockchain/asset-decimals.js +91 -0
- package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
- package/srv/blockchain/backends/blockfrost-backend.js +66 -172
- package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +103 -168
- package/srv/blockchain/backends/koios-backend.js +428 -360
- package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
- package/srv/blockchain/backends/odatano-backend.js +169 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
- package/srv/blockchain/backends/ogmios-backend.js +637 -315
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
- package/srv/blockchain/cardano-client.d.ts +61 -241
- package/srv/blockchain/cardano-client.js +253 -293
- package/srv/blockchain/cardano-indexer.d.ts +282 -281
- package/srv/blockchain/cardano-indexer.js +1551 -484
- package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
- package/srv/blockchain/cardano-tx-builder.js +164 -140
- package/srv/blockchain/circuit-breaker.d.ts +1 -13
- package/srv/blockchain/circuit-breaker.js +5 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +153 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/certificate-backfill.js +162 -0
- package/srv/blockchain/crawler/crawler.d.ts +104 -81
- package/srv/blockchain/crawler/crawler.js +532 -160
- package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
- package/srv/blockchain/crawler/credential-backfill.js +124 -0
- package/srv/blockchain/crawler/hooks.d.ts +2 -17
- package/srv/blockchain/crawler/index.d.ts +1 -8
- package/srv/blockchain/crawler/index.js +31 -17
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +171 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
- package/srv/blockchain/crawler/sync-state.d.ts +27 -47
- package/srv/blockchain/crawler/sync-state.js +113 -63
- package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
- package/srv/blockchain/crawler/transaction-backfill.js +278 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
- package/srv/blockchain/crawler/utxo-set-import.js +399 -0
- package/srv/blockchain/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +419 -0
- package/srv/blockchain/pending-spends.d.ts +16 -0
- package/srv/blockchain/pending-spends.js +81 -0
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/request-coalescer.d.ts +2 -16
- package/srv/blockchain/request-coalescer.js +2 -16
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
- package/srv/blockchain/signing/cose-verifier.js +146 -70
- package/srv/blockchain/signing/external-signer.d.ts +15 -115
- package/srv/blockchain/signing/external-signer.js +17 -126
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +70 -83
- package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
- package/srv/blockchain/signing/submission-finalizer.js +219 -86
- package/srv/blockchain/stored-chain.d.ts +20 -0
- package/srv/blockchain/stored-chain.js +237 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +5 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +44 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
- package/srv/blockchain/wallet-worker/build-request.js +47 -30
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
- package/srv/blockchain/wallet-worker/job-store.js +101 -201
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
- package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
- package/srv/blockchain/wallet-worker/signers.js +4 -12
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
- package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +4 -9
- package/srv/cardano-backend-service.cds +78 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +242 -0
- package/srv/cardano-indexer-service.cds +387 -73
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +532 -16
- package/srv/cardano-service.cds +424 -269
- package/srv/cardano-service.js +289 -201
- package/srv/cardano-sign-service.cds +201 -180
- package/srv/cardano-sign-service.js +71 -201
- package/srv/cardano-tx-service.cds +451 -370
- package/srv/cardano-tx-service.js +271 -289
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +118 -125
- package/srv/cardano-worker-service.js +52 -61
- package/srv/cbor/cip68.d.ts +13 -0
- package/srv/cbor/cip68.js +56 -0
- package/srv/cbor/index.d.ts +3 -1
- package/srv/cbor/index.js +9 -1
- package/srv/cbor/parse.d.ts +30 -18
- package/srv/cbor/parse.js +44 -9
- package/srv/cbor/plutus-data-json.d.ts +20 -0
- package/srv/cbor/plutus-data-json.js +32 -0
- package/srv/config.d.ts +113 -0
- package/srv/config.js +409 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +84 -404
- package/srv/utils/agent-access.d.ts +9 -0
- package/srv/utils/agent-access.js +67 -0
- package/srv/utils/agent-grants-config.d.ts +0 -46
- package/srv/utils/agent-grants-config.js +17 -85
- package/srv/utils/agent-grants.d.ts +106 -122
- package/srv/utils/agent-grants.js +538 -236
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +18 -182
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +3 -10
- package/srv/utils/collections.js +3 -10
- package/srv/utils/const.d.ts +23 -74
- package/srv/utils/const.js +32 -79
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +6 -21
- package/srv/utils/db-indexes.d.ts +27 -0
- package/srv/utils/db-indexes.js +120 -0
- package/srv/utils/db-sanitize.d.ts +20 -0
- package/srv/utils/db-sanitize.js +80 -0
- package/srv/utils/deep-json.d.ts +6 -0
- package/srv/utils/deep-json.js +240 -0
- package/srv/utils/epoch-slots.d.ts +13 -0
- package/srv/utils/epoch-slots.js +38 -0
- package/srv/utils/error-codes.d.ts +22 -75
- package/srv/utils/error-codes.js +23 -72
- package/srv/utils/errors.d.ts +46 -187
- package/srv/utils/errors.js +114 -230
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +102 -223
- package/srv/utils/mappers.js +387 -316
- package/srv/utils/network-context.js +2 -13
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +58 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +54 -0
- package/srv/utils/plutus-placeholders.d.ts +16 -22
- package/srv/utils/plutus-placeholders.js +62 -33
- package/srv/utils/rate-limiter.d.ts +2 -21
- package/srv/utils/rate-limiter.js +5 -17
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/reference-script.d.ts +19 -0
- package/srv/utils/reference-script.js +84 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/service-events.d.ts +0 -24
- package/srv/utils/service-events.js +3 -25
- package/srv/utils/signing-helper.d.ts +3 -20
- package/srv/utils/signing-helper.js +35 -64
- package/srv/utils/tx-build-helper.d.ts +10 -105
- package/srv/utils/tx-build-helper.js +81 -144
- package/srv/utils/tx-request-parsers.d.ts +82 -33
- package/srv/utils/tx-request-parsers.js +401 -49
- package/srv/utils/tx-utils.d.ts +3 -27
- package/srv/utils/tx-utils.js +32 -50
- package/srv/utils/types.d.ts +261 -191
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +22 -92
- package/srv/utils/validators.js +50 -149
|
@@ -7,8 +7,12 @@ 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");
|
|
15
|
+
const account_snapshots_1 = require("./account-snapshots");
|
|
12
16
|
const sync_state_1 = require("./sync-state");
|
|
13
17
|
const { SELECT, DELETE, INSERT } = cds_1.default.ql;
|
|
14
18
|
const logger = cds_1.default.log('CardanoCrawler');
|
|
@@ -19,21 +23,8 @@ class CrawlerStoppedError extends Error {
|
|
|
19
23
|
class CrawlerLeaseLostError extends Error {
|
|
20
24
|
constructor() { super('Crawler DB lease lost'); this.name = 'CrawlerLeaseLostError'; }
|
|
21
25
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
* start block and bulk-indexes Blocks + Transactions (+ inputs/outputs/assets) into the
|
|
25
|
-
* DB, so consumers can query local data instead of hitting a backend per request.
|
|
26
|
-
*
|
|
27
|
-
* Two sources (see CRAWLER_DESIGN.md):
|
|
28
|
-
* - **Ogmios chain-sync** (primary): ordered rollForward + native rollBackward (reorg).
|
|
29
|
-
* - **Blockfrost/Koios pagination** (fallback): forward walk + parent-hash reorg recovery.
|
|
30
|
-
*
|
|
31
|
-
* Lifecycle: start() launches the ingest pipeline detached so the HTTP server binds
|
|
32
|
-
* immediately, but the pipeline promise is retained — stop() halts the loops (waking
|
|
33
|
-
* any pending poll sleep) and AWAITS the pipeline, so shutdown never races in-flight
|
|
34
|
-
* block writes. All per-block writes are atomic. The crawler NEVER crawls from genesis
|
|
35
|
-
* implicitly — it requires an explicit configured start point or an existing cursor.
|
|
36
|
-
*/
|
|
26
|
+
// Streams the chain forward from a start block and bulk-indexes it.
|
|
27
|
+
// Ogmios chain-sync is the primary source, provider pagination the fallback. Each block is written atomically.
|
|
37
28
|
class CardanoCrawler {
|
|
38
29
|
client;
|
|
39
30
|
indexer;
|
|
@@ -42,11 +33,42 @@ class CardanoCrawler {
|
|
|
42
33
|
leaseOwner;
|
|
43
34
|
/** Transient-failure retries per block before giving up. */
|
|
44
35
|
static PERSIST_RETRIES = 3;
|
|
36
|
+
/** Final persist failures for the same block across restarts before the crawler latches off (poison block). */
|
|
37
|
+
static POISON_BLOCK_THRESHOLD = 5;
|
|
38
|
+
/** Process-wide, survives instance restarts: the block currently failing and how often. */
|
|
39
|
+
static poison = null;
|
|
40
|
+
/** Errors caused by the block's data. Only these count towards the poison latch, outages never do. */
|
|
41
|
+
static DATA_REJECTION_PATTERNS = [
|
|
42
|
+
/unsupported unicode escape sequence/i, // PostgreSQL: U+0000 inside a JSON document
|
|
43
|
+
/invalid byte sequence for encoding/i, // PostgreSQL: bytes that are not valid UTF-8
|
|
44
|
+
/out of range for type/i, // PostgreSQL: bigint / integer overflow
|
|
45
|
+
/invalid input syntax for type/i, // PostgreSQL: NaN or text in a numeric column
|
|
46
|
+
/value too long for type/i, // PostgreSQL: varchar(n) exceeded
|
|
47
|
+
/numeric value out of range/i, // HANA / SQL-92
|
|
48
|
+
/inserted value too large for column/i, // HANA
|
|
49
|
+
/string or blob too big/i, // SQLite
|
|
50
|
+
/datatype mismatch/i, // SQLite
|
|
51
|
+
];
|
|
45
52
|
/** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
|
|
46
53
|
static CALL_TIMEOUT_MS = 60_000;
|
|
54
|
+
/** Epoch snapshots are ~100 batched provider requests on mainnet; wider bound, cancelled by beginHalt. */
|
|
55
|
+
static SNAPSHOT_TIMEOUT_MS = 5 * 60_000;
|
|
56
|
+
/** One node request per 2000 known accounts; an hour covers a mainnet-sized set. */
|
|
57
|
+
static ACCOUNT_SNAPSHOT_TIMEOUT_MS = 60 * 60_000;
|
|
58
|
+
/** Backoff after a failed snapshot attempt, doubling up to the cap; the marker is only set on success. */
|
|
59
|
+
static SNAPSHOT_RETRY_BASE_MS = 30_000;
|
|
60
|
+
static SNAPSHOT_RETRY_MAX_MS = 10 * 60_000;
|
|
61
|
+
/** Retry cadence for a chain-sync backend's init while the crawl runs on pagination. */
|
|
62
|
+
static CHAIN_SYNC_RETRY_MS = 30_000;
|
|
47
63
|
running = false;
|
|
48
64
|
chainSyncHandle = null;
|
|
49
|
-
/**
|
|
65
|
+
/** What the ingest loop is currently reading from; null while stopped. */
|
|
66
|
+
activeSource = null;
|
|
67
|
+
/** Chain-sync init retry while on pagination: own timer, in-flight probe, outcome. */
|
|
68
|
+
chainSyncProbeTimer = null;
|
|
69
|
+
chainSyncProbe = null;
|
|
70
|
+
chainSyncRecovered = false;
|
|
71
|
+
/** The detached ingest pipeline. stop() awaits it so teardown never races it. */
|
|
50
72
|
pipeline = null;
|
|
51
73
|
/** Resolver that cancels a pending poll sleep (set while sleeping). */
|
|
52
74
|
wake = null;
|
|
@@ -55,11 +77,35 @@ class CardanoCrawler {
|
|
|
55
77
|
/** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
|
|
56
78
|
inFlightCallbacks = new Set();
|
|
57
79
|
haltPromise = null;
|
|
80
|
+
/** A block chain-sync cannot deliver; the ingest loop fetches it via pagination, then reopens chain-sync. */
|
|
81
|
+
frameFailure = null;
|
|
82
|
+
/** The stream closed after making progress; the ingest loop reopens chain-sync at the cursor. */
|
|
83
|
+
reopenStream = false;
|
|
84
|
+
/** Blocks persisted by the current chain-sync stream. */
|
|
85
|
+
blocksThisStream = 0;
|
|
86
|
+
/** Resolves the ingest loop's wait for the current chain-sync stream to end. */
|
|
87
|
+
streamEnded = null;
|
|
88
|
+
/** An open stream that delivers nothing for this long is taken as dead and reopened at the cursor. */
|
|
89
|
+
static CHAIN_SYNC_IDLE_MS = 5 * 60 * 1000;
|
|
90
|
+
idleTimer = null;
|
|
91
|
+
/** Reopens since the last block, so a chain that stands still warns once. */
|
|
92
|
+
idleReopens = 0;
|
|
58
93
|
finalStatus = 'stopped';
|
|
59
|
-
/** Set only by an unrecoverable halt
|
|
94
|
+
/** Set only by an unrecoverable halt. It clears desiredRunning so restarts stay down. */
|
|
60
95
|
latchOnHalt = false;
|
|
96
|
+
/** Distance to k at which a block no longer counts as acquirable (the tip moves on while we query). */
|
|
97
|
+
static SNAPSHOT_WINDOW_MARGIN = 10;
|
|
98
|
+
/** Epoch whose pool/DRep snapshot this process has settled, and the in-flight attempt. */
|
|
99
|
+
snapshotedEpoch = null;
|
|
100
|
+
snapshotInFlight = null;
|
|
101
|
+
/** Consecutive snapshot failures and the earliest time the next attempt may run. */
|
|
102
|
+
snapshotFailures = 0;
|
|
103
|
+
accountSnapshotWarned = false;
|
|
104
|
+
snapshotRetryAfter = 0;
|
|
61
105
|
leaseHeld = false;
|
|
62
106
|
leaseHeartbeat = null;
|
|
107
|
+
/** Last successful lease renewal by a block commit (epoch ms). */
|
|
108
|
+
leaseRenewedAt = 0;
|
|
63
109
|
leaseWake = null;
|
|
64
110
|
constructor(client, indexer, network, config,
|
|
65
111
|
/** Present for production instances created by index.ts; omitted in engine unit tests. */
|
|
@@ -73,11 +119,15 @@ class CardanoCrawler {
|
|
|
73
119
|
isRunning() {
|
|
74
120
|
return this.running;
|
|
75
121
|
}
|
|
76
|
-
/**
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
122
|
+
/** True once the crawler halted because of a failure (not via stop() or a lost lease). */
|
|
123
|
+
haltedWithError() {
|
|
124
|
+
return !this.running && this.finalStatus === 'error';
|
|
125
|
+
}
|
|
126
|
+
/** Source ingested from right now, or null while not running (a crawl degraded to pagination still advances the cursor). */
|
|
127
|
+
getActiveSource() {
|
|
128
|
+
return this.running ? this.activeSource : null;
|
|
129
|
+
}
|
|
130
|
+
/** Start crawling without awaiting the pipeline. Refuses without a start block or cursor, never syncs from genesis. */
|
|
81
131
|
async start() {
|
|
82
132
|
if (this.running)
|
|
83
133
|
return;
|
|
@@ -90,7 +140,7 @@ class CardanoCrawler {
|
|
|
90
140
|
// must never leave a healthy-looking crawler behind.
|
|
91
141
|
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.ensureSyncStateSingleton)(tx, this.network, start));
|
|
92
142
|
if (!cursor.lastBlockHash && !start) {
|
|
93
|
-
logger.error('Crawler start refused: no start block configured and no existing cursor
|
|
143
|
+
logger.error('Crawler start refused: no start block configured and no existing cursor. Set crawler.startSlot + crawler.startBlockHash.');
|
|
94
144
|
return;
|
|
95
145
|
}
|
|
96
146
|
if (this.leaseOwner) {
|
|
@@ -102,9 +152,43 @@ class CardanoCrawler {
|
|
|
102
152
|
}
|
|
103
153
|
}
|
|
104
154
|
this.running = true;
|
|
155
|
+
// Hand the analytics coverage to the indexer before the first block is written.
|
|
156
|
+
this.indexer.configureCrawlCoverage({
|
|
157
|
+
assetHistory: this.config.assetHistory,
|
|
158
|
+
assetCatalogue: this.config.assetCatalogue,
|
|
159
|
+
assetEnrichRate: this.config.assetEnrichRate,
|
|
160
|
+
certificates: this.config.certificates,
|
|
161
|
+
utxoSet: this.config.utxoSet,
|
|
162
|
+
authoritative: this.config.authoritative ?? false,
|
|
163
|
+
inputAssetCopies: this.config.inputAssetCopies ?? false,
|
|
164
|
+
});
|
|
165
|
+
// Ledger state is only applied after an imported snapshot.
|
|
166
|
+
if (this.config.utxoSet) {
|
|
167
|
+
const u = cursor.utxoSet;
|
|
168
|
+
// Blocks crawled while the mode was off never reached the ledger tables, so the set is stale.
|
|
169
|
+
const lastApplied = u.appliedSlot ?? u.anchorSlot;
|
|
170
|
+
if (u.status === 'active' && lastApplied != null && cursor.lastSlot > lastApplied) {
|
|
171
|
+
const error = `cursor at slot ${cursor.lastSlot} is past the last ledger-applied slot ${lastApplied}: blocks were crawled without the set; re-import`;
|
|
172
|
+
await cds_1.default.tx((tx) => (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error }));
|
|
173
|
+
u.status = 'invalid';
|
|
174
|
+
u.error = error;
|
|
175
|
+
}
|
|
176
|
+
if (u.status === 'active' && u.anchorSlot != null && u.anchorHash) {
|
|
177
|
+
this.indexer.setUtxoAnchor({ slot: u.anchorSlot, hash: u.anchorHash });
|
|
178
|
+
void this.indexer.paymentCredentialsReady();
|
|
179
|
+
logger.info(`UTxO set active from anchor ${u.anchorSlot}/${u.anchorHash}, ledger tables are maintained`);
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
this.indexer.setUtxoAnchor(null);
|
|
183
|
+
logger.error(`crawler.utxoSet is enabled but the UTxO set is "${u.status}"${u.error ? ` (${u.error})` : ''}: ` +
|
|
184
|
+
'ledger tables are not maintained until importUtxoSet has run (pause the crawler first)');
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
this.indexer.setUtxoAnchor(null);
|
|
189
|
+
}
|
|
105
190
|
this.startLeaseHeartbeat();
|
|
106
|
-
// A pipeline crash
|
|
107
|
-
// surface on the cursor — otherwise the crawler looks healthy while doing nothing.
|
|
191
|
+
// A pipeline crash must show on the cursor, or the crawler looks healthy while idle.
|
|
108
192
|
this.pipeline = this.runIngestPipeline().catch(async (err) => {
|
|
109
193
|
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
|
|
110
194
|
await this.halt('stopped');
|
|
@@ -115,37 +199,19 @@ class CardanoCrawler {
|
|
|
115
199
|
await this.halt(streak < 0 ? 'stopped' : 'error');
|
|
116
200
|
});
|
|
117
201
|
}
|
|
118
|
-
/**
|
|
119
|
-
* Stop crawling and WAIT for the pipeline to finish its in-flight step: halts the
|
|
120
|
-
* loops (waking any pending poll sleep), closes the chain-sync stream, records the
|
|
121
|
-
* final status, then awaits the detached pipeline so callers (shutdownAppContext)
|
|
122
|
-
* can safely tear down backends/DB afterwards.
|
|
123
|
-
*/
|
|
202
|
+
/** Stop crawling and await the in-flight step, so callers can tear down backends and the DB. */
|
|
124
203
|
async stop(finalStatus = 'stopped') {
|
|
125
204
|
this.beginHalt(finalStatus);
|
|
126
205
|
if (this.haltPromise)
|
|
127
206
|
await this.haltPromise;
|
|
128
207
|
this.pipeline = null;
|
|
129
208
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
* pipeline (persistBlock failure, stream onError), where awaiting the pipeline
|
|
133
|
-
* would deadlock.
|
|
134
|
-
*/
|
|
135
|
-
/**
|
|
136
|
-
* @param latch clears `desiredRunning`, so NO restart brings the crawler back —
|
|
137
|
-
* only an operator's resumeCrawler does. Reserved for failures a restart cannot
|
|
138
|
-
* fix (misconfiguration, missing resume point). Runtime failures — a dropped
|
|
139
|
-
* chain-sync socket, a provider outage, a node restart — must leave it false,
|
|
140
|
-
* otherwise a routine node restart silently disables the pre-sync for good.
|
|
141
|
-
*/
|
|
209
|
+
// Halt without awaiting the pipeline, so it is safe to call from inside it.
|
|
210
|
+
// `latch` keeps the crawler down across restarts. Use it only for misconfiguration, never for outages.
|
|
142
211
|
async halt(finalStatus = 'stopped', latch = false) {
|
|
143
212
|
this.beginHalt(finalStatus, latch);
|
|
144
213
|
}
|
|
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
|
-
*/
|
|
214
|
+
/** Start teardown without awaiting it, so tracked callbacks can halt from inside themselves. */
|
|
149
215
|
beginHalt(finalStatus, latch = false) {
|
|
150
216
|
if (latch)
|
|
151
217
|
this.latchOnHalt = true;
|
|
@@ -153,7 +219,13 @@ class CardanoCrawler {
|
|
|
153
219
|
if (this.finalStatus !== 'error' || finalStatus === 'error')
|
|
154
220
|
this.finalStatus = finalStatus;
|
|
155
221
|
this.running = false;
|
|
222
|
+
this.activeSource = null;
|
|
223
|
+
// Background asset enrichment belongs to the crawl and must not outlive it.
|
|
224
|
+
this.indexer.stopAssetEnrichment();
|
|
156
225
|
this.wake?.(); // cancel a pending poll sleep so the loop exits now
|
|
226
|
+
this.clearIdleWatchdog();
|
|
227
|
+
this.stopChainSyncProbing();
|
|
228
|
+
this.streamEnded?.(); // release the ingest loop, the pipeline is awaited below
|
|
157
229
|
this.leaseWake?.();
|
|
158
230
|
for (const cancel of [...this.callCancels])
|
|
159
231
|
cancel();
|
|
@@ -180,6 +252,8 @@ class CardanoCrawler {
|
|
|
180
252
|
}
|
|
181
253
|
if (this.leaseHeartbeat)
|
|
182
254
|
await this.leaseHeartbeat.catch(() => undefined);
|
|
255
|
+
if (this.chainSyncProbe)
|
|
256
|
+
await this.chainSyncProbe.catch(() => undefined);
|
|
183
257
|
try {
|
|
184
258
|
if (this.leaseOwner && this.leaseHeld) {
|
|
185
259
|
await cds_1.default.tx((tx) => (0, sync_state_1.releaseCrawlerLease)(tx, this.leaseOwner, this.finalStatus, this.latchOnHalt));
|
|
@@ -193,21 +267,85 @@ class CardanoCrawler {
|
|
|
193
267
|
});
|
|
194
268
|
}
|
|
195
269
|
async runIngestPipeline() {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
270
|
+
while (this.running) {
|
|
271
|
+
const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
|
|
272
|
+
if (chainSync) {
|
|
273
|
+
// One pass per chain-sync stream. An unparseable frame ends the stream, not the crawler:
|
|
274
|
+
// pagination fetches that block, then chain-sync takes over again. Other errors halt.
|
|
275
|
+
while (this.running) {
|
|
276
|
+
const streamEnd = new Promise((resolve) => { this.streamEnded = resolve; });
|
|
277
|
+
await this.runChainSync(chainSync);
|
|
278
|
+
if (!this.chainSyncHandle)
|
|
279
|
+
return; // open refused, halted, or stop() raced us
|
|
280
|
+
await streamEnd;
|
|
281
|
+
const failure = this.takeFrameFailure();
|
|
282
|
+
if (!this.running)
|
|
283
|
+
return;
|
|
284
|
+
if (this.reopenStream) {
|
|
285
|
+
this.reopenStream = false;
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (failure?.height == null)
|
|
289
|
+
return;
|
|
290
|
+
logger.warn(`chain-sync cannot deliver block ${failure.height}, switching to pagination until it is behind the cursor`);
|
|
291
|
+
await this.runPagination({ untilHeight: failure.height + 1 });
|
|
292
|
+
}
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (this.config.source === 'ogmios') {
|
|
296
|
+
// 'ogmios' means chain-sync only. Never fall back to pagination the operator opted out of.
|
|
297
|
+
logger.error("Crawler source is 'ogmios' but no chain-sync backend is available. Crawler not started (use source 'auto' to allow pagination fallback).");
|
|
298
|
+
await this.halt('error', true); // config error: a restart cannot fix it
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
if (this.config.source === 'pagination') {
|
|
302
|
+
await this.runPagination();
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
// 'auto' with no usable chain-sync backend (typical while the node still replays after a
|
|
306
|
+
// restart): crawl on pagination and keep retrying chain-sync.
|
|
307
|
+
logger.warn('No chain-sync backend usable, crawling on pagination and retrying chain-sync periodically');
|
|
308
|
+
await this.runPagination({ untilChainSync: true });
|
|
309
|
+
// Returned because chain-sync came back (or we stopped): the loop reopens it.
|
|
200
310
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
311
|
+
}
|
|
312
|
+
// Retry the chain-sync init on its own timer, because a poll sleep can last an hour.
|
|
313
|
+
// On success the sleep is cut short and the ingest loop reopens chain-sync.
|
|
314
|
+
startChainSyncProbing() {
|
|
315
|
+
this.chainSyncRecovered = false;
|
|
316
|
+
// The startup init has just failed, so give the node a full interval first.
|
|
317
|
+
this.scheduleChainSyncProbe();
|
|
318
|
+
}
|
|
319
|
+
scheduleChainSyncProbe() {
|
|
320
|
+
if (!this.running || this.chainSyncRecovered || this.chainSyncProbeTimer)
|
|
206
321
|
return;
|
|
207
|
-
|
|
208
|
-
|
|
322
|
+
const timer = setTimeout(() => {
|
|
323
|
+
this.chainSyncProbeTimer = null;
|
|
324
|
+
if (!this.running || this.chainSyncRecovered)
|
|
325
|
+
return;
|
|
326
|
+
this.chainSyncProbe = this.client.recoverChainSyncBackend()
|
|
327
|
+
.then((backend) => {
|
|
328
|
+
if (!backend || !this.running)
|
|
329
|
+
return;
|
|
330
|
+
this.chainSyncRecovered = true;
|
|
331
|
+
this.wake?.(); // a poll sleep must not hold the handover back
|
|
332
|
+
})
|
|
333
|
+
.catch((err) => logger.debug('chain-sync probe failed:', err))
|
|
334
|
+
.finally(() => {
|
|
335
|
+
this.chainSyncProbe = null;
|
|
336
|
+
this.scheduleChainSyncProbe();
|
|
337
|
+
});
|
|
338
|
+
}, CardanoCrawler.CHAIN_SYNC_RETRY_MS);
|
|
339
|
+
timer.unref?.(); // never keep the process alive for a probe
|
|
340
|
+
this.chainSyncProbeTimer = timer;
|
|
209
341
|
}
|
|
210
|
-
|
|
342
|
+
stopChainSyncProbing() {
|
|
343
|
+
if (!this.chainSyncProbeTimer)
|
|
344
|
+
return;
|
|
345
|
+
clearTimeout(this.chainSyncProbeTimer);
|
|
346
|
+
this.chainSyncProbeTimer = null;
|
|
347
|
+
}
|
|
348
|
+
/** Bound a direct backend call. These calls bypass the client's timeout and circuit breaker. */
|
|
211
349
|
withTimeout(p, label, ms = CardanoCrawler.CALL_TIMEOUT_MS) {
|
|
212
350
|
return new Promise((resolve, reject) => {
|
|
213
351
|
let settled = false;
|
|
@@ -229,47 +367,73 @@ class CardanoCrawler {
|
|
|
229
367
|
});
|
|
230
368
|
}
|
|
231
369
|
// ---------------------------------------------------------------------------
|
|
232
|
-
// Chain-sync (Ogmios)
|
|
370
|
+
// Chain-sync (Ogmios): primary source, reorg-aware
|
|
233
371
|
// ---------------------------------------------------------------------------
|
|
234
372
|
async runChainSync(backend) {
|
|
235
373
|
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
236
374
|
const points = await this.buildIntersectionPoints(cursor);
|
|
237
375
|
if (!points.length) {
|
|
238
|
-
//
|
|
376
|
+
// start() already refuses this state.
|
|
239
377
|
logger.error('Chain-sync refused: no resume point (configured start block or cursor) available.');
|
|
240
378
|
await this.halt('error', true); // config error: a restart cannot fix it
|
|
241
379
|
return;
|
|
242
380
|
}
|
|
381
|
+
this.blocksThisStream = 0;
|
|
243
382
|
const handle = await backend.openChainSync(points, {
|
|
244
383
|
rollForward: (block, txs, tip) => this.trackCallback(async () => {
|
|
245
384
|
if (!this.running)
|
|
246
385
|
return;
|
|
247
|
-
|
|
386
|
+
this.clearIdleWatchdog();
|
|
387
|
+
if (await this.persistBlock(block, txs, tip)) {
|
|
388
|
+
this.blocksThisStream++;
|
|
389
|
+
this.idleReopens = 0;
|
|
390
|
+
}
|
|
391
|
+
this.armIdleWatchdog();
|
|
248
392
|
}),
|
|
249
393
|
rollBackward: (point) => this.trackCallback(async () => {
|
|
250
394
|
if (!this.running)
|
|
251
395
|
return;
|
|
252
|
-
|
|
253
|
-
//
|
|
254
|
-
// the point differs from
|
|
396
|
+
this.clearIdleWatchdog();
|
|
397
|
+
// Ogmios always opens the stream with a rollBackward to the intersection. That is the
|
|
398
|
+
// handshake, not a reorg, so only roll back when the point differs from the cursor.
|
|
255
399
|
const current = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
256
400
|
if (point !== 'origin' && current?.lastBlockHash === point.hash) {
|
|
257
|
-
logger.debug(`chain-sync intersection acknowledged at slot ${point.slot}
|
|
258
|
-
return;
|
|
401
|
+
logger.debug(`chain-sync intersection acknowledged at slot ${point.slot}, no reorg`);
|
|
259
402
|
}
|
|
260
|
-
|
|
403
|
+
else {
|
|
404
|
+
await this.handleReorg(point);
|
|
405
|
+
}
|
|
406
|
+
this.armIdleWatchdog();
|
|
261
407
|
}),
|
|
262
408
|
onError: (err) => this.trackCallback(async () => {
|
|
263
409
|
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
|
|
264
410
|
return;
|
|
265
|
-
//
|
|
266
|
-
|
|
411
|
+
// An unparseable frame is a fault of that one block. Pagination can still fetch it.
|
|
412
|
+
if (err instanceof errors_1.ChainSyncFrameError && this.canDegradeToPagination(err)) {
|
|
413
|
+
await this.degradeToPagination(err);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
// Socket dropped. After progress, reopen at the cursor. Without progress the server
|
|
417
|
+
// cannot decode the next block, so fetch that block over pagination first.
|
|
418
|
+
if (err instanceof errors_1.ChainSyncClosedError) {
|
|
419
|
+
if (this.blocksThisStream > 0) {
|
|
420
|
+
logger.warn(`${err.message} after ${this.blocksThisStream} block(s), reopening chain-sync at the cursor`);
|
|
421
|
+
await this.endStream(() => { this.reopenStream = true; });
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
425
|
+
if (cursor && this.config.source !== 'ogmios' && this.client.getPaginatingBackend()) {
|
|
426
|
+
await this.degradeToPagination(new errors_1.ChainSyncStalledError(cursor.lastHeight + 1, err.message));
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
// Record and halt, so the cursor shows 'error' instead of a healthy-looking hang.
|
|
267
431
|
const streak = await this.recordCrawlerError(err);
|
|
268
|
-
logger.error('Chain-sync stream error
|
|
432
|
+
logger.error('Chain-sync stream error, stopping crawler:', err);
|
|
269
433
|
await this.halt(streak < 0 ? 'stopped' : 'error');
|
|
270
434
|
}),
|
|
271
435
|
});
|
|
272
|
-
// stop() may have raced the async open
|
|
436
|
+
// stop() may have raced the async open. Close the fresh socket instead of leaking it.
|
|
273
437
|
if (!this.running) {
|
|
274
438
|
try {
|
|
275
439
|
await handle.close();
|
|
@@ -278,20 +442,74 @@ class CardanoCrawler {
|
|
|
278
442
|
return;
|
|
279
443
|
}
|
|
280
444
|
this.chainSyncHandle = handle;
|
|
445
|
+
this.activeSource = 'chain-sync';
|
|
446
|
+
this.armIdleWatchdog();
|
|
281
447
|
logger.info(`Crawler running (chain-sync) from ${points[0].hash} (+${points.length - 1} fallback intersection point(s))`);
|
|
282
448
|
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
449
|
+
// Starts the silence timer of the open stream. It runs only between frames, so a block that
|
|
450
|
+
// takes long to store never counts as silence. A half-open socket sends neither frames nor a close.
|
|
451
|
+
armIdleWatchdog() {
|
|
452
|
+
this.clearIdleWatchdog();
|
|
453
|
+
if (!this.running || !this.chainSyncHandle)
|
|
454
|
+
return;
|
|
455
|
+
const idleMs = CardanoCrawler.CHAIN_SYNC_IDLE_MS;
|
|
456
|
+
this.idleTimer = setTimeout(() => {
|
|
457
|
+
this.idleTimer = null;
|
|
458
|
+
if (!this.running || !this.chainSyncHandle)
|
|
459
|
+
return;
|
|
460
|
+
const message = `chain-sync delivered nothing for ${Math.round(idleMs / 1000)} s, reopening at the cursor`;
|
|
461
|
+
if (this.idleReopens++ === 0)
|
|
462
|
+
logger.warn(message);
|
|
463
|
+
else
|
|
464
|
+
logger.debug(message);
|
|
465
|
+
void this.trackCallback(() => this.endStream(() => { this.reopenStream = true; }));
|
|
466
|
+
}, idleMs);
|
|
467
|
+
this.idleTimer.unref?.();
|
|
468
|
+
}
|
|
469
|
+
clearIdleWatchdog() {
|
|
470
|
+
if (this.idleTimer)
|
|
471
|
+
clearTimeout(this.idleTimer);
|
|
472
|
+
this.idleTimer = null;
|
|
473
|
+
}
|
|
474
|
+
/** Read and clear the pending frame failure, so each stream starts from a clean slate. */
|
|
475
|
+
takeFrameFailure() {
|
|
476
|
+
const failure = this.frameFailure;
|
|
477
|
+
this.frameFailure = null;
|
|
478
|
+
return failure;
|
|
479
|
+
}
|
|
480
|
+
canDegradeToPagination(err) {
|
|
481
|
+
return err.height != null
|
|
482
|
+
&& this.config.source !== 'ogmios'
|
|
483
|
+
&& !!this.client.getPaginatingBackend();
|
|
484
|
+
}
|
|
485
|
+
/** End the stream so the ingest loop passes the bad block on pagination. Records first, so `lastError` names it. */
|
|
486
|
+
async degradeToPagination(err) {
|
|
487
|
+
const streak = await this.recordCrawlerError(err);
|
|
488
|
+
if (streak < 0) {
|
|
489
|
+
await this.halt('stopped');
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
logger.error('Chain-sync cannot deliver a block, continuing on pagination:', err.message);
|
|
493
|
+
await this.endStream(() => { this.frameFailure = err; });
|
|
494
|
+
}
|
|
495
|
+
/** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
|
|
496
|
+
async endStream(mark) {
|
|
497
|
+
mark();
|
|
498
|
+
this.clearIdleWatchdog();
|
|
499
|
+
const handle = this.chainSyncHandle;
|
|
500
|
+
this.chainSyncHandle = null;
|
|
501
|
+
if (handle) {
|
|
502
|
+
try {
|
|
503
|
+
await handle.close();
|
|
504
|
+
}
|
|
505
|
+
catch (e) {
|
|
506
|
+
logger.warn('chain-sync close failed:', e);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
this.streamEnded?.();
|
|
510
|
+
}
|
|
511
|
+
// Intersection points, newest first: cursor, crawled ancestors, configured start block.
|
|
512
|
+
// The ancestors let the node find the last common block if the cursor was orphaned.
|
|
295
513
|
async buildIntersectionPoints(cursor) {
|
|
296
514
|
const points = [];
|
|
297
515
|
const seen = new Set();
|
|
@@ -303,11 +521,8 @@ class CardanoCrawler {
|
|
|
303
521
|
};
|
|
304
522
|
if (cursor?.lastBlockHash) {
|
|
305
523
|
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.
|
|
524
|
+
// Dense over the last DENSE_DEPTH blocks (real rollbacks are shallow and must intersect
|
|
525
|
+
// exactly), doubling after that for deep-reorg reach without hundreds of points.
|
|
311
526
|
const DENSE_DEPTH = 10;
|
|
312
527
|
const heights = [];
|
|
313
528
|
const pushHeight = (height) => { if (height > 0 && !heights.includes(height))
|
|
@@ -337,36 +552,54 @@ class CardanoCrawler {
|
|
|
337
552
|
return promise;
|
|
338
553
|
}
|
|
339
554
|
// ---------------------------------------------------------------------------
|
|
340
|
-
// Pagination (Blockfrost
|
|
555
|
+
// Pagination (Blockfrost, Koios): fallback source
|
|
341
556
|
// ---------------------------------------------------------------------------
|
|
342
|
-
|
|
557
|
+
/** `untilHeight` returns once the cursor reaches it. `untilChainSync` returns once chain-sync is usable again. */
|
|
558
|
+
async runPagination(opts = {}) {
|
|
559
|
+
if (opts.untilChainSync)
|
|
560
|
+
this.startChainSyncProbing();
|
|
561
|
+
try {
|
|
562
|
+
await this.paginate(opts);
|
|
563
|
+
}
|
|
564
|
+
finally {
|
|
565
|
+
this.stopChainSyncProbing();
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
async paginate({ untilHeight, untilChainSync = false }) {
|
|
343
569
|
const backend = this.client.getPaginatingBackend();
|
|
344
570
|
if (!backend) {
|
|
345
|
-
logger.error('No paginating backend available
|
|
571
|
+
logger.error('No paginating backend available: cannot crawl without Ogmios or Blockfrost/Koios');
|
|
346
572
|
await this.halt('error', true); // config error: a restart cannot fix it
|
|
347
573
|
return;
|
|
348
574
|
}
|
|
575
|
+
backend.configureCrawl?.({ certificates: this.config.certificates });
|
|
576
|
+
this.activeSource = 'pagination';
|
|
349
577
|
logger.info('Crawler running (pagination)');
|
|
350
|
-
// Tip cache
|
|
351
|
-
// behind the target" matters) — refetching it every round wasted one HTTP call
|
|
352
|
-
// per batch. Refresh only when the cursor reaches the cached target.
|
|
578
|
+
// Tip cache, refreshed only when the cursor reaches the cached target.
|
|
353
579
|
let tip = null;
|
|
354
580
|
let target = Number.NEGATIVE_INFINITY;
|
|
355
581
|
while (this.running) {
|
|
356
582
|
try {
|
|
583
|
+
if (untilChainSync && this.chainSyncRecovered) {
|
|
584
|
+
logger.info('chain-sync backend usable again, leaving pagination');
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
357
587
|
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
358
588
|
if (!cursor?.lastBlockHash) {
|
|
359
589
|
logger.error('Pagination refused: cursor has no resume block hash.');
|
|
360
590
|
await this.halt('error', true); // broken precondition: a restart cannot fix it
|
|
361
591
|
return;
|
|
362
592
|
}
|
|
593
|
+
if (untilHeight != null && cursor.lastHeight >= untilHeight) {
|
|
594
|
+
logger.info(`pagination reached block ${cursor.lastHeight}, handing back to chain-sync`);
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
363
597
|
if (!tip || cursor.lastHeight >= target) {
|
|
364
598
|
tip = await this.withTimeout(this.client.getLatestBlock(), 'getLatestBlock');
|
|
365
599
|
target = (tip.height ?? 0) - this.config.confirmationDepth;
|
|
366
600
|
}
|
|
367
601
|
const tipHeight = tip.height ?? 0;
|
|
368
|
-
//
|
|
369
|
-
// block 'synced' (block.slot >= 0 is always true).
|
|
602
|
+
// An unknown tip slot means "not at tip". A 0 fallback would mark every block 'synced'.
|
|
370
603
|
const tipPoint = tip.slot != null
|
|
371
604
|
? { slot: tip.slot, hash: tip.hash, height: tipHeight }
|
|
372
605
|
: undefined;
|
|
@@ -381,15 +614,14 @@ class CardanoCrawler {
|
|
|
381
614
|
await this.halt('stopped');
|
|
382
615
|
return;
|
|
383
616
|
}
|
|
384
|
-
await this.
|
|
617
|
+
await this.pollPause(untilChainSync);
|
|
385
618
|
continue;
|
|
386
619
|
}
|
|
387
620
|
const blocks = await this.withTimeout(
|
|
388
|
-
//
|
|
389
|
-
// on a fresh start without configured startHeight)
|
|
621
|
+
// Cursor height as a hint. Height 0 can mean unknown on a fresh start.
|
|
390
622
|
backend.getNextBlocks(cursor.lastBlockHash, this.config.batchSize, cursor.lastHeight > 0 ? cursor.lastHeight : undefined), 'getNextBlocks');
|
|
391
623
|
if (!blocks.length) {
|
|
392
|
-
await this.
|
|
624
|
+
await this.pollPause(untilChainSync);
|
|
393
625
|
continue;
|
|
394
626
|
}
|
|
395
627
|
for (const block of blocks) {
|
|
@@ -401,14 +633,16 @@ class CardanoCrawler {
|
|
|
401
633
|
const ok = await this.persistBlock(block, txs, tipPoint);
|
|
402
634
|
if (!ok)
|
|
403
635
|
return; // persistBlock already recorded + halted
|
|
636
|
+
// Chain-sync came back mid-batch. Streaming the rest is cheaper than fetching it.
|
|
637
|
+
if (untilChainSync && this.chainSyncRecovered)
|
|
638
|
+
break;
|
|
404
639
|
}
|
|
405
640
|
}
|
|
406
641
|
catch (err) {
|
|
407
642
|
if (!this.running || err instanceof CrawlerStoppedError)
|
|
408
643
|
return;
|
|
409
|
-
// Only
|
|
410
|
-
//
|
|
411
|
-
// of launching up to 100 additional provider calls.
|
|
644
|
+
// Only an explicit chain point mismatch suggests an orphaned cursor.
|
|
645
|
+
// Outages back off instead of starting up to 100 more provider calls.
|
|
412
646
|
if (err instanceof Error && err.message.startsWith(CHAIN_POINT_MISMATCH_PREFIX)) {
|
|
413
647
|
const recovered = await this.tryReorgRecovery(backend).catch(() => false);
|
|
414
648
|
if (recovered)
|
|
@@ -426,15 +660,18 @@ 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
|
}
|
|
433
|
-
/**
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
667
|
+
/** Skipped when a chain-sync handover is due, since the probe's wake-up only reaches a running sleep. */
|
|
668
|
+
async pollPause(untilChainSync) {
|
|
669
|
+
if (untilChainSync && this.chainSyncRecovered)
|
|
670
|
+
return;
|
|
671
|
+
await this.sleep(this.config.pollIntervalMs);
|
|
672
|
+
}
|
|
673
|
+
// Walk back by height until the on-chain hash matches the stored one. That height is the fork point.
|
|
674
|
+
// Returns false if the cursor block still matches, so the error counts as transient.
|
|
438
675
|
async tryReorgRecovery(backend) {
|
|
439
676
|
if (!this.running)
|
|
440
677
|
return false;
|
|
@@ -461,10 +698,7 @@ class CardanoCrawler {
|
|
|
461
698
|
if (ours?.hash && onChain.hash === ours.hash) {
|
|
462
699
|
if (h === cursor.lastHeight)
|
|
463
700
|
return false; // tip still matches → not a reorg
|
|
464
|
-
//
|
|
465
|
-
// (BlockData.slot is nullable) would make forkSlot 0 and wipe the ENTIRE
|
|
466
|
-
// crawled dataset — abort this round instead; the next round can retry with
|
|
467
|
-
// a healthy provider response. (Same guard philosophy as the height axis.)
|
|
701
|
+
// A null slot would make forkSlot 0 and wipe all crawled data.
|
|
468
702
|
if (onChain.slot == null)
|
|
469
703
|
return false;
|
|
470
704
|
await this.handleReorg({ slot: onChain.slot, hash: onChain.hash, height: h });
|
|
@@ -476,20 +710,13 @@ class CardanoCrawler {
|
|
|
476
710
|
// ---------------------------------------------------------------------------
|
|
477
711
|
// Persist + reorg (shared)
|
|
478
712
|
// ---------------------------------------------------------------------------
|
|
479
|
-
/**
|
|
480
|
-
* Persist one block atomically and advance the cursor. Transient failures are retried
|
|
481
|
-
* a few times (recording the error streak); only repeated failure stops the crawler —
|
|
482
|
-
* the cursor is not advanced on failure, so a resume re-syncs cleanly from it.
|
|
483
|
-
* Marks the cursor 'synced' when the block is at the reported tip.
|
|
484
|
-
* @returns true when the block was persisted, false when the crawler was stopped
|
|
485
|
-
*/
|
|
713
|
+
/** Persist one block atomically and advance the cursor. Returns false when the crawler stopped. */
|
|
486
714
|
async persistBlock(block, txs, tip) {
|
|
487
715
|
if (txs.length !== block.txCount) {
|
|
488
716
|
throw new errors_1.ProviderUnavailableError(`Incomplete block ${block.hash}: backend returned ${txs.length}/${block.txCount} transactions`, 'crawler');
|
|
489
717
|
}
|
|
490
718
|
const isAtTip = tip != null && block.slot != null && block.slot >= tip.slot;
|
|
491
|
-
//
|
|
492
|
-
// opening the write transaction so the DB lock is never held across network I/O.
|
|
719
|
+
// Fetch epoch data before the write transaction, so no DB lock is held across network I/O.
|
|
493
720
|
if (block.epoch != null) {
|
|
494
721
|
await this.indexer.prefetchCrawlEpoch(block.epoch);
|
|
495
722
|
}
|
|
@@ -498,16 +725,25 @@ class CardanoCrawler {
|
|
|
498
725
|
return false;
|
|
499
726
|
try {
|
|
500
727
|
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
728
|
await this.indexer.indexBlockFull(tx, block, txs);
|
|
507
|
-
|
|
729
|
+
// Written with the cursor, so a cursor ahead of this marker means blocks skipped the set.
|
|
730
|
+
const anchor = this.indexer.getUtxoAnchor();
|
|
731
|
+
const ledgerApplied = anchor != null && (block.slot ?? 0) > anchor.slot;
|
|
732
|
+
// The cursor UPDATE also renews and fences the lease; a lost lease rolls the block back.
|
|
733
|
+
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);
|
|
734
|
+
if (!leaseHeld)
|
|
735
|
+
throw new CrawlerLeaseLostError();
|
|
508
736
|
});
|
|
509
|
-
|
|
510
|
-
|
|
737
|
+
this.leaseRenewedAt = Date.now();
|
|
738
|
+
this.indexer.confirmBlockCommit();
|
|
739
|
+
if (CardanoCrawler.poison?.hash === block.hash)
|
|
740
|
+
CardanoCrawler.poison = null;
|
|
741
|
+
// Applied in memory only after the commit, so a rolled-back attempt changes nothing.
|
|
742
|
+
const invalidation = this.indexer.takeLedgerInvalidation();
|
|
743
|
+
if (invalidation) {
|
|
744
|
+
logger.error(`UTxO set invalidated: ${invalidation}. Ledger tables stop updating until importUtxoSet runs again`);
|
|
745
|
+
}
|
|
746
|
+
// Notify observers after the commit. emitBlockIndexed swallows listener failures.
|
|
511
747
|
(0, hooks_1.emitBlockIndexed)({
|
|
512
748
|
hash: block.hash,
|
|
513
749
|
slot: block.slot ?? null,
|
|
@@ -516,6 +752,7 @@ class CardanoCrawler {
|
|
|
516
752
|
tipSlot: tip?.slot ?? null,
|
|
517
753
|
tipHeight: tip?.height ?? null,
|
|
518
754
|
});
|
|
755
|
+
this.maybeSnapshotEpoch(block, tip);
|
|
519
756
|
return true;
|
|
520
757
|
}
|
|
521
758
|
catch (err) {
|
|
@@ -530,31 +767,123 @@ class CardanoCrawler {
|
|
|
530
767
|
return false;
|
|
531
768
|
}
|
|
532
769
|
if (attempt < CardanoCrawler.PERSIST_RETRIES && streak < sync_state_1.MAX_CONSECUTIVE_ERRORS) {
|
|
533
|
-
logger.warn(`persistBlock ${block.hash} failed (attempt ${attempt}/${CardanoCrawler.PERSIST_RETRIES}, streak ${streak})
|
|
770
|
+
logger.warn(`persistBlock ${block.hash} failed (attempt ${attempt}/${CardanoCrawler.PERSIST_RETRIES}, streak ${streak}), retrying:`, err);
|
|
534
771
|
await this.sleep(1000 * attempt);
|
|
535
772
|
continue;
|
|
536
773
|
}
|
|
537
|
-
|
|
774
|
+
const dataRejection = CardanoCrawler.isDataRejection(err);
|
|
775
|
+
const failures = dataRejection ? CardanoCrawler.notePersistFailure(block.hash) : 0;
|
|
776
|
+
if (failures >= CardanoCrawler.POISON_BLOCK_THRESHOLD) {
|
|
777
|
+
const cause = err instanceof Error ? err.message : String(err);
|
|
778
|
+
const message = `poison block ${block.hash} @${block.height ?? '?'} failed ${failures}x: ${cause}`;
|
|
779
|
+
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);
|
|
780
|
+
// Memory is cleared only once the latch is stored, so a failed write retries after restart.
|
|
781
|
+
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; });
|
|
782
|
+
if (latched)
|
|
783
|
+
CardanoCrawler.poison = null;
|
|
784
|
+
await this.halt('error', true);
|
|
785
|
+
return false;
|
|
786
|
+
}
|
|
787
|
+
const perBlock = dataRejection ? ` (${failures}/${CardanoCrawler.POISON_BLOCK_THRESHOLD} for this block)` : '';
|
|
788
|
+
logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts${perBlock}, stopping crawler (resume re-syncs from cursor):`, err);
|
|
538
789
|
await this.halt('error');
|
|
539
790
|
return false;
|
|
540
791
|
}
|
|
541
792
|
}
|
|
542
793
|
}
|
|
543
|
-
/**
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
794
|
+
/** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
|
|
795
|
+
epochOfSlot(slot) {
|
|
796
|
+
const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network]
|
|
797
|
+
?? const_1.EPOCH_CONFIG_BY_NETWORK.preview;
|
|
798
|
+
return cfg.shelleyStartEpoch + Math.floor((slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
|
|
799
|
+
}
|
|
800
|
+
// Snapshot pools and DReps once per epoch. Ogmios reads the ledger at a block within k of the tip.
|
|
801
|
+
// Koios reports only current state, so the crawl must be in the tip's epoch. Other epochs are skipped.
|
|
802
|
+
maybeSnapshotEpoch(block, tip) {
|
|
803
|
+
if (!this.config.epochSnapshots || block.epoch == null)
|
|
804
|
+
return;
|
|
805
|
+
if (this.snapshotedEpoch === block.epoch || this.snapshotInFlight)
|
|
806
|
+
return;
|
|
807
|
+
// Without a tip the crawler cannot prove it is live.
|
|
808
|
+
if (tip == null) {
|
|
809
|
+
logger.debug(`epoch ${block.epoch} snapshot skipped: no chain tip reported for this block`);
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
const fromLedger = this.client.getEpochStateBackend() != null && !!block.hash;
|
|
813
|
+
if (fromLedger) {
|
|
814
|
+
const k = const_1.EPOCH_CONFIG_BY_NETWORK[this.network]?.securityParam
|
|
815
|
+
?? const_1.EPOCH_CONFIG_BY_NETWORK.mainnet.securityParam;
|
|
816
|
+
const behind = tip.height != null && block.height != null ? tip.height - block.height : null;
|
|
817
|
+
if (behind == null || behind >= k - CardanoCrawler.SNAPSHOT_WINDOW_MARGIN) {
|
|
818
|
+
logger.debug(`epoch ${block.epoch} snapshot skipped at height ${block.height}: ${behind ?? '?'} blocks behind the tip, outside the node's volatile window (k=${k})`);
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
else {
|
|
823
|
+
const tipEpoch = this.epochOfSlot(tip.slot);
|
|
824
|
+
if (block.epoch !== tipEpoch) {
|
|
825
|
+
logger.debug(`epoch ${block.epoch} snapshot skipped: still backfilling (tip is in epoch ${tipEpoch}); ` +
|
|
826
|
+
`the provider reports the pool/DRep set as it is now, never as it was`);
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
if (Date.now() < this.snapshotRetryAfter)
|
|
831
|
+
return;
|
|
832
|
+
const epoch = block.epoch;
|
|
833
|
+
const at = { slot: block.slot ?? 0, time: block.time ?? 0, hash: fromLedger ? block.hash : null };
|
|
834
|
+
this.snapshotInFlight = this.trackCallback(async () => {
|
|
835
|
+
const existing = await cds_1.default.tx(async (tx) => (await tx.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('epoch').where({ epoch })))
|
|
836
|
+
?? (await tx.run(SELECT.one.from(cardano_1.PoolEpochSnapshots).columns('epoch').where({ epoch }))));
|
|
837
|
+
if (!existing) {
|
|
838
|
+
await this.withTimeout(this.indexer.snapshotEpoch(epoch, at), `snapshotEpoch(${epoch})`, CardanoCrawler.SNAPSHOT_TIMEOUT_MS);
|
|
839
|
+
const previous = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.EpochLedgerSnapshots).columns('max(epoch) as e').where({ epoch: { '<': epoch } })));
|
|
840
|
+
const last = previous?.e == null ? null : Number(previous.e);
|
|
841
|
+
if (last != null && epoch > last + 1) {
|
|
842
|
+
logger.warn(`epoch snapshots missing for epochs ${last + 1}..${epoch - 1}: passed outside the snapshot window`);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
await this.maybeSnapshotAccounts(epoch, at);
|
|
846
|
+
this.snapshotedEpoch = epoch;
|
|
847
|
+
this.snapshotFailures = 0;
|
|
848
|
+
this.snapshotRetryAfter = 0;
|
|
849
|
+
})
|
|
850
|
+
.catch((err) => {
|
|
851
|
+
// Never fatal. The epoch is retried after a backoff, so an outage does not re-run per block.
|
|
852
|
+
this.snapshotFailures++;
|
|
853
|
+
const backoff = Math.min(CardanoCrawler.SNAPSHOT_RETRY_BASE_MS * 2 ** (this.snapshotFailures - 1), CardanoCrawler.SNAPSHOT_RETRY_MAX_MS);
|
|
854
|
+
this.snapshotRetryAfter = Date.now() + backoff;
|
|
855
|
+
if (this.running)
|
|
856
|
+
logger.error(`epoch ${epoch} snapshot failed (retry in ${backoff} ms):`, err);
|
|
857
|
+
})
|
|
858
|
+
.finally(() => { this.snapshotInFlight = null; });
|
|
859
|
+
}
|
|
860
|
+
// The account snapshot of an epoch, after its pool snapshot. Skipped with one warning without a
|
|
861
|
+
// backend that reads the ledger at a block.
|
|
862
|
+
async maybeSnapshotAccounts(epoch, at) {
|
|
863
|
+
if (!this.config.accountSnapshots)
|
|
864
|
+
return;
|
|
865
|
+
const backend = at.hash ? this.client.getRewardAccountStateBackend() : null;
|
|
866
|
+
if (!backend || !at.hash) {
|
|
867
|
+
if (!this.accountSnapshotWarned)
|
|
868
|
+
logger.warn('account snapshots need Ogmios (the ledger at the snapshot block); none is taken');
|
|
869
|
+
this.accountSnapshotWarned = true;
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
await this.withTimeout((0, account_snapshots_1.snapshotAccounts)({
|
|
873
|
+
backend, epoch, at: { slot: at.slot, hash: at.hash },
|
|
874
|
+
withdrawals: this.config.certificates,
|
|
875
|
+
shouldStop: () => !this.running,
|
|
876
|
+
}), `snapshotAccounts(${epoch})`, CardanoCrawler.ACCOUNT_SNAPSHOT_TIMEOUT_MS);
|
|
877
|
+
}
|
|
878
|
+
// Roll back in one transaction. Deletes blocks after the fork slot, never by height, and their transactions.
|
|
879
|
+
// Lazily indexed transactions of other blocks stay. Resets the cursor and logs the reorg.
|
|
553
880
|
async handleReorg(point) {
|
|
554
881
|
const forkSlot = point === 'origin' ? (this.config.startSlot ?? 0) : point.slot;
|
|
555
882
|
let blocksRolledBack = 0;
|
|
556
883
|
let txsRolledBack = 0;
|
|
557
884
|
let emittedForkHeight = null;
|
|
885
|
+
const rolledBackTxHashes = [];
|
|
886
|
+
let ledgerInvalidated = false;
|
|
558
887
|
try {
|
|
559
888
|
await cds_1.default.tx(async (tx) => {
|
|
560
889
|
if (this.leaseOwner) {
|
|
@@ -562,7 +891,7 @@ class CardanoCrawler {
|
|
|
562
891
|
if (!renewed)
|
|
563
892
|
throw new CrawlerLeaseLostError();
|
|
564
893
|
}
|
|
565
|
-
// Fork height is
|
|
894
|
+
// Fork height is for the cursor and the log only, never a delete criterion.
|
|
566
895
|
let forkHeight = point === 'origin' ? 0 : point.height;
|
|
567
896
|
if (forkHeight == null && point !== 'origin') {
|
|
568
897
|
const fb = await tx.run(SELECT.one.from(cardano_1.Blocks).where({ hash: point.hash }));
|
|
@@ -570,32 +899,50 @@ class CardanoCrawler {
|
|
|
570
899
|
}
|
|
571
900
|
emittedForkHeight = forkHeight ?? null;
|
|
572
901
|
// Blocks strictly after the fork, cut on the absolute-slot axis. Rows without a
|
|
573
|
-
// slot (
|
|
902
|
+
// slot (lazily indexed blocks from an older schema) are deliberately excluded.
|
|
574
903
|
const staleBlocks = await tx.run(SELECT.from(cardano_1.Blocks).columns('hash').where({ slot: { '>': forkSlot } }));
|
|
575
904
|
const blockHashes = staleBlocks.map((b) => b.hash);
|
|
576
905
|
blocksRolledBack = blockHashes.length;
|
|
577
906
|
for (const blockChunk of (0, collections_1.chunk)(blockHashes, collections_1.IN_CHUNK)) {
|
|
578
|
-
//
|
|
579
|
-
|
|
580
|
-
const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash').where({ blockHash: { in: blockChunk } }));
|
|
907
|
+
// Select by blockHash, so lazily indexed transactions of other blocks stay.
|
|
908
|
+
const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ blockHash: { in: blockChunk } }));
|
|
581
909
|
const txHashes = staleTxs.map((t) => t.hash);
|
|
582
910
|
txsRolledBack += txHashes.length;
|
|
911
|
+
rolledBackTxHashes.push(...txHashes);
|
|
583
912
|
for (const txChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
|
|
584
|
-
// These
|
|
585
|
-
// them before their parent tx/output rows so orphan data cannot leak via OData.
|
|
913
|
+
// These tables have no cascading delete. Remove them first so no orphans leak via OData.
|
|
586
914
|
await tx.run(DELETE.from(cardano_1.UTxOAssets).where({ utxo_hash: { in: txChunk } }));
|
|
587
915
|
await tx.run(DELETE.from(cardano_1.AddressUTxOs).where({ hash: { in: txChunk } }));
|
|
588
916
|
await tx.run(DELETE.from(cardano_1.AddressTransactions).where({ tx_hash: { in: txChunk } }));
|
|
589
917
|
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
918
|
}
|
|
919
|
+
await (0, transaction_rows_1.deleteTransactionRows)(tx, staleTxs);
|
|
597
920
|
await tx.run(DELETE.from(cardano_1.Blocks).where({ hash: { in: blockChunk } }));
|
|
598
921
|
}
|
|
922
|
+
// Epoch snapshots read at a rolled-back block describe a chain that no longer exists.
|
|
923
|
+
if (blocksRolledBack > 0) {
|
|
924
|
+
await (0, account_snapshots_1.dropAccountSnapshotsAfter)(tx, forkSlot);
|
|
925
|
+
for (const entity of [cardano_1.PoolEpochSnapshots, cardano_1.DrepEpochSnapshots, cardano_1.EpochLedgerSnapshots]) {
|
|
926
|
+
await tx.run(DELETE.from(entity).where({ snapshotSlot: { '>': forkSlot } }));
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
// Uses the stored status. A fork after the snapshot slot is undone, one before it invalidates the set.
|
|
930
|
+
const persisted = (await (0, sync_state_1.readCursor)(tx))?.utxoSet;
|
|
931
|
+
if (persisted?.status === 'active' && persisted.anchorSlot != null) {
|
|
932
|
+
if (forkSlot < persisted.anchorSlot) {
|
|
933
|
+
await (0, sync_state_1.setUtxoSetState)(tx, {
|
|
934
|
+
status: 'invalid',
|
|
935
|
+
error: `reorg to slot ${forkSlot} before the UTxO set anchor ${persisted.anchorSlot}: re-import the set`,
|
|
936
|
+
});
|
|
937
|
+
ledgerInvalidated = true;
|
|
938
|
+
}
|
|
939
|
+
else {
|
|
940
|
+
await (0, ledger_state_1.undoLedgerForTransactions)(tx, rolledBackTxHashes);
|
|
941
|
+
if (persisted.appliedSlot != null && persisted.appliedSlot > forkSlot) {
|
|
942
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { appliedSlot: forkSlot });
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
599
946
|
await (0, sync_state_1.resetCursorTo)(tx, point === 'origin'
|
|
600
947
|
? { slot: forkSlot, hash: this.config.startBlockHash ?? '', height: 0 }
|
|
601
948
|
: { slot: point.slot, hash: point.hash, height: forkHeight ?? 0 });
|
|
@@ -618,12 +965,16 @@ class CardanoCrawler {
|
|
|
618
965
|
}
|
|
619
966
|
throw err;
|
|
620
967
|
}
|
|
621
|
-
|
|
622
|
-
|
|
968
|
+
if (ledgerInvalidated) {
|
|
969
|
+
this.indexer.setUtxoAnchor(null);
|
|
970
|
+
logger.error(`UTxO set invalidated: reorg to slot ${forkSlot} reaches behind the anchor. Ledger tables stop updating until importUtxoSet runs again`);
|
|
971
|
+
}
|
|
972
|
+
// The rollback may have removed this epoch's snapshot. The next block re-checks it.
|
|
973
|
+
this.snapshotedEpoch = null;
|
|
623
974
|
(0, hooks_1.emitReorg)({ forkSlot, forkHeight: emittedForkHeight, blocksRolledBack });
|
|
624
975
|
logger.warn(`Reorg handled: rolled back ${blocksRolledBack} blocks (${txsRolledBack} txs) to slot ${forkSlot}`);
|
|
625
976
|
}
|
|
626
|
-
/** Renew the lease while
|
|
977
|
+
/** Renew the lease while no block commits; block writes renew it transactionally. */
|
|
627
978
|
startLeaseHeartbeat() {
|
|
628
979
|
if (!this.leaseOwner || this.leaseHeartbeat)
|
|
629
980
|
return;
|
|
@@ -633,6 +984,9 @@ class CardanoCrawler {
|
|
|
633
984
|
await this.leaseSleep(intervalMs);
|
|
634
985
|
if (!this.running)
|
|
635
986
|
return;
|
|
987
|
+
// Block commits renew the lease; the heartbeat only covers idle stretches.
|
|
988
|
+
if (Date.now() - this.leaseRenewedAt < intervalMs)
|
|
989
|
+
continue;
|
|
636
990
|
try {
|
|
637
991
|
const renewed = await cds_1.default.tx((tx) => (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner));
|
|
638
992
|
if (!renewed) {
|
|
@@ -650,6 +1004,24 @@ class CardanoCrawler {
|
|
|
650
1004
|
}
|
|
651
1005
|
})();
|
|
652
1006
|
}
|
|
1007
|
+
/** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
|
|
1008
|
+
static isDataRejection(err) {
|
|
1009
|
+
// RangeError: BigInt / number conversions in the mappers; SyntaxError: JSON of the block
|
|
1010
|
+
if (err instanceof RangeError || err instanceof SyntaxError)
|
|
1011
|
+
return true;
|
|
1012
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1013
|
+
return CardanoCrawler.DATA_REJECTION_PATTERNS.some((p) => p.test(message));
|
|
1014
|
+
}
|
|
1015
|
+
/** Count final persist failures per block hash (a different hash resets the count). */
|
|
1016
|
+
static notePersistFailure(hash) {
|
|
1017
|
+
const p = CardanoCrawler.poison;
|
|
1018
|
+
CardanoCrawler.poison = p && p.hash === hash ? { hash, failures: p.failures + 1 } : { hash, failures: 1 };
|
|
1019
|
+
return CardanoCrawler.poison.failures;
|
|
1020
|
+
}
|
|
1021
|
+
/** Test seam: forget the poison-block memory (process-wide state). */
|
|
1022
|
+
static resetPoisonMemory() {
|
|
1023
|
+
CardanoCrawler.poison = null;
|
|
1024
|
+
}
|
|
653
1025
|
/** Record state only while this instance still owns the lease. */
|
|
654
1026
|
async recordCrawlerError(err) {
|
|
655
1027
|
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
|
|
@@ -664,7 +1036,7 @@ class CardanoCrawler {
|
|
|
664
1036
|
this.leaseWake = () => { clearTimeout(timer); this.leaseWake = null; resolve(); };
|
|
665
1037
|
});
|
|
666
1038
|
}
|
|
667
|
-
/** Cancellable
|
|
1039
|
+
/** Cancellable delay. halt() wakes it so shutdown never waits out a poll. */
|
|
668
1040
|
sleep(ms) {
|
|
669
1041
|
return new Promise((resolve) => {
|
|
670
1042
|
const timer = setTimeout(() => { this.wake = null; resolve(); }, ms);
|