@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51

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.
Files changed (239) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -0,0 +1,41 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { CardanoClient } from '../cardano-client';
3
+ import type { TxOutputLine } from '../../utils/types';
4
+ /** A transaction as the source of its outputs' fields. */
5
+ export interface OutputSource {
6
+ hash: string;
7
+ txSeq: number;
8
+ outputs: TxOutputLine[];
9
+ }
10
+ /** Rows that received at least one field, per table. */
11
+ export interface OutputFillCounts {
12
+ outputs: number;
13
+ inputs: number;
14
+ ledgerUtxos: number;
15
+ }
16
+ export declare function fillOutputFields(tx: CapTransaction, sources: OutputSource[]): Promise<OutputFillCounts>;
17
+ export declare class OutputDatumBackfillError extends Error {
18
+ constructor(message: string);
19
+ }
20
+ export interface OutputDatumBackfillProgress extends OutputFillCounts {
21
+ /** Stored outputs read. */
22
+ scanned: number;
23
+ /** Outputs with a datum hash and no inline datum. */
24
+ candidates: number;
25
+ /** Transactions read again from the backend. */
26
+ transactions: number;
27
+ /** Candidate transactions the backend did not return. */
28
+ missing: number;
29
+ }
30
+ export interface OutputDatumBackfillOptions {
31
+ client: Pick<CardanoClient, 'getTransactionsBatch' | 'supports'>;
32
+ /** Stored outputs per page. */
33
+ chunkSize?: number;
34
+ /** Transactions per backend read. */
35
+ batchSize?: number;
36
+ onProgress?: (p: OutputDatumBackfillProgress) => void;
37
+ /** Stops the walk before the next page. */
38
+ shouldStop?: () => boolean;
39
+ }
40
+ export declare function backfillOutputDatums(opts: OutputDatumBackfillOptions): Promise<OutputDatumBackfillProgress>;
41
+ //# sourceMappingURL=output-datum-backfill.d.ts.map
@@ -0,0 +1,100 @@
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.OutputDatumBackfillError = void 0;
7
+ exports.fillOutputFields = fillOutputFields;
8
+ exports.backfillOutputDatums = backfillOutputDatums;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const collections_1 = require("../../utils/collections");
11
+ const key_pages_1 = require("./key-pages");
12
+ const cardano_1 = require("#cds-models/odatano/cardano");
13
+ const { SELECT, UPDATE } = cds_1.default.ql;
14
+ const logger = cds_1.default.log('OutputDatumBackfill');
15
+ // Datum and reference-script fields of stored outputs that an earlier read left empty. The same
16
+ // values go to the input rows that spent the output and to its row in the crawler-fed UTxO set.
17
+ const FIELDS = ['dataHash', 'inlineDatum', 'referenceScriptHash', 'referenceScriptSize', 'referenceScriptType'];
18
+ const OUTPUT_COLUMNS = ['txSeq', 'outputIndex', ...FIELDS.map((f) => `utxo_${f}`)];
19
+ /** Fields the stored output lacks and the fresh one carries. */
20
+ function missingFields(row, fresh) {
21
+ return FIELDS.flatMap((f) => {
22
+ const value = fresh[f];
23
+ return row[`utxo_${f}`] == null && value != null && value !== '' ? [[f, value]] : [];
24
+ });
25
+ }
26
+ // Fills the empty datum and reference-script fields of the stored outputs of these transactions,
27
+ // of the inputs that spent them and of their UTxO set rows. Only empty fields change.
28
+ async function fillOutputFields(tx, sources) {
29
+ const counts = { outputs: 0, inputs: 0, ledgerUtxos: 0 };
30
+ const bySeq = new Map(sources.map((s) => [s.txSeq, s]));
31
+ for (const seqs of (0, collections_1.chunk)([...bySeq.keys()], collections_1.IN_CHUNK)) {
32
+ const rows = (await tx.run(SELECT.from(cardano_1.TransactionOutputs).columns(...OUTPUT_COLUMNS).where({ txSeq: { in: seqs } }))) ?? [];
33
+ for (const row of rows) {
34
+ const source = bySeq.get(Number(row.txSeq));
35
+ const outputIndex = Number(row.outputIndex);
36
+ const fresh = source?.outputs.find((o) => o.outputIndex === outputIndex);
37
+ const missing = fresh ? missingFields(row, fresh) : [];
38
+ if (!source || !missing.length)
39
+ continue;
40
+ const set = Object.fromEntries(missing.map(([f, v]) => [`utxo_${f}`, v]));
41
+ await tx.run(UPDATE.entity(cardano_1.TransactionOutputs).set(set).where({ txSeq: row.txSeq, outputIndex }));
42
+ counts.outputs++;
43
+ let inputs = 0;
44
+ let ledgerUtxos = 0;
45
+ for (const [f, v] of missing) {
46
+ const spent = { spentTxHash: source.hash, spentOutputIndex: outputIndex, [`utxoData_${f}`]: null };
47
+ inputs = Math.max(inputs, Number(await tx.run(UPDATE.entity(cardano_1.TransactionInputs).set({ [`utxoData_${f}`]: v }).where(spent))) || 0);
48
+ const unspent = { txHash: source.hash, outputIndex, [`utxo_${f}`]: null };
49
+ ledgerUtxos = Math.max(ledgerUtxos, Number(await tx.run(UPDATE.entity(cardano_1.LedgerUTxOs).set({ [`utxo_${f}`]: v }).where(unspent))) || 0);
50
+ }
51
+ counts.inputs += inputs;
52
+ counts.ledgerUtxos += ledgerUtxos;
53
+ }
54
+ }
55
+ return counts;
56
+ }
57
+ class OutputDatumBackfillError extends Error {
58
+ constructor(message) {
59
+ super(message);
60
+ this.name = 'OutputDatumBackfillError';
61
+ }
62
+ }
63
+ exports.OutputDatumBackfillError = OutputDatumBackfillError;
64
+ // Reads every transaction again that holds an output with a datum hash and no inline datum, and
65
+ // fills what the backend returns. Pages by primary key only. Backend reads run outside any DB tx.
66
+ async function backfillOutputDatums(opts) {
67
+ if (!opts.client.supports('getTransaction')) {
68
+ throw new OutputDatumBackfillError('No configured backend serves transactions. With Ogmios only, run backfillTransactions over the crawled range.');
69
+ }
70
+ const chunkSize = opts.chunkSize ?? 5000;
71
+ const batchSize = Math.min(opts.batchSize ?? 100, collections_1.IN_CHUNK);
72
+ const progress = { scanned: 0, candidates: 0, transactions: 0, missing: 0, outputs: 0, inputs: 0, ledgerUtxos: 0 };
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;
79
+ progress.candidates += candidates.length;
80
+ for (const seqs of (0, collections_1.chunk)([...new Set(candidates.map((r) => Number(r.txSeq)))], batchSize)) {
81
+ const stored = (await cds_1.default.tx((tx) => tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ txSeq: { in: seqs } })))) ?? [];
82
+ const fresh = stored.length ? await opts.client.getTransactionsBatch(stored.map((t) => t.hash)) : new Map();
83
+ const sources = stored.flatMap((t) => {
84
+ const read = fresh.get(t.hash);
85
+ return read ? [{ hash: t.hash, txSeq: Number(t.txSeq), outputs: read.outputs ?? [] }] : [];
86
+ });
87
+ progress.transactions += sources.length;
88
+ progress.missing += seqs.length - sources.length;
89
+ const counts = await cds_1.default.tx((tx) => fillOutputFields(tx, sources));
90
+ progress.outputs += counts.outputs;
91
+ progress.inputs += counts.inputs;
92
+ progress.ledgerUtxos += counts.ledgerUtxos;
93
+ }
94
+ opts.onProgress?.({ ...progress });
95
+ });
96
+ logger.info(`output datums: ${progress.outputs} outputs, ${progress.inputs} inputs and ${progress.ledgerUtxos} UTxO set rows filled; ` +
97
+ `${progress.candidates} candidates in ${progress.scanned} outputs, ${progress.transactions} transactions read, ${progress.missing} not returned`);
98
+ return progress;
99
+ }
100
+ //# sourceMappingURL=output-datum-backfill.js.map
@@ -1,15 +1,4 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
- /**
3
- * Chain crawler cursor helpers (v2.0 pre-sync).
4
- *
5
- * `CardanoSyncState` is a singleton row (key = SINGLETON_ID) that records how far
6
- * the crawler has indexed the chain, so a restart resumes instead of re-crawling.
7
- *
8
- * NOTE (CAP 10): Integer64 / Decimal columns are read back from SQLite/HANA as
9
- * STRINGS, not JS numbers — the same change that makes them strings over OData.
10
- * Every read here therefore coerces numeric fields with `num()`; callers get a
11
- * clean numeric `SyncCursor` and never have to think about it.
12
- */
13
2
  export declare const SINGLETON_ID = "SINGLETON";
