@odatano/core 2.0.0-rc.50 → 2.0.0-rc.52
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/CardanoBackendService/index.d.ts +14 -3
- package/@cds-models/CardanoBackendService/index.js +1 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
- package/@cds-models/CardanoIndexerService/index.js +10 -0
- package/@cds-models/CardanoODataService/index.d.ts +3 -0
- package/@cds-models/CardanoSignService/index.d.ts +13 -0
- package/@cds-models/CardanoSignService/index.js +1 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
- package/@cds-models/CardanoTransactionService/index.js +1 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
- package/@cds-models/CardanoWorkerService/index.js +2 -0
- package/@cds-models/index.d.ts +13 -3
- package/@cds-models/index.js +4 -3
- package/@cds-models/odatano/cardano/index.d.ts +14 -0
- package/README.md +45 -149
- package/db/schema.cds +63 -10
- package/db/types.cds +10 -0
- package/package.json +7 -44
- package/scripts/deploy-schema.mjs +113 -0
- package/scripts/migrate-schema.mjs +209 -15
- package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
- package/srv/blockchain/backends/blockfrost-backend.js +61 -45
- package/srv/blockchain/backends/call-signal.d.ts +7 -0
- package/srv/blockchain/backends/call-signal.js +22 -0
- package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
- package/srv/blockchain/backends/koios-backend.d.ts +9 -6
- package/srv/blockchain/backends/koios-backend.js +145 -207
- package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
- package/srv/blockchain/backends/odatano-backend.js +51 -9
- package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
- package/srv/blockchain/backends/ogmios-backend.js +82 -48
- package/srv/blockchain/cardano-client.d.ts +15 -5
- package/srv/blockchain/cardano-client.js +143 -71
- package/srv/blockchain/cardano-indexer.d.ts +27 -16
- package/srv/blockchain/cardano-indexer.js +223 -102
- package/srv/blockchain/circuit-breaker.d.ts +1 -0
- package/srv/blockchain/circuit-breaker.js +6 -0
- package/srv/blockchain/crawler/account-snapshots.js +22 -2
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
- package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
- package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
- package/srv/blockchain/crawler/certificate-backfill.js +15 -3
- package/srv/blockchain/crawler/crawler.d.ts +22 -1
- package/srv/blockchain/crawler/crawler.js +223 -24
- package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/credential-backfill.js +43 -66
- package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
- package/srv/blockchain/crawler/input-asset-copies.js +17 -27
- package/srv/blockchain/crawler/key-pages.d.ts +12 -0
- package/srv/blockchain/crawler/key-pages.js +48 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
- package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
- package/srv/blockchain/crawler/sync-state.d.ts +5 -1
- package/srv/blockchain/crawler/sync-state.js +63 -106
- package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/transaction-backfill.js +6 -13
- package/srv/blockchain/crawler/utxo-set-import.js +2 -2
- package/srv/blockchain/crawler/window-plan.d.ts +31 -0
- package/srv/blockchain/crawler/window-plan.js +59 -0
- package/srv/blockchain/ledger-state.d.ts +2 -2
- package/srv/blockchain/ledger-state.js +139 -37
- package/srv/blockchain/signing/external-signer.js +5 -5
- package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
- package/srv/blockchain/signing/failed-recheck.js +135 -0
- package/srv/blockchain/signing/landing-proof.d.ts +60 -0
- package/srv/blockchain/signing/landing-proof.js +224 -0
- package/srv/blockchain/signing/signature-verifier.js +10 -13
- package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
- package/srv/blockchain/signing/submission-finalizer.js +90 -29
- package/srv/blockchain/stored-chain.d.ts +1 -2
- package/srv/blockchain/stored-chain.js +36 -15
- package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
- package/srv/blockchain/transaction-presence.d.ts +8 -1
- package/srv/blockchain/transaction-presence.js +12 -12
- package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
- package/srv/blockchain/wallet-worker/build-request.js +35 -365
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
- package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
- package/srv/blockchain/wallet-worker/invalidation.js +128 -0
- package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
- package/srv/blockchain/wallet-worker/job-store.js +107 -80
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
- package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
- package/srv/cardano-agent-service.cds +1 -1
- package/srv/cardano-agent-service.js +8 -0
- package/srv/cardano-backend-service.cds +4 -1
- package/srv/cardano-backend-service.js +26 -9
- package/srv/cardano-indexer-service.cds +448 -387
- package/srv/cardano-indexer-service.js +226 -281
- package/srv/cardano-service.cds +7 -5
- package/srv/cardano-service.js +404 -69
- package/srv/cardano-sign-service.cds +11 -1
- package/srv/cardano-sign-service.js +161 -108
- package/srv/cardano-tx-service.cds +23 -12
- package/srv/cardano-tx-service.js +105 -604
- package/srv/cardano-worker-service.cds +25 -2
- package/srv/cardano-worker-service.js +56 -4
- package/srv/config.d.ts +4 -0
- package/srv/config.js +10 -0
- package/srv/server.js +5 -7
- package/srv/utils/agent-access.d.ts +4 -2
- package/srv/utils/agent-access.js +26 -7
- package/srv/utils/agent-grants.d.ts +1 -1
- package/srv/utils/agent-grants.js +7 -8
- package/srv/utils/agent-token-auth.js +45 -5
- package/srv/utils/build-request.d.ts +52 -0
- package/srv/utils/build-request.js +487 -0
- package/srv/utils/collections.d.ts +1 -0
- package/srv/utils/collections.js +11 -0
- package/srv/utils/const.d.ts +10 -2
- package/srv/utils/const.js +13 -6
- package/srv/utils/crypto.js +5 -4
- package/srv/utils/db-indexes.d.ts +5 -1
- package/srv/utils/db-indexes.js +79 -14
- package/srv/utils/db-kind.d.ts +23 -0
- package/srv/utils/db-kind.js +42 -0
- package/srv/utils/detached-run.d.ts +41 -0
- package/srv/utils/detached-run.js +101 -0
- package/srv/utils/epoch-slots.d.ts +1 -0
- package/srv/utils/epoch-slots.js +7 -0
- package/srv/utils/error-codes.d.ts +4 -0
- package/srv/utils/error-codes.js +4 -0
- package/srv/utils/errors.d.ts +10 -1
- package/srv/utils/errors.js +51 -9
- package/srv/utils/lease.d.ts +20 -0
- package/srv/utils/lease.js +62 -0
- package/srv/utils/mappers.d.ts +9 -0
- package/srv/utils/mappers.js +57 -67
- package/srv/utils/navigation.d.ts +17 -0
- package/srv/utils/navigation.js +52 -0
- package/srv/utils/network-context.d.ts +0 -1
- package/srv/utils/network-context.js +8 -3
- package/srv/utils/pg-inline-json.js +3 -3
- package/srv/utils/pg-order-nulls.js +3 -3
- package/srv/utils/resolution.d.ts +13 -0
- package/srv/utils/resolution.js +47 -0
- package/srv/utils/row-values.d.ts +7 -0
- package/srv/utils/row-values.js +27 -0
- package/srv/utils/tx-build-helper.d.ts +15 -0
- package/srv/utils/tx-build-helper.js +28 -13
- package/srv/utils/types.d.ts +36 -44
- package/srv/utils/types.js +1 -17
- package/srv/utils/validators.d.ts +2 -2
- package/srv/utils/validators.js +14 -25
|
@@ -13,9 +13,9 @@ exports.bothStatement = bothStatement;
|
|
|
13
13
|
exports.pruneInputAssetCopies = pruneInputAssetCopies;
|
|
14
14
|
exports.restoreInputAssetCopies = restoreInputAssetCopies;
|
|
15
15
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
16
|
-
const mappers_1 = require("../../utils/mappers");
|
|
17
16
|
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
18
|
-
const
|
|
17
|
+
const window_plan_1 = require("./window-plan");
|
|
18
|
+
const db_kind_1 = require("../../utils/db-kind");
|
|
19
19
|
const logger = cds_1.default.log('InputAssetCopies');
|
|
20
20
|
// An input reads its assets from a stored copy or, through `spentTxSeq`, from the output it spent.
|
|
21
21
|
// It has one of the two, never both. The prune moves the inputs of a slot range from copies to the
|
|
@@ -27,8 +27,9 @@ const OUTPUTS = 'odatano_cardano_TransactionOutputs';
|
|
|
27
27
|
const OUTPUT_ASSETS = 'odatano_cardano_TransactionOutputAssets';
|
|
28
28
|
/** Columns of an asset row besides its key, the same in the copies and in the output assets. */
|
|
29
29
|
exports.ASSET_COLUMNS = ['asset_quantity', 'asset_policyId', 'asset_assetNameHex', 'asset_assetName', 'asset_fingerprint'];
|
|
30
|
-
const supported = (kind) =>
|
|
31
|
-
|
|
30
|
+
const supported = (kind) => (0, db_kind_1.bulkSqlKind)(kind) !== null;
|
|
31
|
+
/** The two window bounds as numbered parameters, so a statement can name each more than once. */
|
|
32
|
+
const bounds = (kind) => (kind === 'postgres' ? ['$1', '$2'] : ['?1', '?2']);
|
|
32
33
|
// Points the inputs of a window at their output. Only where the output is stored and holds
|
|
33
34
|
// exactly the asset rows of the input's copy, so the input reads the same assets afterwards.
|
|
34
35
|
function referenceStatement(kind) {
|
|
@@ -44,14 +45,15 @@ function referenceStatement(kind) {
|
|
|
44
45
|
`SELECT 1 FROM ${OUTPUT_ASSETS} AS a WHERE ${spent} AND a.unit = c.unit AND a.asset_quantity = c.asset_quantity)) ` +
|
|
45
46
|
`AND (SELECT count(*) FROM ${COPIES} AS c WHERE ${copy}) = (SELECT count(*) FROM ${OUTPUT_ASSETS} AS a WHERE ${spent})`;
|
|
46
47
|
}
|
|
47
|
-
|
|
48
|
+
// Deletes the copies of the inputs of a window that have a reference. The inputs carry the window
|
|
49
|
+
// bounds too: without them the database may read every input to find those with a reference.
|
|
48
50
|
function deleteCopiesStatement(kind) {
|
|
49
51
|
if (!supported(kind))
|
|
50
52
|
return null;
|
|
51
53
|
const [lo, hi] = bounds(kind);
|
|
52
54
|
return `DELETE FROM ${COPIES} WHERE input_txSeq >= ${lo} AND input_txSeq < ${hi} AND EXISTS (` +
|
|
53
55
|
`SELECT 1 FROM ${INPUTS} AS i WHERE i.txSeq = ${COPIES}.input_txSeq AND i.inputIndex = ${COPIES}.input_inputIndex ` +
|
|
54
|
-
`AND i.spentTxSeq IS NOT NULL)`;
|
|
56
|
+
`AND i.spentTxSeq IS NOT NULL AND i.txSeq >= ${lo} AND i.txSeq < ${hi})`;
|
|
55
57
|
}
|
|
56
58
|
/** Counts the inputs of a window that have no reference. */
|
|
57
59
|
function keptStatement(kind) {
|
|
@@ -93,40 +95,28 @@ async function assertOneSource(tx, check, window) {
|
|
|
93
95
|
if (both > 0)
|
|
94
96
|
throw new Error(`${both} inputs between txSeq ${window[0]} and ${window[1]} would have copies and a reference; the window is left unchanged`);
|
|
95
97
|
}
|
|
96
|
-
const dbKind = () => cds_1.default.db?.kind ?? '';
|
|
97
98
|
/** Rows a plain statement changed; the drivers answer with their own result object. */
|
|
98
99
|
function changed(result) {
|
|
99
100
|
const r = result;
|
|
100
101
|
return typeof r === 'number' ? r : Number(r?.changes ?? r?.rowCount) || 0;
|
|
101
102
|
}
|
|
102
103
|
function statementFor(build) {
|
|
103
|
-
const sql = build(
|
|
104
|
+
const sql = build((0, db_kind_1.connectedDbKind)());
|
|
104
105
|
if (!sql)
|
|
105
|
-
throw new Error(`Input asset copies are pruned and restored on PostgreSQL and SQLite only (database kind: ${
|
|
106
|
+
throw new Error(`Input asset copies are pruned and restored on PostgreSQL and SQLite only (database kind: ${(0, db_kind_1.connectedDbKind)() || 'none'})`);
|
|
106
107
|
return sql;
|
|
107
108
|
}
|
|
108
|
-
/**
|
|
109
|
-
async function slotRange(opts) {
|
|
110
|
-
const stored = (await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.TransactionInputs).columns('min(txSeq) as lo', 'max(txSeq) as hi'))));
|
|
111
|
-
if (stored?.lo == null || stored.hi == null)
|
|
112
|
-
return null;
|
|
113
|
-
const from = Math.max(opts.fromSlot, Math.floor(Number(stored.lo) / mappers_1.TX_SEQ_SLOT_FACTOR));
|
|
114
|
-
const to = Math.min(opts.toSlot, Math.floor(Number(stored.hi) / mappers_1.TX_SEQ_SLOT_FACTOR));
|
|
115
|
-
return from <= to ? { from, to } : null;
|
|
116
|
-
}
|
|
117
|
-
/** Calls `step` with the txSeq bounds of each slot window, each in a transaction of its own. */
|
|
109
|
+
/** Walks the windows of the asked slots that hold stored inputs. Null when there is none. */
|
|
118
110
|
async function walk(opts, progress, step) {
|
|
119
|
-
const
|
|
120
|
-
const range = await slotRange(opts);
|
|
111
|
+
const range = await (0, window_plan_1.slotRangeOf)(cardano_1.TransactionInputs, opts);
|
|
121
112
|
if (!range)
|
|
122
113
|
return null;
|
|
123
114
|
progress.toSlot = range.to;
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
progress.atSlot =
|
|
128
|
-
|
|
129
|
-
}
|
|
115
|
+
await (0, window_plan_1.walkSlotWindows)(range, {
|
|
116
|
+
slotWindow: opts.slotWindow,
|
|
117
|
+
shouldStop: opts.shouldStop,
|
|
118
|
+
afterWindow: (atSlot) => { progress.atSlot = atSlot; opts.onProgress?.({ ...progress }); },
|
|
119
|
+
}, step);
|
|
130
120
|
return range;
|
|
131
121
|
}
|
|
132
122
|
// Moves the inputs of the slot range from copies to the reference. Per window, in one transaction:
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface KeyPageSpec {
|
|
2
|
+
entity: unknown;
|
|
3
|
+
/** Primary key in walk order. */
|
|
4
|
+
keys: [first: string, second: string];
|
|
5
|
+
/** Columns to read; the keys are added. */
|
|
6
|
+
columns: string[];
|
|
7
|
+
chunkSize: number;
|
|
8
|
+
/** Stops the walk before the next page. */
|
|
9
|
+
shouldStop?: () => boolean;
|
|
10
|
+
}
|
|
11
|
+
export declare function pageByKey<R extends Record<string, unknown>>(spec: KeyPageSpec, onPage: (rows: R[]) => Promise<void>): Promise<boolean>;
|
|
12
|
+
//# sourceMappingURL=key-pages.d.ts.map
|
|
@@ -0,0 +1,48 @@
|
|
|
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.pageByKey = pageByKey;
|
|
7
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
8
|
+
const window_plan_1 = require("./window-plan");
|
|
9
|
+
const { SELECT } = cds_1.default.ql;
|
|
10
|
+
// Calls `onPage` with each page, outside the read transaction, so it may call a backend.
|
|
11
|
+
// Returns false when `shouldStop` ended the walk.
|
|
12
|
+
async function pageByKey(spec, onPage) {
|
|
13
|
+
const [k1, k2] = spec.keys;
|
|
14
|
+
const columns = [...new Set([k1, k2, ...spec.columns])];
|
|
15
|
+
let at = null;
|
|
16
|
+
for (;;) {
|
|
17
|
+
await (0, window_plan_1.yieldToEventLoop)();
|
|
18
|
+
if (spec.shouldStop?.())
|
|
19
|
+
return false;
|
|
20
|
+
const where = {};
|
|
21
|
+
if (at?.within) {
|
|
22
|
+
where[k1] = at.first;
|
|
23
|
+
where[k2] = { '>': at.second };
|
|
24
|
+
}
|
|
25
|
+
else if (at) {
|
|
26
|
+
where[k1] = { '>': at.first };
|
|
27
|
+
}
|
|
28
|
+
const rows = (await cds_1.default.tx((tx) => tx.run(SELECT.from(spec.entity).columns(...columns).where(where).orderBy(k1, k2).limit(spec.chunkSize)))) ?? [];
|
|
29
|
+
const wasWithin = at?.within ?? false;
|
|
30
|
+
if (!rows.length) {
|
|
31
|
+
if (!wasWithin)
|
|
32
|
+
return true;
|
|
33
|
+
at = { ...at, within: false };
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
const full = rows.length === spec.chunkSize;
|
|
37
|
+
const lastFirst = rows[rows.length - 1][k1];
|
|
38
|
+
const allSame = rows.every((r) => r[k1] === lastFirst);
|
|
39
|
+
// the last first key of a full page may go on, so its rows wait for the next page
|
|
40
|
+
const page = full && !allSame ? rows.filter((r) => r[k1] !== lastFirst) : rows;
|
|
41
|
+
await onPage(page);
|
|
42
|
+
const last = page[page.length - 1];
|
|
43
|
+
at = { first: last[k1], second: last[k2], within: full && allSame };
|
|
44
|
+
if (!full && !wasWithin)
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=key-pages.js.map
|
|
@@ -7,9 +7,15 @@ export interface MetadataPositionProgress {
|
|
|
7
7
|
rows: number;
|
|
8
8
|
}
|
|
9
9
|
export interface MetadataPositionOptions {
|
|
10
|
+
/** First slot to walk; default the first stored transaction. */
|
|
11
|
+
fromSlot?: number | null;
|
|
12
|
+
/** Last slot to walk; default the last stored transaction. */
|
|
13
|
+
toSlot?: number | null;
|
|
10
14
|
/** Slots per statement. */
|
|
11
15
|
slotWindow?: number;
|
|
12
16
|
onProgress?: (p: MetadataPositionProgress) => void;
|
|
17
|
+
/** Stops the walk before the next window. */
|
|
18
|
+
shouldStop?: () => boolean;
|
|
13
19
|
}
|
|
14
20
|
export declare function metadataPositionStatement(kind: string): string | null;
|
|
15
21
|
export declare function backfillMetadataPositions(opts?: MetadataPositionOptions): Promise<MetadataPositionProgress>;
|
|
@@ -6,23 +6,26 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.metadataPositionStatement = metadataPositionStatement;
|
|
7
7
|
exports.backfillMetadataPositions = backfillMetadataPositions;
|
|
8
8
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
9
|
-
const mappers_1 = require("../../utils/mappers");
|
|
10
9
|
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
10
|
+
const window_plan_1 = require("./window-plan");
|
|
11
|
+
const db_kind_1 = require("../../utils/db-kind");
|
|
11
12
|
const { SELECT, UPDATE } = cds_1.default.ql;
|
|
12
13
|
const logger = cds_1.default.log('MetadataPositionBackfill');
|
|
13
14
|
const METADATA_TABLE = 'odatano_cardano_TransactionMetadata';
|
|
14
15
|
const TRANSACTIONS_TABLE = 'odatano_cardano_Transactions';
|
|
15
16
|
// One UPDATE per window that takes the position from the transaction row. Null for databases
|
|
16
|
-
// other than Postgres and SQLite, which update transaction by transaction.
|
|
17
|
+
// other than Postgres and SQLite, which update transaction by transaction. The only way into the
|
|
18
|
+
// metadata table is the join on tx_hash: a filter on txSeq would let the planner scan for it.
|
|
17
19
|
function metadataPositionStatement(kind) {
|
|
18
|
-
|
|
20
|
+
const bulk = (0, db_kind_1.bulkSqlKind)(kind);
|
|
21
|
+
if (!bulk)
|
|
19
22
|
return null;
|
|
20
|
-
const [lo, hi] =
|
|
23
|
+
const [lo, hi] = bulk === 'postgres' ? ['$1', '$2'] : ['?', '?'];
|
|
21
24
|
return `UPDATE ${METADATA_TABLE} AS m SET txSeq = t.txSeq FROM ${TRANSACTIONS_TABLE} AS t ` +
|
|
22
|
-
`WHERE t.hash = m.tx_hash AND
|
|
25
|
+
`WHERE t.hash = m.tx_hash AND t.txSeq >= ${lo} AND t.txSeq < ${hi} AND m.txSeq IS DISTINCT FROM t.txSeq`;
|
|
23
26
|
}
|
|
24
27
|
async function fillWindow(tx, lo, hi) {
|
|
25
|
-
const sql = metadataPositionStatement(
|
|
28
|
+
const sql = metadataPositionStatement((0, db_kind_1.connectedDbKind)());
|
|
26
29
|
if (sql) {
|
|
27
30
|
// a plain statement answers with the driver's result object
|
|
28
31
|
const result = await tx.run(sql, [lo, hi]);
|
|
@@ -31,25 +34,26 @@ async function fillWindow(tx, lo, hi) {
|
|
|
31
34
|
const txs = (await tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ txSeq: { '>=': lo, '<': hi } }))) ?? [];
|
|
32
35
|
let rows = 0;
|
|
33
36
|
for (const t of txs) {
|
|
34
|
-
|
|
37
|
+
// the same rule as the bulk statement: a row without its transaction's position, or with another one
|
|
38
|
+
const seq = Number(t.txSeq);
|
|
39
|
+
rows += Number(await tx.run(UPDATE.entity(cardano_1.TransactionMetadata).set({ txSeq: seq }).where({ tx_hash: t.hash, txSeq: null }))) || 0;
|
|
40
|
+
rows += Number(await tx.run(UPDATE.entity(cardano_1.TransactionMetadata).set({ txSeq: seq }).where({ tx_hash: t.hash, txSeq: { '!=': seq } }))) || 0;
|
|
35
41
|
}
|
|
36
42
|
return rows;
|
|
37
43
|
}
|
|
38
44
|
async function backfillMetadataPositions(opts = {}) {
|
|
39
|
-
const slotWindow = opts.slotWindow ?? 20_000;
|
|
40
|
-
const bounds = (await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.Transactions).columns('min(txSeq) as lo', 'max(txSeq) as hi'))));
|
|
41
45
|
const progress = { atSlot: 0, toSlot: 0, rows: 0 };
|
|
42
|
-
|
|
46
|
+
const range = await (0, window_plan_1.slotRangeOf)(cardano_1.Transactions, opts);
|
|
47
|
+
if (!range)
|
|
43
48
|
return progress;
|
|
44
|
-
|
|
45
|
-
progress.toSlot =
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
progress.atSlot =
|
|
50
|
-
|
|
51
|
-
}
|
|
52
|
-
logger.info(`metadata positions: ${progress.rows} rows filled up to slot ${progress.toSlot}`);
|
|
49
|
+
progress.atSlot = range.from;
|
|
50
|
+
progress.toSlot = range.to;
|
|
51
|
+
await (0, window_plan_1.walkSlotWindows)(range, {
|
|
52
|
+
slotWindow: opts.slotWindow,
|
|
53
|
+
shouldStop: opts.shouldStop,
|
|
54
|
+
afterWindow: (atSlot) => { progress.atSlot = atSlot; opts.onProgress?.({ ...progress }); },
|
|
55
|
+
}, async (tx, [lo, hi]) => { progress.rows += await fillWindow(tx, lo, hi); });
|
|
56
|
+
logger.info(`metadata positions: ${progress.rows} rows filled, slots ${range.from} to ${progress.atSlot}`);
|
|
53
57
|
return progress;
|
|
54
58
|
}
|
|
55
59
|
//# sourceMappingURL=metadata-position-backfill.js.map
|
|
@@ -29,11 +29,13 @@ export interface OutputDatumBackfillProgress extends OutputFillCounts {
|
|
|
29
29
|
}
|
|
30
30
|
export interface OutputDatumBackfillOptions {
|
|
31
31
|
client: Pick<CardanoClient, 'getTransactionsBatch' | 'supports'>;
|
|
32
|
-
/** Stored outputs per page.
|
|
32
|
+
/** Stored outputs per page. */
|
|
33
33
|
chunkSize?: number;
|
|
34
34
|
/** Transactions per backend read. */
|
|
35
35
|
batchSize?: number;
|
|
36
36
|
onProgress?: (p: OutputDatumBackfillProgress) => void;
|
|
37
|
+
/** Stops the walk before the next page. */
|
|
38
|
+
shouldStop?: () => boolean;
|
|
37
39
|
}
|
|
38
40
|
export declare function backfillOutputDatums(opts: OutputDatumBackfillOptions): Promise<OutputDatumBackfillProgress>;
|
|
39
41
|
//# sourceMappingURL=output-datum-backfill.d.ts.map
|
|
@@ -8,6 +8,7 @@ exports.fillOutputFields = fillOutputFields;
|
|
|
8
8
|
exports.backfillOutputDatums = backfillOutputDatums;
|
|
9
9
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
10
10
|
const collections_1 = require("../../utils/collections");
|
|
11
|
+
const key_pages_1 = require("./key-pages");
|
|
11
12
|
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
12
13
|
const { SELECT, UPDATE } = cds_1.default.ql;
|
|
13
14
|
const logger = cds_1.default.log('OutputDatumBackfill');
|
|
@@ -69,20 +70,12 @@ async function backfillOutputDatums(opts) {
|
|
|
69
70
|
const chunkSize = opts.chunkSize ?? 5000;
|
|
70
71
|
const batchSize = Math.min(opts.batchSize ?? 100, collections_1.IN_CHUNK);
|
|
71
72
|
const progress = { scanned: 0, candidates: 0, transactions: 0, missing: 0, outputs: 0, inputs: 0, ledgerUtxos: 0 };
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
break;
|
|
79
|
-
const full = rows.length === chunkSize;
|
|
80
|
-
const lastSeq = Number(rows[rows.length - 1].txSeq);
|
|
81
|
-
// The last transaction of a full page may continue on the next one, so its rows wait there.
|
|
82
|
-
const whole = rows.filter((r) => Number(r.txSeq) !== lastSeq);
|
|
83
|
-
const complete = full && whole.length ? whole : rows;
|
|
84
|
-
const candidates = complete.filter((r) => r.utxo_dataHash != null && r.utxo_inlineDatum == null);
|
|
85
|
-
progress.scanned += complete.length;
|
|
73
|
+
await (0, key_pages_1.pageByKey)({
|
|
74
|
+
entity: cardano_1.TransactionOutputs, keys: ['txSeq', 'outputIndex'], columns: ['utxo_dataHash', 'utxo_inlineDatum'], chunkSize,
|
|
75
|
+
shouldStop: opts.shouldStop,
|
|
76
|
+
}, async (rows) => {
|
|
77
|
+
const candidates = rows.filter((r) => r.utxo_dataHash != null && r.utxo_inlineDatum == null);
|
|
78
|
+
progress.scanned += rows.length;
|
|
86
79
|
progress.candidates += candidates.length;
|
|
87
80
|
for (const seqs of (0, collections_1.chunk)([...new Set(candidates.map((r) => Number(r.txSeq)))], batchSize)) {
|
|
88
81
|
const stored = (await cds_1.default.tx((tx) => tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ txSeq: { in: seqs } })))) ?? [];
|
|
@@ -98,11 +91,8 @@ async function backfillOutputDatums(opts) {
|
|
|
98
91
|
progress.inputs += counts.inputs;
|
|
99
92
|
progress.ledgerUtxos += counts.ledgerUtxos;
|
|
100
93
|
}
|
|
101
|
-
cursor = Number(complete[complete.length - 1].txSeq);
|
|
102
94
|
opts.onProgress?.({ ...progress });
|
|
103
|
-
|
|
104
|
-
break;
|
|
105
|
-
}
|
|
95
|
+
});
|
|
106
96
|
logger.info(`output datums: ${progress.outputs} outputs, ${progress.inputs} inputs and ${progress.ledgerUtxos} UTxO set rows filled; ` +
|
|
107
97
|
`${progress.candidates} candidates in ${progress.scanned} outputs, ${progress.transactions} transactions read, ${progress.missing} not returned`);
|
|
108
98
|
return progress;
|
|
@@ -38,6 +38,8 @@ export interface SyncCursor {
|
|
|
38
38
|
desiredRunning: boolean;
|
|
39
39
|
leaseOwner: string | null;
|
|
40
40
|
leaseUntil: string | null;
|
|
41
|
+
/** Since when the node is behind the cursor and its rollback was refused; null while it follows. */
|
|
42
|
+
nodeBehindSince: string | null;
|
|
41
43
|
utxoSet: UtxoSetState;
|
|
42
44
|
}
|
|
43
45
|
/** Ensure the cursor row exists and return it. A fresh DB gets the configured start point. */
|
|
@@ -46,7 +48,7 @@ export declare function ensureSyncStateSingleton(db: CapTransaction, network: st
|
|
|
46
48
|
export declare function readCursor(db: CapTransaction): Promise<SyncCursor | null>;
|
|
47
49
|
/** Whether the shared lease currently represents a live cluster-wide crawler. */
|
|
48
50
|
export declare function isCrawlerLeaseActive(cursor: SyncCursor | null, now?: Date): boolean;
|
|
49
|
-
/** Take a free or expired lease.
|
|
51
|
+
/** Take a free or expired lease. A foreign lease goes only when the UPDATE still sees it expired. */
|
|
50
52
|
export declare function tryAcquireCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
|
|
51
53
|
/** Renew the lease inside every crawler write transaction, so a former leader cannot write after a takeover. */
|
|
52
54
|
export declare function renewCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
|
|
@@ -67,6 +69,8 @@ export declare function releaseImportLease(db: CapTransaction, owner: string): P
|
|
|
67
69
|
export declare function setUtxoSetState(db: CapTransaction, state: Partial<UtxoSetState>): Promise<void>;
|
|
68
70
|
/** Reset the cursor to a rollback point (used by reorg handling). */
|
|
69
71
|
export declare function resetCursorTo(db: CapTransaction, point: CrawlPoint): Promise<void>;
|
|
72
|
+
export declare function markNodeBehind(db: CapTransaction, reason: string, leaseOwner?: string): Promise<boolean>;
|
|
73
|
+
export declare function recordRollbackRefusal(db: CapTransaction, reason: string, leaseOwner?: string): Promise<number>;
|
|
70
74
|
/** Set the crawler status (e.g. 'synced' when caught up, 'stopped' on shutdown). */
|
|
71
75
|
export declare function setSyncStatus(db: CapTransaction, status: CrawlSyncStatusValue, pauseCluster?: boolean): Promise<void>;
|
|
72
76
|
/** Record a crawler error and return the new streak. Sets status 'error' at the threshold. -1 means the lease is lost. */
|
|
@@ -18,11 +18,15 @@ exports.renewImportLease = renewImportLease;
|
|
|
18
18
|
exports.releaseImportLease = releaseImportLease;
|
|
19
19
|
exports.setUtxoSetState = setUtxoSetState;
|
|
20
20
|
exports.resetCursorTo = resetCursorTo;
|
|
21
|
+
exports.markNodeBehind = markNodeBehind;
|
|
22
|
+
exports.recordRollbackRefusal = recordRollbackRefusal;
|
|
21
23
|
exports.setSyncStatus = setSyncStatus;
|
|
22
24
|
exports.recordError = recordError;
|
|
23
25
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
24
26
|
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
25
27
|
const errors_1 = require("../../utils/errors");
|
|
28
|
+
const row_values_1 = require("../../utils/row-values");
|
|
29
|
+
const lease_1 = require("../../utils/lease");
|
|
26
30
|
const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
|
|
27
31
|
const logger = cds_1.default.log('CardanoCrawler');
|
|
28
32
|
// Cursor helpers for the singleton `CardanoSyncState` row.
|
|
@@ -32,59 +36,38 @@ exports.SINGLETON_ID = 'SINGLETON';
|
|
|
32
36
|
exports.MAX_CONSECUTIVE_ERRORS = 10;
|
|
33
37
|
/** A short, renewable DB lease prevents two app instances from advancing one cursor. */
|
|
34
38
|
exports.CRAWLER_LEASE_TTL_MS = 15_000;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
}
|
|
44
|
-
function timestamp(v) {
|
|
45
|
-
if (v === null || v === undefined || v === '')
|
|
46
|
-
return null;
|
|
47
|
-
if (v instanceof Date)
|
|
48
|
-
return v.toISOString();
|
|
49
|
-
return String(v);
|
|
50
|
-
}
|
|
51
|
-
/** Unlike the crawler lease, this ignores `desiredRunning`, which is cleared while an import runs. */
|
|
52
|
-
function importLeaseHeld(cursor, owner, expectedMs) {
|
|
53
|
-
if (!cursor || cursor.leaseOwner !== owner || !cursor.leaseUntil)
|
|
54
|
-
return false;
|
|
55
|
-
const actualMs = Date.parse(cursor.leaseUntil);
|
|
56
|
-
return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
|
|
57
|
-
}
|
|
58
|
-
function leaseDeadlineReached(cursor, owner, expectedMs) {
|
|
59
|
-
if (cursor?.desiredRunning !== true || cursor.leaseOwner !== owner || !cursor.leaseUntil)
|
|
60
|
-
return false;
|
|
61
|
-
const actualMs = Date.parse(cursor.leaseUntil);
|
|
62
|
-
// Some adapters normalize Timestamp precision/format. One second tolerance covers
|
|
63
|
-
// that representation change without accepting an old lease interval.
|
|
64
|
-
return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
|
|
65
|
-
}
|
|
39
|
+
/** The crawler lease: held only while the cluster is meant to run. */
|
|
40
|
+
const crawlerLease = () => ({
|
|
41
|
+
entity: cardano_1.CardanoSyncState,
|
|
42
|
+
key: { ID: exports.SINGLETON_ID },
|
|
43
|
+
requires: { desiredRunning: true },
|
|
44
|
+
holds: (row) => row.desiredRunning !== false,
|
|
45
|
+
});
|
|
46
|
+
/** The import lease on the same columns. It ignores `desiredRunning`, which is cleared while an import runs. */
|
|
47
|
+
const importLease = () => ({ entity: cardano_1.CardanoSyncState, key: { ID: exports.SINGLETON_ID } });
|
|
66
48
|
function toCursor(row) {
|
|
67
49
|
return {
|
|
68
50
|
network: row.network ?? null,
|
|
69
|
-
startSlot: optionalNum(row.startSlot),
|
|
51
|
+
startSlot: (0, row_values_1.optionalNum)(row.startSlot),
|
|
70
52
|
startBlockHash: row.startBlockHash ?? null,
|
|
71
|
-
lastSlot: requiredNum(row.lastSlot),
|
|
53
|
+
lastSlot: (0, row_values_1.requiredNum)(row.lastSlot),
|
|
72
54
|
lastBlockHash: row.lastBlockHash ?? null,
|
|
73
|
-
lastHeight: requiredNum(row.lastHeight),
|
|
74
|
-
tipSlot: optionalNum(row.tipSlot),
|
|
75
|
-
tipHeight: optionalNum(row.tipHeight),
|
|
55
|
+
lastHeight: (0, row_values_1.requiredNum)(row.lastHeight),
|
|
56
|
+
tipSlot: (0, row_values_1.optionalNum)(row.tipSlot),
|
|
57
|
+
tipHeight: (0, row_values_1.optionalNum)(row.tipHeight),
|
|
76
58
|
syncStatus: (row.syncStatus ?? 'stopped'),
|
|
77
|
-
consecutiveErrors: requiredNum(row.consecutiveErrors),
|
|
78
|
-
lastIndexedAt: timestamp(row.lastIndexedAt),
|
|
59
|
+
consecutiveErrors: (0, row_values_1.requiredNum)(row.consecutiveErrors),
|
|
60
|
+
lastIndexedAt: (0, row_values_1.timestamp)(row.lastIndexedAt),
|
|
79
61
|
desiredRunning: row.desiredRunning !== false,
|
|
80
62
|
leaseOwner: row.leaseOwner ?? null,
|
|
81
|
-
leaseUntil: timestamp(row.leaseUntil),
|
|
63
|
+
leaseUntil: (0, row_values_1.timestamp)(row.leaseUntil),
|
|
64
|
+
nodeBehindSince: (0, row_values_1.timestamp)(row.nodeBehindSince),
|
|
82
65
|
utxoSet: {
|
|
83
66
|
status: (row.utxoSetStatus ?? 'none'),
|
|
84
|
-
anchorSlot: optionalNum(row.utxoAnchorSlot),
|
|
67
|
+
anchorSlot: (0, row_values_1.optionalNum)(row.utxoAnchorSlot),
|
|
85
68
|
anchorHash: row.utxoAnchorHash ?? null,
|
|
86
|
-
importedAt: timestamp(row.utxoSetImportedAt),
|
|
87
|
-
appliedSlot: optionalNum(row.utxoAppliedSlot),
|
|
69
|
+
importedAt: (0, row_values_1.timestamp)(row.utxoSetImportedAt),
|
|
70
|
+
appliedSlot: (0, row_values_1.optionalNum)(row.utxoAppliedSlot),
|
|
88
71
|
error: row.utxoSetError ?? null,
|
|
89
72
|
},
|
|
90
73
|
};
|
|
@@ -137,51 +120,18 @@ function isCrawlerLeaseActive(cursor, now = new Date()) {
|
|
|
137
120
|
const deadline = Date.parse(cursor.leaseUntil);
|
|
138
121
|
return Number.isFinite(deadline) && deadline > now.getTime();
|
|
139
122
|
}
|
|
140
|
-
/** Take a free or expired lease.
|
|
123
|
+
/** Take a free or expired lease. A foreign lease goes only when the UPDATE still sees it expired. */
|
|
141
124
|
async function tryAcquireCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
|
|
142
|
-
|
|
143
|
-
if (!raw)
|
|
144
|
-
return false;
|
|
145
|
-
const current = toCursor(raw);
|
|
146
|
-
if (!current.desiredRunning)
|
|
147
|
-
return false;
|
|
148
|
-
const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
|
|
149
|
-
if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
|
|
150
|
-
return false;
|
|
151
|
-
// Compare the owner only. Some adapters reformat timestamps, so a leaseUntil match could fail forever.
|
|
152
|
-
// An old owner that renews meanwhile is fenced by its next renewal.
|
|
153
|
-
const where = {
|
|
154
|
-
ID: exports.SINGLETON_ID,
|
|
155
|
-
leaseOwner: raw.leaseOwner ?? null,
|
|
156
|
-
};
|
|
157
|
-
if (Object.prototype.hasOwnProperty.call(raw, 'desiredRunning')) {
|
|
158
|
-
where.desiredRunning = raw.desiredRunning;
|
|
159
|
-
}
|
|
160
|
-
const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
|
|
161
|
-
await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseOwner: owner, leaseUntil }).where(where));
|
|
162
|
-
const verified = await readCursor(db);
|
|
163
|
-
return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
|
|
125
|
+
return (0, lease_1.tryAcquireLease)(db, crawlerLease(), owner, { now, ttlMs });
|
|
164
126
|
}
|
|
165
127
|
/** Renew the lease inside every crawler write transaction, so a former leader cannot write after a takeover. */
|
|
166
128
|
async function renewCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
|
|
167
|
-
|
|
168
|
-
await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseUntil }).where({
|
|
169
|
-
ID: exports.SINGLETON_ID,
|
|
170
|
-
leaseOwner: owner,
|
|
171
|
-
desiredRunning: true,
|
|
172
|
-
}));
|
|
173
|
-
const verified = await readCursor(db);
|
|
174
|
-
return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
|
|
129
|
+
return (0, lease_1.renewLease)(db, crawlerLease(), owner, { now, ttlMs });
|
|
175
130
|
}
|
|
176
131
|
// Release only the caller's lease. `pauseCluster` keeps the crawler down across restarts.
|
|
177
132
|
// Use it only for failures a restart cannot fix, such as misconfiguration.
|
|
178
133
|
async function releaseCrawlerLease(db, owner, status, pauseCluster = false) {
|
|
179
|
-
await
|
|
180
|
-
leaseOwner: null,
|
|
181
|
-
leaseUntil: null,
|
|
182
|
-
syncStatus: status,
|
|
183
|
-
...(pauseCluster ? { desiredRunning: false } : {}),
|
|
184
|
-
}).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
|
|
134
|
+
await (0, lease_1.releaseLease)(db, crawlerLease(), owner, { syncStatus: status, ...(pauseCluster ? { desiredRunning: false } : {}) });
|
|
185
135
|
}
|
|
186
136
|
/** Store the pause intent for all instances. Resuming clears the error streak, so the backoff restarts. */
|
|
187
137
|
async function setCrawlerDesiredRunning(db, desiredRunning) {
|
|
@@ -226,40 +176,17 @@ extra, leaseOwner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
|
|
|
226
176
|
await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
|
|
227
177
|
return true;
|
|
228
178
|
}
|
|
229
|
-
|
|
230
|
-
await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({
|
|
231
|
-
ID: exports.SINGLETON_ID,
|
|
232
|
-
leaseOwner,
|
|
233
|
-
desiredRunning: true,
|
|
234
|
-
}));
|
|
235
|
-
const verified = await readCursor(db);
|
|
236
|
-
return leaseDeadlineReached(verified, leaseOwner, now.getTime() + ttlMs);
|
|
179
|
+
return (0, lease_1.renewLease)(db, crawlerLease(), leaseOwner, { now, ttlMs }, set);
|
|
237
180
|
}
|
|
238
181
|
// Lease for the UTxO set import on the crawler's lease columns. Blocks crawler starts and other imports.
|
|
239
182
|
async function tryAcquireImportLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
|
|
240
|
-
|
|
241
|
-
if (!raw)
|
|
242
|
-
return false;
|
|
243
|
-
const current = toCursor(raw);
|
|
244
|
-
const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
|
|
245
|
-
if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
|
|
246
|
-
return false;
|
|
247
|
-
const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
|
|
248
|
-
await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseOwner: owner, leaseUntil }).where({
|
|
249
|
-
ID: exports.SINGLETON_ID,
|
|
250
|
-
leaseOwner: raw.leaseOwner ?? null,
|
|
251
|
-
}));
|
|
252
|
-
const verified = await readCursor(db);
|
|
253
|
-
return importLeaseHeld(verified, owner, now.getTime() + ttlMs);
|
|
183
|
+
return (0, lease_1.tryAcquireLease)(db, importLease(), owner, { now, ttlMs });
|
|
254
184
|
}
|
|
255
185
|
async function renewImportLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
|
|
256
|
-
|
|
257
|
-
await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseUntil }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
|
|
258
|
-
const verified = await readCursor(db);
|
|
259
|
-
return importLeaseHeld(verified, owner, now.getTime() + ttlMs);
|
|
186
|
+
return (0, lease_1.renewLease)(db, importLease(), owner, { now, ttlMs });
|
|
260
187
|
}
|
|
261
188
|
async function releaseImportLease(db, owner) {
|
|
262
|
-
await
|
|
189
|
+
await (0, lease_1.releaseLease)(db, importLease(), owner);
|
|
263
190
|
}
|
|
264
191
|
/** Persist the crawler-fed ledger state's anchor / validity (crawler.utxoSet). */
|
|
265
192
|
async function setUtxoSetState(db, state) {
|
|
@@ -290,6 +217,36 @@ async function resetCursorTo(db, point) {
|
|
|
290
217
|
}).where({ ID: exports.SINGLETON_ID }));
|
|
291
218
|
logger.warn(`Sync cursor reset to fork point ${point.slot}/${point.hash}`);
|
|
292
219
|
}
|
|
220
|
+
// Records that the node behind chain-sync is behind the cursor, and since when. It is no error:
|
|
221
|
+
// nothing failed, the crawler waits for the node. The next chain-sync block clears it.
|
|
222
|
+
async function markNodeBehind(db, reason, leaseOwner) {
|
|
223
|
+
if (leaseOwner && !(await renewCrawlerLease(db, leaseOwner)))
|
|
224
|
+
return false;
|
|
225
|
+
const current = await readCursor(db);
|
|
226
|
+
await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
|
|
227
|
+
nodeBehindSince: current?.nodeBehindSince ?? new Date().toISOString(),
|
|
228
|
+
// the crawl stands still until the node catches up, so the crawled chain no longer ends at the tip
|
|
229
|
+
syncStatus: 'syncing',
|
|
230
|
+
lastError: reason.slice(0, 500),
|
|
231
|
+
lastErrorAt: new Date().toISOString(),
|
|
232
|
+
}).where({ ID: exports.SINGLETON_ID }));
|
|
233
|
+
return true;
|
|
234
|
+
}
|
|
235
|
+
// Records a chain-sync rollback that contradicts the stored chain: status error, the reason, and
|
|
236
|
+
// one more in the error streak. Returns the streak, or -1 when the lease is lost.
|
|
237
|
+
async function recordRollbackRefusal(db, reason, leaseOwner) {
|
|
238
|
+
if (leaseOwner && !(await renewCrawlerLease(db, leaseOwner)))
|
|
239
|
+
return -1;
|
|
240
|
+
const current = await readCursor(db);
|
|
241
|
+
const streak = (current?.consecutiveErrors ?? 0) + 1;
|
|
242
|
+
await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
|
|
243
|
+
consecutiveErrors: streak,
|
|
244
|
+
syncStatus: 'error',
|
|
245
|
+
lastError: reason.slice(0, 500),
|
|
246
|
+
lastErrorAt: new Date().toISOString(),
|
|
247
|
+
}).where({ ID: exports.SINGLETON_ID }));
|
|
248
|
+
return streak;
|
|
249
|
+
}
|
|
293
250
|
/** Set the crawler status (e.g. 'synced' when caught up, 'stopped' on shutdown). */
|
|
294
251
|
async function setSyncStatus(db, status, pauseCluster = false) {
|
|
295
252
|
await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
|
|
@@ -33,6 +33,8 @@ export interface TransactionBackfillOptions {
|
|
|
33
33
|
toSlot: number;
|
|
34
34
|
batchBlocks?: number;
|
|
35
35
|
onProgress?: (p: TransactionBackfillProgress) => void;
|
|
36
|
+
/** Ends the stream after the current batch. */
|
|
37
|
+
shouldStop?: () => boolean;
|
|
36
38
|
}
|
|
37
39
|
export interface TransactionBackfillResult extends TransactionBackfillProgress {
|
|
38
40
|
fromSlot: number;
|
|
@@ -11,6 +11,7 @@ const mappers_1 = require("../../utils/mappers");
|
|
|
11
11
|
const collections_1 = require("../../utils/collections");
|
|
12
12
|
const certificate_backfill_1 = require("./certificate-backfill");
|
|
13
13
|
const output_datum_backfill_1 = require("./output-datum-backfill");
|
|
14
|
+
const db_kind_1 = require("../../utils/db-kind");
|
|
14
15
|
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
15
16
|
const { SELECT, UPDATE, UPSERT, DELETE } = cds_1.default.ql;
|
|
16
17
|
const logger = cds_1.default.log('TransactionBackfill');
|
|
@@ -104,29 +105,21 @@ const FILL_COLUMNS = [
|
|
|
104
105
|
// One UPDATE per chunk that joins a JSON array of fills on the input key. COALESCE keeps existing
|
|
105
106
|
// values. Null for databases other than Postgres and SQLite, which update row by row.
|
|
106
107
|
function inputFillStatement(kind) {
|
|
108
|
+
const bulk = (0, db_kind_1.bulkSqlKind)(kind);
|
|
109
|
+
if (!bulk)
|
|
110
|
+
return null;
|
|
107
111
|
const set = FILL_COLUMNS
|
|
108
112
|
.map(([c]) => c.startsWith('has')
|
|
109
113
|
? `${c} = CASE WHEN v.address_address IS NOT NULL AND t.address_address IS NULL THEN v.${c} ELSE t.${c} END`
|
|
110
114
|
: `${c} = COALESCE(t.${c}, v.${c})`)
|
|
111
115
|
.join(', ');
|
|
112
|
-
|
|
113
|
-
const cols = [['txSeq', 'bigint'], ['inputIndex', 'integer'], ...FILL_COLUMNS].map(([c, ty]) => `${c.toLowerCase()} ${ty}`).join(', ');
|
|
114
|
-
return `UPDATE ${INPUTS_TABLE} AS t SET ${set} FROM json_to_recordset($1::json) AS v(${cols}) ` +
|
|
115
|
-
'WHERE t.txSeq = v.txseq AND t.inputIndex = v.inputindex';
|
|
116
|
-
}
|
|
117
|
-
if (kind === 'sqlite' || kind === 'better-sqlite') {
|
|
118
|
-
const cols = ['txSeq', 'inputIndex', ...FILL_COLUMNS.map(([c]) => c)]
|
|
119
|
-
.map((c) => `json_extract(value, '$.${c.toLowerCase()}') AS ${c}`).join(', ');
|
|
120
|
-
return `UPDATE ${INPUTS_TABLE} AS t SET ${set} FROM (SELECT ${cols} FROM json_each(?)) AS v ` +
|
|
121
|
-
'WHERE t.txSeq = v.txSeq AND t.inputIndex = v.inputIndex';
|
|
122
|
-
}
|
|
123
|
-
return null;
|
|
116
|
+
return (0, db_kind_1.jsonFillUpdate)(bulk, { table: INPUTS_TABLE, keys: [['txSeq', 'bigint'], ['inputIndex', 'integer']], values: FILL_COLUMNS, set });
|
|
124
117
|
}
|
|
125
118
|
/** Writes the fills of a batch: bulk statement where the database has one, else row by row. */
|
|
126
119
|
async function writeInputFills(tx, fills) {
|
|
127
120
|
if (!fills.length)
|
|
128
121
|
return;
|
|
129
|
-
const sql = inputFillStatement(
|
|
122
|
+
const sql = inputFillStatement((0, db_kind_1.connectedDbKind)());
|
|
130
123
|
if (!sql) {
|
|
131
124
|
for (const f of fills)
|
|
132
125
|
await tx.run(UPDATE.entity(cardano_1.TransactionInputs).set(f.set).where({ txSeq: f.txSeq, inputIndex: f.inputIndex }));
|