@odatano/core 2.0.0-rc.1 → 2.0.0-rc.11
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 +255 -0
- package/@cds-models/CardanoAgentService/index.js +36 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +37 -2
- package/@cds-models/CardanoIndexerService/index.js +4 -0
- package/@cds-models/CardanoSignService/index.d.ts +5 -2
- package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
- package/@cds-models/odatano/cardano/index.d.ts +86 -0
- package/@cds-models/odatano/cardano/index.js +6 -0
- package/README.md +62 -4
- package/db/schema.cds +105 -0
- package/package.json +9 -3
- package/src/index.d.ts +6 -0
- package/src/index.js +21 -1
- package/src/plugin.js +33 -30
- package/srv/blockchain/backends/blockfrost-backend.js +1 -10
- package/srv/blockchain/backends/koios-backend.js +1 -10
- package/srv/blockchain/backends/ogmios-backend.d.ts +29 -4
- package/srv/blockchain/backends/ogmios-backend.js +96 -7
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +77 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +181 -0
- package/srv/blockchain/cardano-indexer.d.ts +18 -0
- package/srv/blockchain/cardano-indexer.js +58 -3
- package/srv/blockchain/crawler/crawler.d.ts +55 -0
- package/srv/blockchain/crawler/crawler.js +153 -3
- package/srv/blockchain/crawler/index.d.ts +9 -0
- package/srv/blockchain/crawler/index.js +37 -4
- package/srv/blockchain/crawler/sync-state.d.ts +13 -1
- package/srv/blockchain/crawler/sync-state.js +24 -2
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
- package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
- package/srv/blockchain/wallet-worker/build-request.js +35 -6
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +32 -1
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +91 -29
- package/srv/blockchain/wallet-worker/job-store.d.ts +11 -0
- package/srv/blockchain/wallet-worker/job-store.js +42 -9
- package/srv/cardano-agent-service.cds +150 -0
- package/srv/cardano-agent-service.d.ts +2 -0
- package/srv/cardano-agent-service.js +16 -0
- package/srv/cardano-indexer-service.cds +36 -3
- package/srv/cardano-indexer-service.js +3 -0
- package/srv/cardano-service.js +57 -3
- package/srv/cardano-sign-service.cds +200 -180
- package/srv/cardano-tx-service.cds +32 -26
- package/srv/cardano-tx-service.js +96 -38
- package/srv/cardano-worker-service.cds +125 -125
- package/srv/server.d.ts +2 -1
- package/srv/server.js +18 -34
- package/srv/utils/agent-grants-config.d.ts +65 -0
- package/srv/utils/agent-grants-config.js +148 -0
- package/srv/utils/agent-grants.d.ts +314 -0
- package/srv/utils/agent-grants.js +821 -0
- package/srv/utils/agent-token-auth.d.ts +19 -0
- package/srv/utils/agent-token-auth.js +81 -0
- package/srv/utils/db-sanitize.d.ts +40 -0
- package/srv/utils/db-sanitize.js +98 -0
- package/srv/utils/errors.d.ts +18 -0
- package/srv/utils/errors.js +24 -1
- package/srv/utils/liveness.d.ts +23 -0
- package/srv/utils/liveness.js +49 -0
- package/srv/utils/mappers.d.ts +27 -0
- package/srv/utils/mappers.js +67 -7
- package/srv/utils/rate-limiter.d.ts +57 -0
- package/srv/utils/rate-limiter.js +126 -0
- package/srv/utils/tx-request-parsers.d.ts +13 -0
- package/srv/utils/tx-request-parsers.js +32 -0
- package/srv/utils/types.d.ts +34 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.widenBigIntegers = widenBigIntegers;
|
|
7
|
+
exports.installOgmiosFrameGuard = installOgmiosFrameGuard;
|
|
8
|
+
exports.resetOgmiosFrameGuardForTests = resetOgmiosFrameGuardForTests;
|
|
9
|
+
/**
|
|
10
|
+
* Guard against Ogmios chain-sync frames that the client's JSON parser cannot handle.
|
|
11
|
+
*
|
|
12
|
+
* `@cardano-ogmios/client` parses every WebSocket frame with `safeJSON.parse`, which is
|
|
13
|
+
* `sanitize(JSONBig.parse(raw))`. Both halves recurse once per nesting level: the
|
|
14
|
+
* `@cardanosolutions/json-bigint` parser is Crockford's recursive descent, and `sanitize`
|
|
15
|
+
* walks the parsed tree recursively. A native script nests one JSON object per clause, and
|
|
16
|
+
* nested clauses cost only a few bytes each in CBOR — so an ordinary-looking block can
|
|
17
|
+
* expand into JSON that is ten thousand levels deep and exhaust the V8 stack.
|
|
18
|
+
*
|
|
19
|
+
* That is not a theoretical shape. Preprod block 5183974 carries a native script nested
|
|
20
|
+
* 10 774 levels deep (`{"clause":"all","from":[ … ]}` down to a single signature clause).
|
|
21
|
+
* The block is 43 kB on chain and 205 kB as a chain-sync frame.
|
|
22
|
+
*
|
|
23
|
+
* The crash is fatal rather than merely annoying, because of where the parse happens
|
|
24
|
+
* (`ChainSynchronization/Client.js`):
|
|
25
|
+
*
|
|
26
|
+
* socket.on('message', async (message) => {
|
|
27
|
+
* await responseHandler(util_1.safeJSON.parse(message));
|
|
28
|
+
* });
|
|
29
|
+
*
|
|
30
|
+
* `safeJSON.parse` throws synchronously inside an `async` handler that nobody awaits, so
|
|
31
|
+
* the `RangeError` surfaces as an unhandled rejection and Node takes the process down. The
|
|
32
|
+
* crawler's poison-block latch cannot help: it guards the persist path, and the server is
|
|
33
|
+
* gone long before a block reaches it. Docker restarts, the crawler resumes at the same
|
|
34
|
+
* block, and the loop repeats — 53 restarts in seven minutes on the hosted box.
|
|
35
|
+
*
|
|
36
|
+
* This guard wraps `safeJSON.parse` (a public export of the client package) so that the
|
|
37
|
+
* fast path is untouched and only an overflowing frame takes the recovery route:
|
|
38
|
+
*
|
|
39
|
+
* 1. the original parser, so every ordinary frame keeps its exact BigInt handling;
|
|
40
|
+
* 2. on `RangeError`, `widenBigIntegers()` rewrites integer literals that a double cannot
|
|
41
|
+
* hold into JSON strings, then plain `JSON.parse` — V8's parser is iterative, so depth
|
|
42
|
+
* is no longer a limit. `sanitize` is skipped, because it would overflow on the very
|
|
43
|
+
* same structure;
|
|
44
|
+
* 3. if even that fails, the frame is reported to the caller and a sentinel is returned.
|
|
45
|
+
* The guard never throws, because throwing here is what kills the process.
|
|
46
|
+
*
|
|
47
|
+
* Measured against the real frame (node 22, 205 728 bytes, depth 10 774): json-bigint and
|
|
48
|
+
* `JSON.parse` with a reviver both overflow — a reviver walk is recursive too — while plain
|
|
49
|
+
* `JSON.parse` completes in 17 ms.
|
|
50
|
+
*
|
|
51
|
+
* Upstream: a recursive parser on untrusted chain data is a denial-of-service against every
|
|
52
|
+
* consumer of the client, mainnet included. This guard is a local mitigation, not the cure.
|
|
53
|
+
*/
|
|
54
|
+
const client_1 = require("@cardano-ogmios/client");
|
|
55
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
56
|
+
const logger = cds_1.default.log('OgmiosFrameGuard');
|
|
57
|
+
/**
|
|
58
|
+
* Integers outside the safe double range, written into JSON strings so that plain
|
|
59
|
+
* `JSON.parse` cannot round them. Runs as one linear pass with an explicit in-string state,
|
|
60
|
+
* never recursing, so it is immune to the nesting that sent us here in the first place.
|
|
61
|
+
*
|
|
62
|
+
* Only numbers in value position are touched: digits inside strings (hashes, CBOR, asset
|
|
63
|
+
* names) are skipped, and so are floats and exponents, which are doubles by nature and have
|
|
64
|
+
* no exact integer to preserve.
|
|
65
|
+
*/
|
|
66
|
+
function widenBigIntegers(text) {
|
|
67
|
+
const SAFE_DIGITS = String(Number.MAX_SAFE_INTEGER).length; // 16
|
|
68
|
+
let out = '';
|
|
69
|
+
let last = 0;
|
|
70
|
+
let inString = false;
|
|
71
|
+
let escaped = false;
|
|
72
|
+
for (let i = 0; i < text.length; i++) {
|
|
73
|
+
const c = text[i];
|
|
74
|
+
if (inString) {
|
|
75
|
+
if (escaped)
|
|
76
|
+
escaped = false;
|
|
77
|
+
else if (c === '\\')
|
|
78
|
+
escaped = true;
|
|
79
|
+
else if (c === '"')
|
|
80
|
+
inString = false;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (c === '"') {
|
|
84
|
+
inString = true;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
// a number literal starts here only after a structural character
|
|
88
|
+
if (c !== '-' && (c < '0' || c > '9'))
|
|
89
|
+
continue;
|
|
90
|
+
const prev = text[i - 1];
|
|
91
|
+
if (prev !== ':' && prev !== ',' && prev !== '[' && prev !== ' ' && prev !== '\n' && prev !== '\t' && prev !== '\r')
|
|
92
|
+
continue;
|
|
93
|
+
let j = i;
|
|
94
|
+
if (text[j] === '-')
|
|
95
|
+
j++;
|
|
96
|
+
const digitsFrom = j;
|
|
97
|
+
while (j < text.length && text[j] >= '0' && text[j] <= '9')
|
|
98
|
+
j++;
|
|
99
|
+
const digits = j - digitsFrom;
|
|
100
|
+
if (digits === 0)
|
|
101
|
+
continue;
|
|
102
|
+
// a fraction or exponent means it was never an exact integer — leave it alone
|
|
103
|
+
const after = text[j];
|
|
104
|
+
if (after === '.' || after === 'e' || after === 'E') {
|
|
105
|
+
i = j;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (digits >= SAFE_DIGITS) {
|
|
109
|
+
const literal = text.slice(i, j);
|
|
110
|
+
if (!Number.isSafeInteger(Number(literal))) {
|
|
111
|
+
out += text.slice(last, i) + '"' + literal + '"';
|
|
112
|
+
last = j;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
i = j - 1;
|
|
116
|
+
}
|
|
117
|
+
return last === 0 ? text : out + text.slice(last);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Block header fields out of a frame we could not parse. They sit near the front of a
|
|
121
|
+
* chain-sync response and at shallow depth, so a narrow match finds them even when the
|
|
122
|
+
* body is unusable — enough to name the offending block in a log line and in `lastError`.
|
|
123
|
+
*/
|
|
124
|
+
function readBlockHeader(text) {
|
|
125
|
+
const head = text.slice(0, 4096);
|
|
126
|
+
const id = /"id"\s*:\s*"([0-9a-fA-F]{64})"/.exec(head);
|
|
127
|
+
const height = /"height"\s*:\s*(\d{1,15})/.exec(head);
|
|
128
|
+
return { height: height ? Number(height[1]) : null, id: id ? id[1] : null };
|
|
129
|
+
}
|
|
130
|
+
let installed = false;
|
|
131
|
+
/**
|
|
132
|
+
* Wrap `safeJSON.parse` once per process. Idempotent: a second call only replaces the
|
|
133
|
+
* report callback, so reopening the chain-sync stream never stacks wrappers.
|
|
134
|
+
*
|
|
135
|
+
* @param onUnparseableFrame called when a frame survives neither parser. The guard returns
|
|
136
|
+
* a sentinel instead of throwing, so the caller owns what happens next — the stream
|
|
137
|
+
* itself stalls, because the client drops anything that is not a nextBlock response.
|
|
138
|
+
*/
|
|
139
|
+
function installOgmiosFrameGuard(onUnparseableFrame) {
|
|
140
|
+
report = onUnparseableFrame;
|
|
141
|
+
if (installed)
|
|
142
|
+
return;
|
|
143
|
+
const original = client_1.safeJSON.parse.bind(client_1.safeJSON);
|
|
144
|
+
installed = true; // only once the original is safely in hand
|
|
145
|
+
client_1.safeJSON.parse = (raw) => {
|
|
146
|
+
try {
|
|
147
|
+
return original(raw);
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
if (!(err instanceof RangeError))
|
|
151
|
+
throw err; // a genuine syntax error stays a syntax error
|
|
152
|
+
const text = String(raw);
|
|
153
|
+
const where = readBlockHeader(text);
|
|
154
|
+
try {
|
|
155
|
+
const parsed = JSON.parse(widenBigIntegers(text));
|
|
156
|
+
logger.warn(`chain-sync frame too deeply nested for the client's parser (block ${where.height ?? '?'} ` +
|
|
157
|
+
`${where.id ?? ''}, ${text.length} bytes) — parsed without it. Integers beyond 2^53 are ` +
|
|
158
|
+
`strings on this path; the chain-sync mapper stringifies them anyway.`);
|
|
159
|
+
return parsed;
|
|
160
|
+
}
|
|
161
|
+
catch (fallbackErr) {
|
|
162
|
+
const reason = fallbackErr instanceof Error ? fallbackErr.message : String(fallbackErr);
|
|
163
|
+
logger.error(`chain-sync frame unparseable (block ${where.height ?? '?'} ${where.id ?? ''}, ` +
|
|
164
|
+
`${text.length} bytes): ${reason}`);
|
|
165
|
+
report({ ...where, reason, bytes: text.length });
|
|
166
|
+
// Never throw: this runs in an async socket handler nobody awaits, so a throw
|
|
167
|
+
// becomes an unhandled rejection and ends the process.
|
|
168
|
+
return {};
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
let report = () => { };
|
|
174
|
+
/** Tests only — drop the wrapper so each case starts from the untouched client. */
|
|
175
|
+
function resetOgmiosFrameGuardForTests(originalParse) {
|
|
176
|
+
if (originalParse)
|
|
177
|
+
client_1.safeJSON.parse = originalParse;
|
|
178
|
+
installed = false;
|
|
179
|
+
report = () => { };
|
|
180
|
+
}
|
|
181
|
+
//# sourceMappingURL=ogmios-frame-guard.js.map
|
|
@@ -187,6 +187,24 @@ export declare class CardanoIndexer {
|
|
|
187
187
|
* DB. Inputs that already carry an address (Blockfrost/Koios) are skipped.
|
|
188
188
|
*/
|
|
189
189
|
private resolveInputs;
|
|
190
|
+
/**
|
|
191
|
+
* Settle the fee of phase-2-invalid transactions and the block total that follows from it.
|
|
192
|
+
*
|
|
193
|
+
* A failed script phase does not pay the fee declared in the body: the ledger consumes the
|
|
194
|
+
* collateral instead, i.e. the collateral inputs minus the collateral return. The Ogmios
|
|
195
|
+
* mapper already uses the body's `total_collateral` when it declares one; what is left are
|
|
196
|
+
* the transactions without it, and those need the collateral inputs that resolveInputs()
|
|
197
|
+
* has just filled in.
|
|
198
|
+
*
|
|
199
|
+
* A collateral input the crawler cannot resolve — spent from an output produced before the
|
|
200
|
+
* crawl start, so no row exists locally — would make the sum silently too small. The
|
|
201
|
+
* declared fee is kept in that case and the transaction is logged: a value that is wrong in
|
|
202
|
+
* a known, named way beats one that looks derived but is short by an unknown amount.
|
|
203
|
+
*
|
|
204
|
+
* Only the chain-sync path sets `spendsCollaterals`; Blockfrost and Koios transactions carry
|
|
205
|
+
* it as undefined and pass through untouched.
|
|
206
|
+
*/
|
|
207
|
+
private applyCollateralFees;
|
|
190
208
|
/**
|
|
191
209
|
* Index & return the epoch information data
|
|
192
210
|
* @param tx CAP transaction object
|
|
@@ -493,10 +493,15 @@ class CardanoIndexer {
|
|
|
493
493
|
if (epochRows.length)
|
|
494
494
|
await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
|
|
495
495
|
}
|
|
496
|
-
|
|
497
|
-
//
|
|
496
|
+
// Backfill chain-sync inputs (empty address/amount) from local outputs, then settle
|
|
497
|
+
// the fee of any phase-2 failure. Both run before the block row is written, because a
|
|
498
|
+
// corrected fee changes the block's fee total.
|
|
498
499
|
await this.resolveInputs(tx, txs);
|
|
499
|
-
|
|
500
|
+
this.applyCollateralFees(blockData, txs);
|
|
501
|
+
await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
|
|
502
|
+
// Accumulate rows across the whole block, then one bulk UPSERT per table.
|
|
503
|
+
// NUL safety (PostgreSQL rejects U+0000 in text/JSON) is enforced for every write
|
|
504
|
+
// of this plugin by the db-level hook in srv/utils/db-sanitize.ts, not per call site.
|
|
500
505
|
const txRows = txs.map(t => (0, mappers_1.mapTransaction)(t));
|
|
501
506
|
const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)(t.hash, t.inputs ?? []));
|
|
502
507
|
const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)(t.hash, t.inputs ?? []));
|
|
@@ -580,6 +585,56 @@ class CardanoIndexer {
|
|
|
580
585
|
input.amount = amt;
|
|
581
586
|
}
|
|
582
587
|
}
|
|
588
|
+
/**
|
|
589
|
+
* Settle the fee of phase-2-invalid transactions and the block total that follows from it.
|
|
590
|
+
*
|
|
591
|
+
* A failed script phase does not pay the fee declared in the body: the ledger consumes the
|
|
592
|
+
* collateral instead, i.e. the collateral inputs minus the collateral return. The Ogmios
|
|
593
|
+
* mapper already uses the body's `total_collateral` when it declares one; what is left are
|
|
594
|
+
* the transactions without it, and those need the collateral inputs that resolveInputs()
|
|
595
|
+
* has just filled in.
|
|
596
|
+
*
|
|
597
|
+
* A collateral input the crawler cannot resolve — spent from an output produced before the
|
|
598
|
+
* crawl start, so no row exists locally — would make the sum silently too small. The
|
|
599
|
+
* declared fee is kept in that case and the transaction is logged: a value that is wrong in
|
|
600
|
+
* a known, named way beats one that looks derived but is short by an unknown amount.
|
|
601
|
+
*
|
|
602
|
+
* Only the chain-sync path sets `spendsCollaterals`; Blockfrost and Koios transactions carry
|
|
603
|
+
* it as undefined and pass through untouched.
|
|
604
|
+
*/
|
|
605
|
+
applyCollateralFees(blockData, txs) {
|
|
606
|
+
const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
|
|
607
|
+
let corrected = false;
|
|
608
|
+
for (const t of txs) {
|
|
609
|
+
// totalCollateral set = the mapper already put the charged amount in `fee`
|
|
610
|
+
if (!t.spendsCollaterals || t.totalCollateral != null)
|
|
611
|
+
continue;
|
|
612
|
+
const collateral = (t.inputs ?? []).filter(i => i.isCollateral);
|
|
613
|
+
if (!collateral.length)
|
|
614
|
+
continue; // nothing to derive from — leave the declared fee
|
|
615
|
+
const unresolved = collateral.find(i => !i.address);
|
|
616
|
+
if (unresolved) {
|
|
617
|
+
logger.warn(`collateral fee for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
|
|
618
|
+
`— keeping the declared fee ${t.fee}, which understates what the ledger charged`);
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
const consumed = collateral.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n);
|
|
622
|
+
const returned = (t.outputs ?? [])
|
|
623
|
+
.filter(o => o.isCollateral)
|
|
624
|
+
.reduce((sum, o) => sum + lovelaceOf(o.amount), 0n);
|
|
625
|
+
const charged = consumed - returned;
|
|
626
|
+
if (charged < 0n) {
|
|
627
|
+
logger.warn(`collateral fee for ${t.hash}: return ${returned} exceeds collateral ${consumed} ` +
|
|
628
|
+
`— keeping the declared fee ${t.fee}`);
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
631
|
+
t.fee = charged.toString();
|
|
632
|
+
corrected = true;
|
|
633
|
+
}
|
|
634
|
+
if (corrected) {
|
|
635
|
+
blockData.fees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n).toString();
|
|
636
|
+
}
|
|
637
|
+
}
|
|
583
638
|
/**
|
|
584
639
|
* Index & return the epoch information data
|
|
585
640
|
* @param tx CAP transaction object
|
|
@@ -41,6 +41,23 @@ export declare class CardanoCrawler {
|
|
|
41
41
|
private readonly leaseOwner?;
|
|
42
42
|
/** Transient-failure retries per block before giving up. */
|
|
43
43
|
private static readonly PERSIST_RETRIES;
|
|
44
|
+
/**
|
|
45
|
+
* A block whose persist keeps failing across crawler restarts is a poison block
|
|
46
|
+
* (e.g. data PostgreSQL rejects). After this many failed persistBlock() calls for
|
|
47
|
+
* the same hash the crawler latches off (desiredRunning=false) instead of
|
|
48
|
+
* restarting forever; an operator fixes the cause and calls resumeCrawler().
|
|
49
|
+
*/
|
|
50
|
+
private static readonly POISON_BLOCK_THRESHOLD;
|
|
51
|
+
/** Process-wide, survives instance restarts: the block currently failing and how often. */
|
|
52
|
+
private static poison;
|
|
53
|
+
/**
|
|
54
|
+
* Database errors that are deterministic for the block's data — the same bytes fail
|
|
55
|
+
* the same way on every restart. Only these count towards the poison-block latch:
|
|
56
|
+
* a DB outage, a statement timeout or an exhausted pool fails the same block too,
|
|
57
|
+
* but a restart fixes those, and latching on them would disable the pre-sync for
|
|
58
|
+
* good (the contract of halt()).
|
|
59
|
+
*/
|
|
60
|
+
private static readonly DATA_REJECTION_PATTERNS;
|
|
44
61
|
/** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
|
|
45
62
|
private static readonly CALL_TIMEOUT_MS;
|
|
46
63
|
private running;
|
|
@@ -54,6 +71,14 @@ export declare class CardanoCrawler {
|
|
|
54
71
|
/** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
|
|
55
72
|
private readonly inFlightCallbacks;
|
|
56
73
|
private haltPromise;
|
|
74
|
+
/**
|
|
75
|
+
* Set when a chain-sync frame could not be parsed at all. The stream cannot deliver that
|
|
76
|
+
* block, so the ingest loop takes it through the paginating backend and then reopens
|
|
77
|
+
* chain-sync — see runIngestPipeline().
|
|
78
|
+
*/
|
|
79
|
+
private frameFailure;
|
|
80
|
+
/** Resolves the ingest loop's wait for the current chain-sync stream to end. */
|
|
81
|
+
private streamEnded;
|
|
57
82
|
private finalStatus;
|
|
58
83
|
/** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
|
|
59
84
|
private latchOnHalt;
|
|
@@ -64,6 +89,8 @@ export declare class CardanoCrawler {
|
|
|
64
89
|
/** Present for production instances created by index.ts; omitted in engine unit tests. */
|
|
65
90
|
leaseOwner?: string | undefined);
|
|
66
91
|
isRunning(): boolean;
|
|
92
|
+
/** True once the crawler halted because of a failure (not via stop() or a lost lease). */
|
|
93
|
+
haltedWithError(): boolean;
|
|
67
94
|
/**
|
|
68
95
|
* Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
|
|
69
96
|
* Refuses to start without a resume point: an explicit configured start block or an
|
|
@@ -99,6 +126,22 @@ export declare class CardanoCrawler {
|
|
|
99
126
|
/** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
|
|
100
127
|
private withTimeout;
|
|
101
128
|
private runChainSync;
|
|
129
|
+
/** Read and clear the pending frame failure, so each stream starts from a clean slate. */
|
|
130
|
+
private takeFrameFailure;
|
|
131
|
+
/**
|
|
132
|
+
* Can this unparseable frame be worked around by fetching the block over HTTP instead?
|
|
133
|
+
*
|
|
134
|
+
* Requires a height to walk to, a paginating backend to walk with, and an operator who has
|
|
135
|
+
* not pinned the source to 'ogmios' — that setting means chain-sync only, and silently
|
|
136
|
+
* degrading to the weaker pagination reorg handling would defeat the point of it.
|
|
137
|
+
*/
|
|
138
|
+
private canDegradeToPagination;
|
|
139
|
+
/**
|
|
140
|
+
* End the chain-sync stream and hand control back to the ingest loop, which continues on
|
|
141
|
+
* pagination past the offending block. Records the error first, so `lastError` names the
|
|
142
|
+
* block rather than leaving the empty status a crashed process used to leave behind.
|
|
143
|
+
*/
|
|
144
|
+
private degradeToPagination;
|
|
102
145
|
/**
|
|
103
146
|
* Candidate intersection points, NEWEST FIRST: the cursor, then an exponentially
|
|
104
147
|
* spaced ladder of our own already-crawled ancestors, then the configured start
|
|
@@ -114,6 +157,12 @@ export declare class CardanoCrawler {
|
|
|
114
157
|
private buildIntersectionPoints;
|
|
115
158
|
/** Track streamed callbacks because closing a socket does not imply DB callbacks finished. */
|
|
116
159
|
private trackCallback;
|
|
160
|
+
/**
|
|
161
|
+
* @param untilHeight when set, return as soon as the cursor has reached it instead of
|
|
162
|
+
* looping forever. Used to walk past a block the chain-sync stream cannot deliver and
|
|
163
|
+
* then hand back to it — pagination is roughly seven times slower, so staying on it
|
|
164
|
+
* for the rest of a backfill would be a poor trade.
|
|
165
|
+
*/
|
|
117
166
|
private runPagination;
|
|
118
167
|
/**
|
|
119
168
|
* Pagination reorg recovery: walk back by height comparing the on-chain block hash with
|
|
@@ -142,6 +191,12 @@ export declare class CardanoCrawler {
|
|
|
142
191
|
private handleReorg;
|
|
143
192
|
/** Renew the lease while an Ogmios stream is idle; block writes renew it transactionally. */
|
|
144
193
|
private startLeaseHeartbeat;
|
|
194
|
+
/** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
|
|
195
|
+
static isDataRejection(err: unknown): boolean;
|
|
196
|
+
/** Count final persist failures per block hash (a different hash resets the count). */
|
|
197
|
+
private static notePersistFailure;
|
|
198
|
+
/** Test seam: forget the poison-block memory (process-wide state). */
|
|
199
|
+
static resetPoisonMemory(): void;
|
|
145
200
|
/** Record state only while this instance still owns the lease. */
|
|
146
201
|
private recordCrawlerError;
|
|
147
202
|
private leaseSleep;
|
|
@@ -42,6 +42,33 @@ class CardanoCrawler {
|
|
|
42
42
|
leaseOwner;
|
|
43
43
|
/** Transient-failure retries per block before giving up. */
|
|
44
44
|
static PERSIST_RETRIES = 3;
|
|
45
|
+
/**
|
|
46
|
+
* A block whose persist keeps failing across crawler restarts is a poison block
|
|
47
|
+
* (e.g. data PostgreSQL rejects). After this many failed persistBlock() calls for
|
|
48
|
+
* the same hash the crawler latches off (desiredRunning=false) instead of
|
|
49
|
+
* restarting forever; an operator fixes the cause and calls resumeCrawler().
|
|
50
|
+
*/
|
|
51
|
+
static POISON_BLOCK_THRESHOLD = 5;
|
|
52
|
+
/** Process-wide, survives instance restarts: the block currently failing and how often. */
|
|
53
|
+
static poison = null;
|
|
54
|
+
/**
|
|
55
|
+
* Database errors that are deterministic for the block's data — the same bytes fail
|
|
56
|
+
* the same way on every restart. Only these count towards the poison-block latch:
|
|
57
|
+
* a DB outage, a statement timeout or an exhausted pool fails the same block too,
|
|
58
|
+
* but a restart fixes those, and latching on them would disable the pre-sync for
|
|
59
|
+
* good (the contract of halt()).
|
|
60
|
+
*/
|
|
61
|
+
static DATA_REJECTION_PATTERNS = [
|
|
62
|
+
/unsupported unicode escape sequence/i, // PostgreSQL: U+0000 inside a JSON document
|
|
63
|
+
/invalid byte sequence for encoding/i, // PostgreSQL: bytes that are not valid UTF-8
|
|
64
|
+
/out of range for type/i, // PostgreSQL: bigint / integer overflow
|
|
65
|
+
/invalid input syntax for type/i, // PostgreSQL: NaN or text in a numeric column
|
|
66
|
+
/value too long for type/i, // PostgreSQL: varchar(n) exceeded
|
|
67
|
+
/numeric value out of range/i, // HANA / SQL-92
|
|
68
|
+
/inserted value too large for column/i, // HANA
|
|
69
|
+
/string or blob too big/i, // SQLite
|
|
70
|
+
/datatype mismatch/i, // SQLite
|
|
71
|
+
];
|
|
45
72
|
/** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
|
|
46
73
|
static CALL_TIMEOUT_MS = 60_000;
|
|
47
74
|
running = false;
|
|
@@ -55,6 +82,14 @@ class CardanoCrawler {
|
|
|
55
82
|
/** Chain-sync callback promises outlive openChainSync(); stop() explicitly drains them. */
|
|
56
83
|
inFlightCallbacks = new Set();
|
|
57
84
|
haltPromise = null;
|
|
85
|
+
/**
|
|
86
|
+
* Set when a chain-sync frame could not be parsed at all. The stream cannot deliver that
|
|
87
|
+
* block, so the ingest loop takes it through the paginating backend and then reopens
|
|
88
|
+
* chain-sync — see runIngestPipeline().
|
|
89
|
+
*/
|
|
90
|
+
frameFailure = null;
|
|
91
|
+
/** Resolves the ingest loop's wait for the current chain-sync stream to end. */
|
|
92
|
+
streamEnded = null;
|
|
58
93
|
finalStatus = 'stopped';
|
|
59
94
|
/** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
|
|
60
95
|
latchOnHalt = false;
|
|
@@ -73,6 +108,10 @@ class CardanoCrawler {
|
|
|
73
108
|
isRunning() {
|
|
74
109
|
return this.running;
|
|
75
110
|
}
|
|
111
|
+
/** True once the crawler halted because of a failure (not via stop() or a lost lease). */
|
|
112
|
+
haltedWithError() {
|
|
113
|
+
return !this.running && this.finalStatus === 'error';
|
|
114
|
+
}
|
|
76
115
|
/**
|
|
77
116
|
* Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
|
|
78
117
|
* Refuses to start without a resume point: an explicit configured start block or an
|
|
@@ -154,6 +193,7 @@ class CardanoCrawler {
|
|
|
154
193
|
this.finalStatus = finalStatus;
|
|
155
194
|
this.running = false;
|
|
156
195
|
this.wake?.(); // cancel a pending poll sleep so the loop exits now
|
|
196
|
+
this.streamEnded?.(); // release the ingest loop — beginHalt awaits the pipeline below
|
|
157
197
|
this.leaseWake?.();
|
|
158
198
|
for (const cancel of [...this.callCancels])
|
|
159
199
|
cancel();
|
|
@@ -195,7 +235,22 @@ class CardanoCrawler {
|
|
|
195
235
|
async runIngestPipeline() {
|
|
196
236
|
const chainSync = this.config.source !== 'pagination' ? this.client.getChainSyncBackend() : null;
|
|
197
237
|
if (chainSync) {
|
|
198
|
-
|
|
238
|
+
// One pass per chain-sync stream. A frame the client's parser cannot turn into an
|
|
239
|
+
// object ends the stream without ending the crawler: pagination fetches that one
|
|
240
|
+
// block over HTTP, and chain-sync takes over again as soon as it is behind the
|
|
241
|
+
// cursor. Any other stream error still halts, as it always did.
|
|
242
|
+
while (this.running) {
|
|
243
|
+
const streamEnd = new Promise((resolve) => { this.streamEnded = resolve; });
|
|
244
|
+
await this.runChainSync(chainSync);
|
|
245
|
+
if (!this.chainSyncHandle)
|
|
246
|
+
return; // open refused, halted, or stop() raced us
|
|
247
|
+
await streamEnd;
|
|
248
|
+
const failure = this.takeFrameFailure();
|
|
249
|
+
if (!this.running || failure?.height == null)
|
|
250
|
+
return;
|
|
251
|
+
logger.warn(`chain-sync cannot deliver block ${failure.height} — switching to pagination until it is behind the cursor`);
|
|
252
|
+
await this.runPagination(failure.height + 1);
|
|
253
|
+
}
|
|
199
254
|
return;
|
|
200
255
|
}
|
|
201
256
|
if (this.config.source === 'ogmios') {
|
|
@@ -262,6 +317,12 @@ class CardanoCrawler {
|
|
|
262
317
|
onError: (err) => this.trackCallback(async () => {
|
|
263
318
|
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError)
|
|
264
319
|
return;
|
|
320
|
+
// A frame the client's parser cannot handle is a fault of that one block, not of the
|
|
321
|
+
// crawler or the node — pagination can still fetch it, so degrade instead of halting.
|
|
322
|
+
if (err instanceof errors_1.ChainSyncFrameError && this.canDegradeToPagination(err)) {
|
|
323
|
+
await this.degradeToPagination(err);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
265
326
|
// The stream is stalled (mapping/callback failure) — record and halt cleanly
|
|
266
327
|
// so the cursor status shows 'error' instead of a healthy-looking hang.
|
|
267
328
|
const streak = await this.recordCrawlerError(err);
|
|
@@ -280,6 +341,49 @@ class CardanoCrawler {
|
|
|
280
341
|
this.chainSyncHandle = handle;
|
|
281
342
|
logger.info(`Crawler running (chain-sync) from ${points[0].hash} (+${points.length - 1} fallback intersection point(s))`);
|
|
282
343
|
}
|
|
344
|
+
/** Read and clear the pending frame failure, so each stream starts from a clean slate. */
|
|
345
|
+
takeFrameFailure() {
|
|
346
|
+
const failure = this.frameFailure;
|
|
347
|
+
this.frameFailure = null;
|
|
348
|
+
return failure;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Can this unparseable frame be worked around by fetching the block over HTTP instead?
|
|
352
|
+
*
|
|
353
|
+
* Requires a height to walk to, a paginating backend to walk with, and an operator who has
|
|
354
|
+
* not pinned the source to 'ogmios' — that setting means chain-sync only, and silently
|
|
355
|
+
* degrading to the weaker pagination reorg handling would defeat the point of it.
|
|
356
|
+
*/
|
|
357
|
+
canDegradeToPagination(err) {
|
|
358
|
+
return err.height != null
|
|
359
|
+
&& this.config.source !== 'ogmios'
|
|
360
|
+
&& !!this.client.getPaginatingBackend();
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* End the chain-sync stream and hand control back to the ingest loop, which continues on
|
|
364
|
+
* pagination past the offending block. Records the error first, so `lastError` names the
|
|
365
|
+
* block rather than leaving the empty status a crashed process used to leave behind.
|
|
366
|
+
*/
|
|
367
|
+
async degradeToPagination(err) {
|
|
368
|
+
const streak = await this.recordCrawlerError(err);
|
|
369
|
+
if (streak < 0) {
|
|
370
|
+
await this.halt('stopped');
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
logger.error('Chain-sync frame unusable — continuing on pagination:', err.message);
|
|
374
|
+
this.frameFailure = err;
|
|
375
|
+
const handle = this.chainSyncHandle;
|
|
376
|
+
this.chainSyncHandle = null;
|
|
377
|
+
if (handle) {
|
|
378
|
+
try {
|
|
379
|
+
await handle.close();
|
|
380
|
+
}
|
|
381
|
+
catch (e) {
|
|
382
|
+
logger.warn('chain-sync close failed:', e);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
this.streamEnded?.();
|
|
386
|
+
}
|
|
283
387
|
/**
|
|
284
388
|
* Candidate intersection points, NEWEST FIRST: the cursor, then an exponentially
|
|
285
389
|
* spaced ladder of our own already-crawled ancestors, then the configured start
|
|
@@ -339,7 +443,13 @@ class CardanoCrawler {
|
|
|
339
443
|
// ---------------------------------------------------------------------------
|
|
340
444
|
// Pagination (Blockfrost/Koios) — fallback
|
|
341
445
|
// ---------------------------------------------------------------------------
|
|
342
|
-
|
|
446
|
+
/**
|
|
447
|
+
* @param untilHeight when set, return as soon as the cursor has reached it instead of
|
|
448
|
+
* looping forever. Used to walk past a block the chain-sync stream cannot deliver and
|
|
449
|
+
* then hand back to it — pagination is roughly seven times slower, so staying on it
|
|
450
|
+
* for the rest of a backfill would be a poor trade.
|
|
451
|
+
*/
|
|
452
|
+
async runPagination(untilHeight) {
|
|
343
453
|
const backend = this.client.getPaginatingBackend();
|
|
344
454
|
if (!backend) {
|
|
345
455
|
logger.error('No paginating backend available — cannot crawl without Ogmios or Blockfrost/Koios');
|
|
@@ -360,6 +470,10 @@ class CardanoCrawler {
|
|
|
360
470
|
await this.halt('error', true); // broken precondition: a restart cannot fix it
|
|
361
471
|
return;
|
|
362
472
|
}
|
|
473
|
+
if (untilHeight != null && cursor.lastHeight >= untilHeight) {
|
|
474
|
+
logger.info(`pagination reached block ${cursor.lastHeight} — handing back to chain-sync`);
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
363
477
|
if (!tip || cursor.lastHeight >= target) {
|
|
364
478
|
tip = await this.withTimeout(this.client.getLatestBlock(), 'getLatestBlock');
|
|
365
479
|
target = (tip.height ?? 0) - this.config.confirmationDepth;
|
|
@@ -506,6 +620,8 @@ class CardanoCrawler {
|
|
|
506
620
|
await this.indexer.indexBlockFull(tx, block, txs);
|
|
507
621
|
await (0, sync_state_1.advanceCursor)(tx, { slot: block.slot ?? 0, hash: block.hash, height: block.height ?? 0 }, tip ? { slot: tip.slot, height: tip.height } : undefined, isAtTip ? 'synced' : 'syncing');
|
|
508
622
|
});
|
|
623
|
+
if (CardanoCrawler.poison?.hash === block.hash)
|
|
624
|
+
CardanoCrawler.poison = null;
|
|
509
625
|
// Notify observers (wallet-worker confirmation tracker) AFTER the commit —
|
|
510
626
|
// listener failures are swallowed inside emitBlockIndexed.
|
|
511
627
|
(0, hooks_1.emitBlockIndexed)({
|
|
@@ -534,7 +650,23 @@ class CardanoCrawler {
|
|
|
534
650
|
await this.sleep(1000 * attempt);
|
|
535
651
|
continue;
|
|
536
652
|
}
|
|
537
|
-
|
|
653
|
+
const dataRejection = CardanoCrawler.isDataRejection(err);
|
|
654
|
+
const failures = dataRejection ? CardanoCrawler.notePersistFailure(block.hash) : 0;
|
|
655
|
+
if (failures >= CardanoCrawler.POISON_BLOCK_THRESHOLD) {
|
|
656
|
+
const cause = err instanceof Error ? err.message : String(err);
|
|
657
|
+
const message = `poison block ${block.hash} @${block.height ?? '?'} failed ${failures}x: ${cause}`;
|
|
658
|
+
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);
|
|
659
|
+
// Lease-independent on purpose (see latchPoisonBlock). The memory is only
|
|
660
|
+
// forgotten once the latch is durable, so a failed write is retried after
|
|
661
|
+
// the next restart instead of restarting the count from one.
|
|
662
|
+
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; });
|
|
663
|
+
if (latched)
|
|
664
|
+
CardanoCrawler.poison = null;
|
|
665
|
+
await this.halt('error', true);
|
|
666
|
+
return false;
|
|
667
|
+
}
|
|
668
|
+
const perBlock = dataRejection ? ` (${failures}/${CardanoCrawler.POISON_BLOCK_THRESHOLD} for this block)` : '';
|
|
669
|
+
logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts${perBlock} — stopping crawler (resume re-syncs from cursor):`, err);
|
|
538
670
|
await this.halt('error');
|
|
539
671
|
return false;
|
|
540
672
|
}
|
|
@@ -650,6 +782,24 @@ class CardanoCrawler {
|
|
|
650
782
|
}
|
|
651
783
|
})();
|
|
652
784
|
}
|
|
785
|
+
/** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
|
|
786
|
+
static isDataRejection(err) {
|
|
787
|
+
// RangeError: BigInt / number conversions in the mappers; SyntaxError: JSON of the block
|
|
788
|
+
if (err instanceof RangeError || err instanceof SyntaxError)
|
|
789
|
+
return true;
|
|
790
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
791
|
+
return CardanoCrawler.DATA_REJECTION_PATTERNS.some((p) => p.test(message));
|
|
792
|
+
}
|
|
793
|
+
/** Count final persist failures per block hash (a different hash resets the count). */
|
|
794
|
+
static notePersistFailure(hash) {
|
|
795
|
+
const p = CardanoCrawler.poison;
|
|
796
|
+
CardanoCrawler.poison = p && p.hash === hash ? { hash, failures: p.failures + 1 } : { hash, failures: 1 };
|
|
797
|
+
return CardanoCrawler.poison.failures;
|
|
798
|
+
}
|
|
799
|
+
/** Test seam: forget the poison-block memory (process-wide state). */
|
|
800
|
+
static resetPoisonMemory() {
|
|
801
|
+
CardanoCrawler.poison = null;
|
|
802
|
+
}
|
|
653
803
|
/** Record state only while this instance still owns the lease. */
|
|
654
804
|
async recordCrawlerError(err) {
|
|
655
805
|
if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
|
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import type { CardanoClient } from '../cardano-client';
|
|
2
2
|
import type { CardanoIndexer } from '../cardano-indexer';
|
|
3
3
|
import { CardanoCrawler, type CrawlerConfig } from './crawler';
|
|
4
|
+
/**
|
|
5
|
+
* Delay before the next standby start attempt. A healthy standby (a lease loser, or
|
|
6
|
+
* the leader's own no-op tick) retries every 5 s. Only after the crawler in THIS
|
|
7
|
+
* process halted with an error does the shared cursor's consecutiveErrors drive an
|
|
8
|
+
* exponential backoff (5 s, 10 s, 20 s ... capped at 5 min), so a block the crawler
|
|
9
|
+
* cannot persist no longer re-syncs the chain-sync stream every 5 s. A standby that
|
|
10
|
+
* never held the lease is not slowed down by the leader's streak: failover stays 5 s.
|
|
11
|
+
*/
|
|
12
|
+
export declare function standbyDelayMs(consecutiveErrors: number): number;
|
|
4
13
|
export interface StartCrawlerDeps {
|
|
5
14
|
client: CardanoClient;
|
|
6
15
|
indexer: CardanoIndexer;
|