14
3
  /** Circuit-breaker threshold: pause crawling after this many back-to-back failures. */
15
4
  export declare const MAX_CONSECUTIVE_ERRORS = 10;
@@ -22,6 +11,17 @@ export interface CrawlPoint {
22
11
  hash: string;
23
12
  height?: number;
24
13
  }
14
+ export type UtxoSetStatusValue = 'none' | 'importing' | 'active' | 'invalid';
15
+ /** Crawler-fed ledger state (crawler.utxoSet): the anchor the imported UTxO set describes. */
16
+ export interface UtxoSetState {
17
+ status: UtxoSetStatusValue;
18
+ anchorSlot: number | null;
19
+ anchorHash: string | null;
20
+ importedAt: string | null;
21
+ /** Slot of the last block applied to the ledger tables (null = nothing applied since the import). */
22
+ appliedSlot: number | null;
23
+ error: string | null;
24
+ }
25
25
  /** Normalized, number-typed view of the cursor row (numeric fields already coerced). */
26
26
  export interface SyncCursor {
27
27
  network: string | null;
@@ -34,61 +34,45 @@ export interface SyncCursor {
34
34
  tipHeight: number | null;
35
35
  syncStatus: CrawlSyncStatusValue;
36
36
  consecutiveErrors: number;
37
+ lastIndexedAt: string | null;
37
38
  desiredRunning: boolean;
38
39
  leaseOwner: string | null;
39
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;
43
+ utxoSet: UtxoSetState;
40
44
  }
41
- /**
42
- * Idempotently ensure the singleton cursor row exists and return it.
43
- * On first call (fresh DB) the row is created with the configured start point
44
- * (if given) and status 'stopped'. Subsequent calls just return the current row.
45
- * Safe to call from both the crawler and the control service.
46
- */
45
+ /** Ensure the cursor row exists and return it. A fresh DB gets the configured start point. */
47
46
  export declare function ensureSyncStateSingleton(db: CapTransaction, network: string, start?: CrawlPoint): Promise<SyncCursor>;
48
47
  /** Read the current cursor, or null if it has not been initialized yet. */
49
48
  export declare function readCursor(db: CapTransaction): Promise<SyncCursor | null>;
50
49
  /** Whether the shared lease currently represents a live cluster-wide crawler. */
51
50
  export declare function isCrawlerLeaseActive(cursor: SyncCursor | null, now?: Date): boolean;
52
- /**
53
- * Atomically acquire an expired/unowned lease with compare-and-swap semantics.
54
- * The post-update read is intentional: CAP adapters consistently return the row
55
- * for SELECT, whereas affected-row return shapes differ between SQLite and HANA.
56
- */
51
+ /** Take a free or expired lease. A foreign lease goes only when the UPDATE still sees it expired. */
57
52
  export declare function tryAcquireCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
58
- /**
59
- * Renew/fence a lease. Call this inside the same transaction as every crawler write:
60
- * the conditional UPDATE serializes a former leader against a newly elected one.
61
- */
53
+ /** Renew the lease inside every crawler write transaction, so a former leader cannot write after a takeover. */
62
54
  export declare function renewCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
63
- /**
64
- * Release only the caller's lease; a stale process can never clear a successor.
65
- *
66
- * `pauseCluster` clears `desiredRunning`, which no restart undoes — every instance
67
- * then refuses to start until an operator calls resumeCrawler. Reserve it for
68
- * failures a restart genuinely cannot fix (misconfiguration, no resume point). A
69
- * crashed stream, a provider outage or a node restart must NOT latch: those are
70
- * exactly the cases where coming back up should resume the pre-sync by itself.
71
- */
72
55
  export declare function releaseCrawlerLease(db: CapTransaction, owner: string, status: CrawlSyncStatusValue, pauseCluster?: boolean): Promise<void>;
73
- /** Persist the pause/resume intent shared by every app instance. */
56
+ /** Store the pause intent for all instances. Resuming clears the error streak, so the backoff restarts. */
74
57
  export declare function setCrawlerDesiredRunning(db: CapTransaction, desiredRunning: boolean): Promise<void>;
75
- /**
76
- * Advance the cursor to a freshly-indexed block. Sets the status (default 'syncing';
77
- * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
78
- * lastIndexedAt. Optionally records the latest known tip (for progress).
79
- */
58
+ export declare function latchPoisonBlock(db: CapTransaction, message: string): Promise<void>;
80
59
  export declare function advanceCursor(db: CapTransaction, block: CrawlPoint, tip?: {
81
60
  slot: number;
82
61
  height?: number;
83
- }, status?: CrawlSyncStatusValue): Promise<void>;
62
+ }, status?: CrawlSyncStatusValue,
63
+ /** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
64
+ extra?: Record<string, unknown>, leaseOwner?: string, now?: Date, ttlMs?: number): Promise<boolean>;
65
+ export declare function tryAcquireImportLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
66
+ export declare function renewImportLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
67
+ export declare function releaseImportLease(db: CapTransaction, owner: string): Promise<void>;
68
+ /** Persist the crawler-fed ledger state's anchor / validity (crawler.utxoSet). */
69
+ export declare function setUtxoSetState(db: CapTransaction, state: Partial<UtxoSetState>): Promise<void>;
84
70
  /** Reset the cursor to a rollback point (used by reorg handling). */
85
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>;
86
74
  /** Set the crawler status (e.g. 'synced' when caught up, 'stopped' on shutdown). */
87
75
  export declare function setSyncStatus(db: CapTransaction, status: CrawlSyncStatusValue, pauseCluster?: boolean): Promise<void>;
88
- /**
89
- * Record a crawler error. Increments the consecutive-error counter and flips status
90
- * to 'error' once the circuit-breaker threshold is reached. Returns the new streak
91
- * length so the caller can decide whether to back off / stop.
92
- */
76
+ /** Record a crawler error and return the new streak. Sets status 'error' at the threshold. -1 means the lease is lost. */
93
77
  export declare function recordError(db: CapTransaction, err: unknown, leaseOwner?: string): Promise<number>;
94
78
  //# sourceMappingURL=sync-state.d.ts.map
@@ -11,84 +11,68 @@ exports.tryAcquireCrawlerLease = tryAcquireCrawlerLease;
11
11
  exports.renewCrawlerLease = renewCrawlerLease;
12
12
  exports.releaseCrawlerLease = releaseCrawlerLease;
13
13
  exports.setCrawlerDesiredRunning = setCrawlerDesiredRunning;
14
+ exports.latchPoisonBlock = latchPoisonBlock;
14
15
  exports.advanceCursor = advanceCursor;
16
+ exports.tryAcquireImportLease = tryAcquireImportLease;
17
+ exports.renewImportLease = renewImportLease;
18
+ exports.releaseImportLease = releaseImportLease;
19
+ exports.setUtxoSetState = setUtxoSetState;
15
20
  exports.resetCursorTo = resetCursorTo;
21
+ exports.markNodeBehind = markNodeBehind;
22
+ exports.recordRollbackRefusal = recordRollbackRefusal;
16
23
  exports.setSyncStatus = setSyncStatus;
17
24
  exports.recordError = recordError;
18
25
  const cds_1 = __importDefault(require("@sap/cds"));
19
26
  const cardano_1 = require("#cds-models/odatano/cardano");
20
27
  const errors_1 = require("../../utils/errors");
28
+ const row_values_1 = require("../../utils/row-values");
29
+ const lease_1 = require("../../utils/lease");
21
30
  const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
22
31
  const logger = cds_1.default.log('CardanoCrawler');
23
- /**
24
- * Chain crawler cursor helpers (v2.0 pre-sync).
25
- *
26
- * `CardanoSyncState` is a singleton row (key = SINGLETON_ID) that records how far
27
- * the crawler has indexed the chain, so a restart resumes instead of re-crawling.
28
- *
29
- * NOTE (CAP 10): Integer64 / Decimal columns are read back from SQLite/HANA as
30
- * STRINGS, not JS numbers — the same change that makes them strings over OData.
31
- * Every read here therefore coerces numeric fields with `num()`; callers get a
32
- * clean numeric `SyncCursor` and never have to think about it.
33
- */
32
+ // Cursor helpers for the singleton `CardanoSyncState` row.
33
+ // Numeric columns come back from the DB as strings, so every read converts them to numbers.
34
34
  exports.SINGLETON_ID = 'SINGLETON';
35
35
  /** Circuit-breaker threshold: pause crawling after this many back-to-back failures. */
36
36
  exports.MAX_CONSECUTIVE_ERRORS = 10;
37
37
  /** A short, renewable DB lease prevents two app instances from advancing one cursor. */
38
38
  exports.CRAWLER_LEASE_TTL_MS = 15_000;
39
- /**
40
- * Coerce a CAP-10 numeric-as-string (or number/bigint/null) into a JS number.
41
- * Separate optional/required helpers avoid overload declarations (and the
42
- * no-redeclare lint false-positive they caused).
43
- */
44
- function optionalNum(v) {
45
- if (v === null || v === undefined || v === '')
46
- return null;
47
- const n = Number(v);
48
- return Number.isNaN(n) ? null : n;
49
- }
50
- function requiredNum(v, fallback = 0) {
51
- return optionalNum(v) ?? fallback;
52
- }
53
- function timestamp(v) {
54
- if (v === null || v === undefined || v === '')
55
- return null;
56
- if (v instanceof Date)
57
- return v.toISOString();
58
- return String(v);
59
- }
60
- function leaseDeadlineReached(cursor, owner, expectedMs) {
61
- if (cursor?.desiredRunning !== true || cursor.leaseOwner !== owner || !cursor.leaseUntil)
62
- return false;
63
- const actualMs = Date.parse(cursor.leaseUntil);
64
- // Some adapters normalize Timestamp precision/format. One second tolerance covers
65
- // that representation change without accepting an old lease interval.
66
- return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
67
- }
68
- /** Map a raw DB row into the normalized numeric cursor. */
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 } });
69
48
  function toCursor(row) {
70
49
  return {
71
50
  network: row.network ?? null,
72
- startSlot: optionalNum(row.startSlot),
51
+ startSlot: (0, row_values_1.optionalNum)(row.startSlot),
73
52
  startBlockHash: row.startBlockHash ?? null,
74
- lastSlot: requiredNum(row.lastSlot),
53
+ lastSlot: (0, row_values_1.requiredNum)(row.lastSlot),
75
54
  lastBlockHash: row.lastBlockHash ?? null,
76
- lastHeight: requiredNum(row.lastHeight),
77
- tipSlot: optionalNum(row.tipSlot),
78
- 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),
79
58
  syncStatus: (row.syncStatus ?? 'stopped'),
80
- consecutiveErrors: requiredNum(row.consecutiveErrors),
59
+ consecutiveErrors: (0, row_values_1.requiredNum)(row.consecutiveErrors),
60
+ lastIndexedAt: (0, row_values_1.timestamp)(row.lastIndexedAt),
81
61
  desiredRunning: row.desiredRunning !== false,
82
62
  leaseOwner: row.leaseOwner ?? null,
83
- leaseUntil: timestamp(row.leaseUntil),
63
+ leaseUntil: (0, row_values_1.timestamp)(row.leaseUntil),
64
+ nodeBehindSince: (0, row_values_1.timestamp)(row.nodeBehindSince),
65
+ utxoSet: {
66
+ status: (row.utxoSetStatus ?? 'none'),
67
+ anchorSlot: (0, row_values_1.optionalNum)(row.utxoAnchorSlot),
68
+ anchorHash: row.utxoAnchorHash ?? null,
69
+ importedAt: (0, row_values_1.timestamp)(row.utxoSetImportedAt),
70
+ appliedSlot: (0, row_values_1.optionalNum)(row.utxoAppliedSlot),
71
+ error: row.utxoSetError ?? null,
72
+ },
84
73
  };
85
74
  }
86
- /**
87
- * Idempotently ensure the singleton cursor row exists and return it.
88
- * On first call (fresh DB) the row is created with the configured start point
89
- * (if given) and status 'stopped'. Subsequent calls just return the current row.
90
- * Safe to call from both the crawler and the control service.
91
- */
75
+ /** Ensure the cursor row exists and return it. A fresh DB gets the configured start point. */
92
76
  async function ensureSyncStateSingleton(db, network, start) {
93
77
  const existing = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
94
78
  if (existing) {
@@ -113,6 +97,12 @@ async function ensureSyncStateSingleton(db, network, start) {
113
97
  desiredRunning: true,
114
98
  leaseOwner: null,
115
99
  leaseUntil: null,
100
+ utxoSetStatus: 'none',
101
+ utxoAnchorSlot: null,
102
+ utxoAnchorHash: null,
103
+ utxoSetImportedAt: null,
104
+ utxoAppliedSlot: null,
105
+ utxoSetError: null,
116
106
  };
117
107
  await db.run(INSERT.into(cardano_1.CardanoSyncState).entries(row));
118
108
  logger.info(`Sync cursor initialized (network=${network}, start=${start ? `${start.slot}/${start.hash}` : 'none'})`);
@@ -130,86 +120,43 @@ function isCrawlerLeaseActive(cursor, now = new Date()) {
130
120
  const deadline = Date.parse(cursor.leaseUntil);
131
121
  return Number.isFinite(deadline) && deadline > now.getTime();
132
122
  }
133
- /**
134
- * Atomically acquire an expired/unowned lease with compare-and-swap semantics.
135
- * The post-update read is intentional: CAP adapters consistently return the row
136
- * for SELECT, whereas affected-row return shapes differ between SQLite and HANA.
137
- */
123
+ /** Take a free or expired lease. A foreign lease goes only when the UPDATE still sees it expired. */
138
124
  async function tryAcquireCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
139
- const raw = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
140
- if (!raw)
141
- return false;
142
- const current = toCursor(raw);
143
- if (!current.desiredRunning)
144
- return false;
145
- const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
146
- if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
147
- return false;
148
- // CAS on the observed OWNER only (a plain string that round-trips identically
149
- // on every adapter). If two instances race, the first writer changes leaseOwner
150
- // and the loser's UPDATE matches 0 rows → its read-back verification fails.
151
- // Deliberately NOT comparing leaseUntil: HANA/driver timestamp normalization can
152
- // make the read-back representation differ from what the WHERE serializes, so a
153
- // timestamp-equality CAS may NEVER match again after a leader crash — the lease
154
- // would be stuck until the row is cleared by hand. The residual race (the old
155
- // owner renewing concurrently) resolves via fencing: its next renew no longer
156
- // matches leaseOwner and it halts.
157
- const where = {
158
- ID: exports.SINGLETON_ID,
159
- leaseOwner: raw.leaseOwner ?? null,
160
- };
161
- if (Object.prototype.hasOwnProperty.call(raw, 'desiredRunning')) {
162
- where.desiredRunning = raw.desiredRunning;
163
- }
164
- const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
165
- await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseOwner: owner, leaseUntil }).where(where));
166
- const verified = await readCursor(db);
167
- return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
125
+ return (0, lease_1.tryAcquireLease)(db, crawlerLease(), owner, { now, ttlMs });
168
126
  }
169
- /**
170
- * Renew/fence a lease. Call this inside the same transaction as every crawler write:
171
- * the conditional UPDATE serializes a former leader against a newly elected one.
172
- */
127
+ /** Renew the lease inside every crawler write transaction, so a former leader cannot write after a takeover. */
173
128
  async function renewCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
174
- const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
175
- await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseUntil }).where({
176
- ID: exports.SINGLETON_ID,
177
- leaseOwner: owner,
178
- desiredRunning: true,
179
- }));
180
- const verified = await readCursor(db);
181
- return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
129
+ return (0, lease_1.renewLease)(db, crawlerLease(), owner, { now, ttlMs });
182
130
  }
183
- /**
184
- * Release only the caller's lease; a stale process can never clear a successor.
185
- *
186
- * `pauseCluster` clears `desiredRunning`, which no restart undoes — every instance
187
- * then refuses to start until an operator calls resumeCrawler. Reserve it for
188
- * failures a restart genuinely cannot fix (misconfiguration, no resume point). A
189
- * crashed stream, a provider outage or a node restart must NOT latch: those are
190
- * exactly the cases where coming back up should resume the pre-sync by itself.
191
- */
131
+ // Release only the caller's lease. `pauseCluster` keeps the crawler down across restarts.
132
+ // Use it only for failures a restart cannot fix, such as misconfiguration.
192
133
  async function releaseCrawlerLease(db, owner, status, pauseCluster = false) {
193
- await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
194
- leaseOwner: null,
195
- leaseUntil: null,
196
- syncStatus: status,
197
- ...(pauseCluster ? { desiredRunning: false } : {}),
198
- }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
134
+ await (0, lease_1.releaseLease)(db, crawlerLease(), owner, { syncStatus: status, ...(pauseCluster ? { desiredRunning: false } : {}) });
199
135
  }
200
- /** Persist the pause/resume intent shared by every app instance. */
136
+ /** Store the pause intent for all instances. Resuming clears the error streak, so the backoff restarts. */
201
137
  async function setCrawlerDesiredRunning(db, desiredRunning) {
202
138
  const set = { desiredRunning };
203
- if (!desiredRunning)
139
+ if (desiredRunning)
140
+ set.consecutiveErrors = 0;
141
+ else
204
142
  set.syncStatus = 'stopped';
205
143
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
206
144
  }
207
- /**
208
- * Advance the cursor to a freshly-indexed block. Sets the status (default 'syncing';
209
- * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
210
- * lastIndexedAt. Optionally records the latest known tip (for progress).
211
- */
212
- async function advanceCursor(db, block, tip, status = 'syncing') {
145
+ // Latch the cluster off for a poison block. Not tied to the lease, since the fault is in the block.
146
+ // Only resumeCrawler brings the crawler back.
147
+ async function latchPoisonBlock(db, message) {
148
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
149
+ desiredRunning: false,
150
+ syncStatus: 'error',
151
+ lastError: message.slice(0, 500),
152
+ lastErrorAt: new Date().toISOString(),
153
+ }).where({ ID: exports.SINGLETON_ID }));
154
+ }
155
+ // Advance the cursor to an indexed block and clear the error streak. With `leaseOwner` the
156
+ // same UPDATE renews the lease. Returns false when the lease is lost, and the caller must roll back.
157
+ async function advanceCursor(db, block, tip, status = 'syncing',
158
+ /** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
159
+ extra, leaseOwner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
213
160
  const set = {
214
161
  lastSlot: block.slot,
215
162
  lastBlockHash: block.hash,
@@ -218,12 +165,46 @@ async function advanceCursor(db, block, tip, status = 'syncing') {
218
165
  syncStatus: status,
219
166
  consecutiveErrors: 0,
220
167
  lastError: null,
168
+ ...(extra ?? {}),
221
169
  };
222
170
  if (tip) {
223
171
  set.tipSlot = tip.slot;
224
172
  if (tip.height !== undefined)
225
173
  set.tipHeight = tip.height;
226
174
  }
175
+ if (!leaseOwner) {
176
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
177
+ return true;
178
+ }
179
+ return (0, lease_1.renewLease)(db, crawlerLease(), leaseOwner, { now, ttlMs }, set);
180
+ }
181
+ // Lease for the UTxO set import on the crawler's lease columns. Blocks crawler starts and other imports.
182
+ async function tryAcquireImportLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
183
+ return (0, lease_1.tryAcquireLease)(db, importLease(), owner, { now, ttlMs });
184
+ }
185
+ async function renewImportLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
186
+ return (0, lease_1.renewLease)(db, importLease(), owner, { now, ttlMs });
187
+ }
188
+ async function releaseImportLease(db, owner) {
189
+ await (0, lease_1.releaseLease)(db, importLease(), owner);
190
+ }
191
+ /** Persist the crawler-fed ledger state's anchor / validity (crawler.utxoSet). */
192
+ async function setUtxoSetState(db, state) {
193
+ const set = {};
194
+ if (state.status !== undefined)
195
+ set.utxoSetStatus = state.status;
196
+ if (state.anchorSlot !== undefined)
197
+ set.utxoAnchorSlot = state.anchorSlot;
198
+ if (state.anchorHash !== undefined)
199
+ set.utxoAnchorHash = state.anchorHash;
200
+ if (state.importedAt !== undefined)
201
+ set.utxoSetImportedAt = state.importedAt;
202
+ if (state.appliedSlot !== undefined)
203
+ set.utxoAppliedSlot = state.appliedSlot;
204
+ if (state.error !== undefined)
205
+ set.utxoSetError = state.error;
206
+ if (!Object.keys(set).length)
207
+ return;
227
208
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
228
209
  }
229
210
  /** Reset the cursor to a rollback point (used by reorg handling). */
@@ -236,6 +217,36 @@ async function resetCursorTo(db, point) {
236
217
  }).where({ ID: exports.SINGLETON_ID }));
237
218
  logger.warn(`Sync cursor reset to fork point ${point.slot}/${point.hash}`);
238
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
+ }
239
250
  /** Set the crawler status (e.g. 'synced' when caught up, 'stopped' on shutdown). */
240
251
  async function setSyncStatus(db, status, pauseCluster = false) {
241
252
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
@@ -243,11 +254,7 @@ async function setSyncStatus(db, status, pauseCluster = false) {
243
254
  ...(pauseCluster ? { desiredRunning: false } : {}),
244
255
  }).where({ ID: exports.SINGLETON_ID }));
245
256
  }
246
- /**
247
- * Record a crawler error. Increments the consecutive-error counter and flips status
248
- * to 'error' once the circuit-breaker threshold is reached. Returns the new streak
249
- * length so the caller can decide whether to back off / stop.
250
- */
257
+ /** Record a crawler error and return the new streak. Sets status 'error' at the threshold. -1 means the lease is lost. */
251
258
  async function recordError(db, err, leaseOwner) {
252
259
  if (leaseOwner && !(await renewCrawlerLease(db, leaseOwner)))
253
260
  return -1;
@@ -0,0 +1,46 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { CardanoClient } from '../cardano-client';
3
+ import type { ChainPoint } from '../backends/cardano-backend';
4
+ import type { Transaction } from '../../utils/types';
5
+ import type { LedgerLookup } from '../ledger-state';
6
+ export declare class TransactionBackfillError extends Error {
7
+ constructor(message: string);
8
+ }
9
+ export interface TransactionBackfillProgress {
10
+ /** Slot of the last block handled. */
11
+ atSlot: number;
12
+ blocks: number;
13
+ transactions: number;
14
+ /** Input rows that got at least one field. */
15
+ inputs: number;
16
+ /** Output rows that got a datum or reference-script field. */
17
+ outputs: number;
18
+ redeemers: number;
19
+ datums: number;
20
+ /** Transactions whose stored rows differed from the ledger view (order, inputs or outputs the ledger did not apply) and were rewritten. */
21
+ rewritten: number;
22
+ /** Transactions left as they are: stored inputs differ from the stream. */
23
+ skipped: number;
24
+ }
25
+ /** Resolves bare chain-sync inputs from the index (CardanoIndexer.resolveInputs). */
26
+ export interface InputResolver {
27
+ resolveInputs(tx: CapTransaction, txs: Transaction[], ledger?: LedgerLookup): Promise<void>;
28
+ }
29
+ export interface TransactionBackfillOptions {
30
+ client: CardanoClient;
31
+ indexer: InputResolver;
32
+ fromSlot: number;
33
+ toSlot: number;
34
+ batchBlocks?: number;
35
+ onProgress?: (p: TransactionBackfillProgress) => void;
36
+ /** Ends the stream after the current batch. */
37
+ shouldStop?: () => boolean;
38
+ }
39
+ export interface TransactionBackfillResult extends TransactionBackfillProgress {
40
+ fromSlot: number;
41
+ toSlot: number;
42
+ intersection: ChainPoint | 'origin';
43
+ }
44
+ export declare function inputFillStatement(kind: string): string | null;
45
+ export declare function backfillTransactions(opts: TransactionBackfillOptions): Promise<TransactionBackfillResult>;
46
+ //# sourceMappingURL=transaction-backfill.d.ts.map