@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.
Files changed (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +23 -12
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +36 -44
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -18,6 +18,7 @@ const asset_decimals_backfill_1 = require("./blockchain/crawler/asset-decimals-b
18
18
  const asset_registry_backfill_1 = require("./blockchain/crawler/asset-registry-backfill");
19
19
  const output_datum_backfill_1 = require("./blockchain/crawler/output-datum-backfill");
20
20
  const metadata_position_backfill_1 = require("./blockchain/crawler/metadata-position-backfill");
21
+ const asset_slice_backfill_1 = require("./blockchain/crawler/asset-slice-backfill");
21
22
  const input_asset_copies_1 = require("./blockchain/crawler/input-asset-copies");
22
23
  const validators_1 = require("./utils/validators");
23
24
  const server_1 = require("./server");
@@ -25,37 +26,41 @@ const config_1 = require("./config");
25
26
  const liveness_1 = require("./utils/liveness");
26
27
  const readiness_1 = require("./utils/readiness");
27
28
  const result_numbers_1 = require("./utils/result-numbers");
29
+ const detached_run_1 = require("./utils/detached-run");
30
+ const failed_recheck_1 = require("./blockchain/signing/failed-recheck");
28
31
  const cardano_1 = require("#cds-models/odatano/cardano");
29
32
  const { SELECT } = cds_1.default.ql;
30
33
  const logger = cds_1.default.log('CardanoIndexerService');
31
- /** One import at a time per process; the promise is only used as the busy flag. */
32
- let utxoSetImportInFlight = null;
33
- /** Set while a start request is validated, so a second request cannot start a parallel run. */
34
- let certificateBackfillStarting = false;
35
- let certificateBackfill = {
36
- status: 'none', fromSlot: 0, toSlot: 0, atSlot: 0, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0, removed: 0,
37
- startedAt: null, finishedAt: null, error: null,
34
+ // One run per kind and process. Each keeps the state of its last run until the next start.
35
+ const certificateRun = new detached_run_1.DetachedRun('Certificate backfill', { fromSlot: 0, toSlot: 0, atSlot: 0, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0, removed: 0 }, ['fromSlot', 'toSlot', 'atSlot']);
36
+ const transactionRun = new detached_run_1.DetachedRun('Transaction backfill', { fromSlot: 0, toSlot: 0, atSlot: 0, blocks: 0, transactions: 0, inputs: 0, outputs: 0, redeemers: 0, datums: 0, rewritten: 0, skipped: 0 }, ['fromSlot', 'toSlot', 'atSlot']);
37
+ const credentialRun = new detached_run_1.DetachedRun('Payment-credential backfill', { table: null, outputs: 0, inputs: 0, ledgerUtxos: 0 });
38
+ const decimalsRun = new detached_run_1.DetachedRun('Asset-decimals backfill', { scanned: 0, candidates: 0, filled: 0 });
39
+ const registryRun = new detached_run_1.DetachedRun('Asset-registry backfill', { units: 0, processed: 0, filled: 0, failed: 0, absent: 0, skipped: 0 });
40
+ const datumRun = new detached_run_1.DetachedRun('Output-datum backfill', { scanned: 0, candidates: 0, transactions: 0, missing: 0, outputs: 0, inputs: 0, ledgerUtxos: 0 });
41
+ const metadataRun = new detached_run_1.DetachedRun('Metadata-position backfill', { atSlot: 0, toSlot: 0, rows: 0 }, ['atSlot', 'toSlot']);
42
+ const sliceRun = new detached_run_1.DetachedRun('Asset-slice backfill', { table: null, outputs: 0, inputs: 0, ledgerUtxos: 0, ledgerAddresses: 0, utxoSlices: 0, addressSlices: 0 });
43
+ const epochRun = new detached_run_1.DetachedRun('Epoch backfill', { atEpoch: 0, toEpoch: 0, updated: 0, created: 0 });
44
+ const recheckRun = new detached_run_1.DetachedRun('Re-check of failed submits', { submissions: 0, requests: 0, jobs: 0, restored: 0 });
45
+ const pruneRun = new detached_run_1.DetachedRun('Prune of input asset copies', { atSlot: 0, toSlot: 0, referenced: 0, kept: 0, deleted: 0 }, ['atSlot', 'toSlot']);
46
+ const restoreRun = new detached_run_1.DetachedRun('Restore of input asset copies', { atSlot: 0, toSlot: 0, restored: 0, rows: 0 }, ['atSlot', 'toSlot']);
47
+ /** The UTxO set import and its two repairs: one at a time, the status shows it as importing. */
48
+ const utxoSetRun = new detached_run_1.DetachedRun('UTxO set import', {});
49
+ /** The runs cancelMaintenance can stop, by the name getStatus shows them under. */
50
+ const CANCELLABLE = {
51
+ certificateBackfill: certificateRun,
52
+ transactionBackfill: transactionRun,
53
+ credentialBackfill: credentialRun,
54
+ decimalsBackfill: decimalsRun,
55
+ registryBackfill: registryRun,
56
+ datumBackfill: datumRun,
57
+ metadataBackfill: metadataRun,
58
+ epochBackfill: epochRun,
59
+ failedRecheck: recheckRun,
60
+ sliceBackfill: sliceRun,
61
+ copyPrune: pruneRun,
62
+ copyRestore: restoreRun,
38
63
  };
39
- let transactionBackfillStarting = false;
40
- let transactionBackfill = {
41
- status: 'none', fromSlot: 0, toSlot: 0, atSlot: 0, blocks: 0, transactions: 0, inputs: 0, outputs: 0, redeemers: 0, datums: 0, rewritten: 0, skipped: 0,
42
- startedAt: null, finishedAt: null, error: null,
43
- };
44
- const NO_DATUM_PROGRESS = { scanned: 0, candidates: 0, transactions: 0, missing: 0, outputs: 0, inputs: 0, ledgerUtxos: 0 };
45
- let datumBackfill = { status: 'none', ...NO_DATUM_PROGRESS, startedAt: null, finishedAt: null, error: null };
46
- let metadataBackfill = { status: 'none', atSlot: 0, toSlot: 0, rows: 0, startedAt: null, finishedAt: null, error: null };
47
- const IDLE = { status: 'none', startedAt: null, finishedAt: null, error: null };
48
- let epochBackfill = { ...IDLE, atEpoch: 0, toEpoch: 0, updated: 0, created: 0 };
49
- let copyPrune = { ...IDLE, atSlot: 0, toSlot: 0, referenced: 0, kept: 0, deleted: 0 };
50
- let copyRestore = { ...IDLE, atSlot: 0, toSlot: 0, restored: 0, rows: 0 };
51
- let credentialBackfill = {
52
- status: 'none', table: null, outputs: 0, inputs: 0, ledgerUtxos: 0, startedAt: null, finishedAt: null, error: null,
53
- };
54
- let decimalsBackfill = {
55
- status: 'none', scanned: 0, candidates: 0, filled: 0, startedAt: null, finishedAt: null, error: null,
56
- };
57
- const REGISTRY_IDLE = { units: 0, processed: 0, filled: 0, failed: 0, absent: 0, skipped: 0 };
58
- let registryBackfill = { ...REGISTRY_IDLE, status: 'none', startedAt: null, finishedAt: null, error: null };
59
64
  /** Slot range of a backfill: defaults to crawl start .. cursor, never past the cursor. */
60
65
  async function backfillRange(db, data) {
61
66
  const cursor = await (0, sync_state_1.readCursor)(db);
@@ -131,52 +136,17 @@ module.exports = (srv) => {
131
136
  consecutiveErrors: cursor?.consecutiveErrors ?? 0,
132
137
  lastIndexedAt: cursor?.lastIndexedAt ?? null,
133
138
  stalled: isCrawlerStalled(cursor),
139
+ nodeBehindSince: cursor?.nodeBehindSince ?? null,
134
140
  utxoSet: {
135
141
  enabled: crawlerOption('utxoSet'),
136
- status: utxoSetImportInFlight ? 'importing' : (cursor?.utxoSet?.status ?? 'none'),
142
+ status: utxoSetRun.isBusy() ? 'importing' : (cursor?.utxoSet?.status ?? 'none'),
137
143
  anchorSlot: cursor?.utxoSet?.anchorSlot == null ? null : String(cursor.utxoSet.anchorSlot),
138
144
  anchorHash: cursor?.utxoSet?.anchorHash ?? null,
139
145
  importedAt: cursor?.utxoSet?.importedAt ?? null,
140
146
  error: cursor?.utxoSet?.error ?? null,
141
147
  },
142
- certificateBackfill: {
143
- status: certificateBackfill.status,
144
- fromSlot: String(certificateBackfill.fromSlot),
145
- toSlot: String(certificateBackfill.toSlot),
146
- atSlot: String(certificateBackfill.atSlot),
147
- blocks: certificateBackfill.blocks,
148
- certificates: certificateBackfill.certificates,
149
- withdrawals: certificateBackfill.withdrawals,
150
- removed: certificateBackfill.removed,
151
- startedAt: certificateBackfill.startedAt,
152
- finishedAt: certificateBackfill.finishedAt,
153
- error: certificateBackfill.error,
154
- },
155
- transactionBackfill: {
156
- status: transactionBackfill.status,
157
- fromSlot: String(transactionBackfill.fromSlot),
158
- toSlot: String(transactionBackfill.toSlot),
159
- atSlot: String(transactionBackfill.atSlot),
160
- blocks: transactionBackfill.blocks,
161
- transactions: transactionBackfill.transactions,
162
- inputs: transactionBackfill.inputs,
163
- outputs: transactionBackfill.outputs,
164
- redeemers: transactionBackfill.redeemers,
165
- datums: transactionBackfill.datums,
166
- rewritten: transactionBackfill.rewritten,
167
- skipped: transactionBackfill.skipped,
168
- startedAt: transactionBackfill.startedAt,
169
- finishedAt: transactionBackfill.finishedAt,
170
- error: transactionBackfill.error,
171
- },
172
- credentialBackfill: { ...credentialBackfill },
173
- decimalsBackfill: { ...decimalsBackfill },
174
- registryBackfill: { ...registryBackfill },
175
- datumBackfill: { ...datumBackfill },
176
- metadataBackfill: { ...metadataBackfill, atSlot: String(metadataBackfill.atSlot), toSlot: String(metadataBackfill.toSlot) },
177
- epochBackfill: { ...epochBackfill },
178
- copyPrune: { ...copyPrune, atSlot: String(copyPrune.atSlot), toSlot: String(copyPrune.toSlot) },
179
- copyRestore: { ...copyRestore, atSlot: String(copyRestore.atSlot), toSlot: String(copyRestore.toSlot) },
148
+ ...Object.fromEntries(Object.entries(CANCELLABLE).map(([name, run]) => [name, run.snapshot()])),
149
+ epochBackfill: epochRun.snapshot(),
180
150
  epochSnapshots: {
181
151
  enabled: crawlerOption('epochSnapshots'),
182
152
  source: epochSnapshotSource(),
@@ -190,218 +160,175 @@ module.exports = (srv) => {
190
160
  };
191
161
  });
192
162
  });
163
+ const busy = (req, action, run) => (0, errors_1.rejectInvalid)(req, action, `${run.label} is already running`);
164
+ /** A transaction backfill rewrites inputs a prune or restore moves, so they never overlap. */
165
+ const copyWalkBusy = () => pruneRun.isBusy() || restoreRun.isBusy();
193
166
  // backfillCertificates: a second chain-sync stream over crawled blocks.
194
167
  // Writes only the certificate and withdrawal tables and runs detached.
195
168
  srv.on('backfillCertificates', async (req) => {
196
169
  const data = (req.data ?? {});
197
- if (data.fromSlot != null && !Number.isInteger(Number(data.fromSlot)))
198
- return (0, errors_1.rejectInvalid)(req, 'backfillCertificates', 'fromSlot must be an integer', 'fromSlot');
199
- if (data.toSlot != null && !Number.isInteger(Number(data.toSlot)))
200
- return (0, errors_1.rejectInvalid)(req, 'backfillCertificates', 'toSlot must be an integer', 'toSlot');
201
- if (certificateBackfill.status === 'running' || certificateBackfillStarting)
202
- return (0, errors_1.rejectInvalid)(req, 'backfillCertificates', 'A certificate backfill is already running');
170
+ if (certificateRun.isBusy())
171
+ return busy(req, 'backfillCertificates', certificateRun);
203
172
  if (!(0, server_1.getCardanoClient)().getChainSyncBackend())
204
173
  return (0, errors_1.rejectInvalid)(req, 'backfillCertificates', 'No chain-sync backend available (needs Ogmios)');
205
- certificateBackfillStarting = true;
206
- try {
207
- return await (0, backend_request_handler_1.handleRequest)(req, async (db) => {
208
- const { fromSlot, toSlot } = await backfillRange(db, data);
209
- certificateBackfill = {
210
- status: 'running', fromSlot, toSlot, atSlot: fromSlot, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0, removed: 0,
211
- startedAt: new Date().toISOString(), finishedAt: null, error: null,
212
- };
213
- void (0, certificate_backfill_1.backfillCertificates)({
214
- client: (0, server_1.getCardanoClient)(), fromSlot, toSlot,
174
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => certificateRun.start(async () => {
175
+ const { fromSlot, toSlot } = await backfillRange(db, data);
176
+ return {
177
+ initial: { fromSlot, toSlot, atSlot: fromSlot },
178
+ run: (ctl) => (0, certificate_backfill_1.backfillCertificates)({
179
+ client: (0, server_1.getCardanoClient)(), fromSlot, toSlot, shouldStop: ctl.shouldStop,
215
180
  onProgress: (p) => {
216
- Object.assign(certificateBackfill, p);
217
- if (certificateBackfill.blocks % 20_000 < 200)
181
+ ctl.progress(p);
182
+ if (p.blocks % 20_000 < 200)
218
183
  logger.info(`Certificate backfill at slot ${p.atSlot}: ${p.blocks} blocks, ${p.certificates} certificates, ${p.withdrawals} withdrawals`);
219
184
  },
220
- })
221
- .then((r) => { Object.assign(certificateBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
222
- .catch((err) => {
223
- const message = err instanceof Error ? err.message : String(err);
224
- Object.assign(certificateBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
225
- logger.error(`Certificate backfill failed: ${message}`);
226
- });
227
- return {
185
+ }),
186
+ answer: {
228
187
  accepted: true,
229
188
  fromSlot: String(fromSlot),
230
189
  toSlot: String(toSlot),
231
190
  message: `Certificate backfill started for slots ${fromSlot}..${toSlot}; poll getStatus().certificateBackfill.`,
232
- };
233
- });
234
- }
235
- finally {
236
- certificateBackfillStarting = false;
237
- }
191
+ },
192
+ };
193
+ }));
238
194
  });
239
195
  // backfillTransactions: a second chain-sync stream over crawled blocks.
240
196
  // Fills empty input fields and the redeemers and runs detached.
241
197
  srv.on('backfillTransactions', async (req) => {
242
198
  const data = (req.data ?? {});
243
- if (data.fromSlot != null && !Number.isInteger(Number(data.fromSlot)))
244
- return (0, errors_1.rejectInvalid)(req, 'backfillTransactions', 'fromSlot must be an integer', 'fromSlot');
245
- if (data.toSlot != null && !Number.isInteger(Number(data.toSlot)))
246
- return (0, errors_1.rejectInvalid)(req, 'backfillTransactions', 'toSlot must be an integer', 'toSlot');
247
- if (transactionBackfill.status === 'running' || transactionBackfillStarting)
248
- return (0, errors_1.rejectInvalid)(req, 'backfillTransactions', 'A transaction backfill is already running');
199
+ if (transactionRun.isBusy())
200
+ return busy(req, 'backfillTransactions', transactionRun);
201
+ if (copyWalkBusy())
202
+ return (0, errors_1.rejectInvalid)(req, 'backfillTransactions', 'A prune or restore of input asset copies is running; it moves the inputs this backfill rewrites');
249
203
  if (!(0, server_1.getCardanoClient)().getChainSyncBackend())
250
204
  return (0, errors_1.rejectInvalid)(req, 'backfillTransactions', 'No chain-sync backend available (needs Ogmios)');
251
- transactionBackfillStarting = true;
252
- try {
253
- return await (0, backend_request_handler_1.handleRequest)(req, async (db) => {
254
- const { fromSlot, toSlot } = await backfillRange(db, data);
255
- transactionBackfill = {
256
- status: 'running', fromSlot, toSlot, atSlot: fromSlot, blocks: 0, transactions: 0, inputs: 0, outputs: 0, redeemers: 0, datums: 0, rewritten: 0, skipped: 0,
257
- startedAt: new Date().toISOString(), finishedAt: null, error: null,
258
- };
259
- void (0, transaction_backfill_1.backfillTransactions)({
260
- client: (0, server_1.getCardanoClient)(), indexer: (0, server_1.getCardanoIndexer)(), fromSlot, toSlot,
205
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => transactionRun.start(async () => {
206
+ const { fromSlot, toSlot } = await backfillRange(db, data);
207
+ return {
208
+ initial: { fromSlot, toSlot, atSlot: fromSlot },
209
+ run: (ctl) => (0, transaction_backfill_1.backfillTransactions)({
210
+ client: (0, server_1.getCardanoClient)(), indexer: (0, server_1.getCardanoIndexer)(), fromSlot, toSlot, shouldStop: ctl.shouldStop,
261
211
  onProgress: (p) => {
262
- Object.assign(transactionBackfill, p);
263
- if (transactionBackfill.blocks % 20_000 < 200)
212
+ ctl.progress(p);
213
+ if (p.blocks % 20_000 < 200)
264
214
  logger.info(`Transaction backfill at slot ${p.atSlot}: ${p.blocks} blocks, ${p.inputs} inputs, ${p.redeemers} redeemers`);
265
215
  },
266
- })
267
- .then((r) => { Object.assign(transactionBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
268
- .catch((err) => {
269
- const message = err instanceof Error ? err.message : String(err);
270
- Object.assign(transactionBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
271
- logger.error(`Transaction backfill failed: ${message}`);
272
- });
273
- return {
216
+ }),
217
+ answer: {
274
218
  accepted: true,
275
219
  fromSlot: String(fromSlot),
276
220
  toSlot: String(toSlot),
277
221
  message: `Transaction backfill started for slots ${fromSlot}..${toSlot}; poll getStatus().transactionBackfill.`,
278
- };
279
- });
280
- }
281
- finally {
282
- transactionBackfillStarting = false;
283
- }
222
+ },
223
+ };
224
+ }));
284
225
  });
285
226
  // backfillPaymentCredentials: fills the credential from the stored address in every UTxO table.
286
227
  // Needs no backend and runs detached. Progress is in getStatus().credentialBackfill.
287
228
  srv.on('backfillPaymentCredentials', async (req) => {
288
- if (credentialBackfill.status === 'running')
289
- return (0, errors_1.rejectInvalid)(req, 'backfillPaymentCredentials', 'A payment-credential backfill is already running');
290
- credentialBackfill = { status: 'running', table: null, outputs: 0, inputs: 0, ledgerUtxos: 0, startedAt: new Date().toISOString(), finishedAt: null, error: null };
291
- void (0, credential_backfill_1.backfillUtxoCredentials)({
292
- onProgress: (p) => { Object.assign(credentialBackfill, p); },
293
- })
294
- .then((r) => { Object.assign(credentialBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
295
- .catch((err) => {
296
- const message = err instanceof Error ? err.message : String(err);
297
- Object.assign(credentialBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
298
- logger.error(`Payment-credential backfill failed: ${message}`);
299
- });
300
- return { accepted: true, message: 'Payment-credential backfill started; poll getStatus().credentialBackfill.' };
229
+ if (credentialRun.isBusy())
230
+ return busy(req, 'backfillPaymentCredentials', credentialRun);
231
+ return credentialRun.start(() => ({
232
+ run: (ctl) => (0, credential_backfill_1.backfillUtxoCredentials)({ onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
233
+ answer: { accepted: true, message: 'Payment-credential backfill started; poll getStatus().credentialBackfill.' },
234
+ }));
301
235
  });
302
236
  // backfillAssetDecimals: reads the CIP-68 reference datum of every label 333 and 444 unit.
303
237
  // Needs no backend and runs detached. Progress is in getStatus().decimalsBackfill.
304
238
  srv.on('backfillAssetDecimals', async (req) => {
305
- if (decimalsBackfill.status === 'running')
306
- return (0, errors_1.rejectInvalid)(req, 'backfillAssetDecimals', 'An asset-decimals backfill is already running');
307
- decimalsBackfill = { status: 'running', scanned: 0, candidates: 0, filled: 0, startedAt: new Date().toISOString(), finishedAt: null, error: null };
308
- void (0, asset_decimals_backfill_1.backfillAssetDecimals)({
309
- onProgress: (p) => { Object.assign(decimalsBackfill, p); },
310
- })
311
- .then((r) => { Object.assign(decimalsBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
312
- .catch((err) => {
313
- const message = err instanceof Error ? err.message : String(err);
314
- Object.assign(decimalsBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
315
- logger.error(`Asset-decimals backfill failed: ${message}`);
316
- });
317
- return { accepted: true, message: 'Asset-decimals backfill started; poll getStatus().decimalsBackfill.' };
239
+ if (decimalsRun.isBusy())
240
+ return busy(req, 'backfillAssetDecimals', decimalsRun);
241
+ return decimalsRun.start(() => ({
242
+ run: (ctl) => (0, asset_decimals_backfill_1.backfillAssetDecimals)({ onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
243
+ answer: { accepted: true, message: 'Asset-decimals backfill started; poll getStatus().decimalsBackfill.' },
244
+ }));
318
245
  });
319
246
  // backfillAssetRegistry: writes the CIP-26 registry fields of every registered unit. The registry is
320
247
  // off-chain: it comes from a backend that lists it, or from the entry files of its repository.
321
248
  srv.on('backfillAssetRegistry', async (req) => {
322
249
  const data = (req.data ?? {});
323
250
  const source = data.source ?? 'koios';
324
- if (registryBackfill.status === 'running')
325
- return (0, errors_1.rejectInvalid)(req, 'backfillAssetRegistry', 'An asset-registry backfill is already running');
326
- if (source === 'file') {
327
- if (!data.path)
328
- return (0, errors_1.rejectMissing)(req, 'backfillAssetRegistry', 'path');
329
- try {
330
- await (0, asset_registry_backfill_1.registryEntryFiles)(data.path);
331
- }
332
- catch (err) {
333
- return (0, errors_1.rejectInvalid)(req, 'backfillAssetRegistry', err instanceof Error ? err.message : String(err), 'path');
334
- }
335
- }
336
- else if (!(0, server_1.getCardanoClient)().getTokenRegistryBackend()) {
251
+ if (registryRun.isBusy())
252
+ return busy(req, 'backfillAssetRegistry', registryRun);
253
+ if (source === 'file' && !data.path)
254
+ return (0, errors_1.rejectMissing)(req, 'backfillAssetRegistry', 'path');
255
+ if (source !== 'file' && !(0, server_1.getCardanoClient)().getTokenRegistryBackend()) {
337
256
  return (0, errors_1.rejectInvalid)(req, 'backfillAssetRegistry', 'No backend lists the token registry (needs Koios, or source file)');
338
257
  }
339
- registryBackfill = { ...REGISTRY_IDLE, status: 'running', startedAt: new Date().toISOString(), finishedAt: null, error: null };
340
- const onProgress = (p) => { Object.assign(registryBackfill, p); };
341
- const run = source === 'file' && data.path
342
- ? (0, asset_registry_backfill_1.backfillAssetRegistryFromFiles)({ directory: data.path, onProgress })
343
- : (0, asset_registry_backfill_1.backfillAssetRegistry)({ client: (0, server_1.getCardanoClient)(), indexer: (0, server_1.getCardanoIndexer)(), onProgress });
344
- void run
345
- .then((r) => { Object.assign(registryBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
346
- .catch((err) => {
347
- const message = err instanceof Error ? err.message : String(err);
348
- Object.assign(registryBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
349
- logger.error(`Asset-registry backfill failed: ${message}`);
350
- });
351
- return { accepted: true, message: 'Asset-registry backfill started; poll getStatus().registryBackfill.' };
258
+ const directory = source === 'file' ? String(data.path) : null;
259
+ try {
260
+ return await registryRun.start(async () => {
261
+ if (directory)
262
+ await (0, asset_registry_backfill_1.registryEntryFiles)(directory);
263
+ return {
264
+ run: (ctl) => directory
265
+ ? (0, asset_registry_backfill_1.backfillAssetRegistryFromFiles)({ directory, onProgress: ctl.progress, shouldStop: ctl.shouldStop })
266
+ : (0, asset_registry_backfill_1.backfillAssetRegistry)({ client: (0, server_1.getCardanoClient)(), indexer: (0, server_1.getCardanoIndexer)(), onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
267
+ answer: { accepted: true, message: 'Asset-registry backfill started; poll getStatus().registryBackfill.' },
268
+ };
269
+ });
270
+ }
271
+ catch (err) {
272
+ return (0, errors_1.rejectInvalid)(req, 'backfillAssetRegistry', err instanceof Error ? err.message : String(err), 'path');
273
+ }
352
274
  });
353
275
  // backfillOutputDatums: reads transactions again whose outputs hold a datum hash and no inline
354
276
  // datum. Needs a backend that serves transactions. Progress is in getStatus().datumBackfill.
355
277
  srv.on('backfillOutputDatums', async (req) => {
356
- if (datumBackfill.status === 'running')
357
- return (0, errors_1.rejectInvalid)(req, 'backfillOutputDatums', 'An output-datum backfill is already running');
278
+ if (datumRun.isBusy())
279
+ return busy(req, 'backfillOutputDatums', datumRun);
358
280
  if (!(0, server_1.getCardanoClient)().supports('getTransaction')) {
359
281
  return (0, errors_1.rejectInvalid)(req, 'backfillOutputDatums', 'No configured backend serves transactions. With Ogmios only, run backfillTransactions over the crawled range');
360
282
  }
361
- datumBackfill = { status: 'running', ...NO_DATUM_PROGRESS, startedAt: new Date().toISOString(), finishedAt: null, error: null };
362
- void (0, output_datum_backfill_1.backfillOutputDatums)({
363
- client: (0, server_1.getCardanoClient)(),
364
- onProgress: (p) => { Object.assign(datumBackfill, p); },
365
- })
366
- .then((r) => { Object.assign(datumBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
367
- .catch((err) => {
368
- const message = err instanceof Error ? err.message : String(err);
369
- Object.assign(datumBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
370
- logger.error(`Output-datum backfill failed: ${message}`);
371
- });
372
- return { accepted: true, message: 'Output-datum backfill started; poll getStatus().datumBackfill.' };
283
+ return datumRun.start(() => ({
284
+ run: (ctl) => (0, output_datum_backfill_1.backfillOutputDatums)({ client: (0, server_1.getCardanoClient)(), onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
285
+ answer: { accepted: true, message: 'Output-datum backfill started; poll getStatus().datumBackfill.' },
286
+ }));
373
287
  });
374
288
  // backfillMetadataPositions: writes the chain position to metadata rows that lack it.
375
289
  // Needs no backend and runs detached. Progress is in getStatus().metadataBackfill.
376
290
  srv.on('backfillMetadataPositions', async (req) => {
377
- if (metadataBackfill.status === 'running')
378
- return (0, errors_1.rejectInvalid)(req, 'backfillMetadataPositions', 'A metadata-position backfill is already running');
379
- metadataBackfill = { status: 'running', atSlot: 0, toSlot: 0, rows: 0, startedAt: new Date().toISOString(), finishedAt: null, error: null };
380
- void (0, metadata_position_backfill_1.backfillMetadataPositions)({
381
- onProgress: (p) => { Object.assign(metadataBackfill, p); },
382
- })
383
- .then((r) => { Object.assign(metadataBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
384
- .catch((err) => {
385
- const message = err instanceof Error ? err.message : String(err);
386
- Object.assign(metadataBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
387
- logger.error(`Metadata-position backfill failed: ${message}`);
388
- });
389
- return { accepted: true, message: 'Metadata-position backfill started; poll getStatus().metadataBackfill.' };
291
+ const data = (req.data ?? {});
292
+ const range = { fromSlot: data.fromSlot == null ? null : Number(data.fromSlot), toSlot: data.toSlot == null ? null : Number(data.toSlot) };
293
+ if (range.fromSlot != null && range.toSlot != null && range.fromSlot > range.toSlot) {
294
+ return (0, errors_1.rejectInvalid)(req, 'backfillMetadataPositions', 'fromSlot must not be after toSlot', 'fromSlot');
295
+ }
296
+ if (metadataRun.isBusy())
297
+ return busy(req, 'backfillMetadataPositions', metadataRun);
298
+ return metadataRun.start(() => ({
299
+ run: (ctl) => (0, metadata_position_backfill_1.backfillMetadataPositions)({ ...range, onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
300
+ answer: { accepted: true, message: 'Metadata-position backfill started; poll getStatus().metadataBackfill.' },
301
+ }));
302
+ });
303
+ // backfillAssetSlices: writes policy id, name and fingerprint of every stored asset row as derived
304
+ // from its unit. Needs no backend and runs detached. Progress is in getStatus().sliceBackfill.
305
+ srv.on('backfillAssetSlices', async (req) => {
306
+ if (sliceRun.isBusy())
307
+ return busy(req, 'backfillAssetSlices', sliceRun);
308
+ return sliceRun.start(() => ({
309
+ run: (ctl) => (0, asset_slice_backfill_1.backfillAssetSlices)({ onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
310
+ answer: { accepted: true, message: 'Asset-slice backfill started; poll getStatus().sliceBackfill.' },
311
+ }));
390
312
  });
391
313
  // backfillEpochs: rebuilds the epoch rows of the crawled range from the stored blocks.
392
314
  // Needs no backend and runs detached.
393
315
  srv.on('backfillEpochs', async (req) => {
394
- if (epochBackfill.status === 'running')
395
- return (0, errors_1.rejectInvalid)(req, 'backfillEpochs', 'An epoch backfill is already running');
396
- epochBackfill = { ...IDLE, status: 'running', startedAt: new Date().toISOString(), atEpoch: 0, toEpoch: 0, updated: 0, created: 0 };
397
- void (0, server_1.getCardanoIndexer)().backfillEpochs((p) => { Object.assign(epochBackfill, p); })
398
- .then((r) => { Object.assign(epochBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
399
- .catch((err) => {
400
- const message = err instanceof Error ? err.message : String(err);
401
- Object.assign(epochBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
402
- logger.error(`Epoch backfill failed: ${message}`);
403
- });
404
- return { accepted: true, message: 'Epoch backfill started; poll getStatus().epochBackfill.' };
316
+ if (epochRun.isBusy())
317
+ return busy(req, 'backfillEpochs', epochRun);
318
+ return epochRun.start(() => ({
319
+ run: (ctl) => (0, server_1.getCardanoIndexer)().backfillEpochs(ctl.progress, () => ctl.shouldStop()),
320
+ answer: { accepted: true, message: 'Epoch backfill started; poll getStatus().epochBackfill.' },
321
+ }));
322
+ });
323
+ // recheckFailedSubmits: a submission or signing request marked failed whose transaction is on chain
324
+ // with passing scripts goes back to submitted. Rows an earlier version failed on a refusal or time.
325
+ srv.on('recheckFailedSubmits', async (req) => {
326
+ if (recheckRun.isBusy())
327
+ return busy(req, 'recheckFailedSubmits', recheckRun);
328
+ return recheckRun.start(() => ({
329
+ run: (ctl) => (0, failed_recheck_1.recheckFailed)({ indexer: (0, server_1.getCardanoIndexer)(), client: (0, server_1.getCardanoClient)() }, { shouldStop: () => ctl.shouldStop(), onProgress: ctl.progress }),
330
+ answer: { accepted: true, message: 'Re-check of failed submits started; poll getStatus().failedRecheck.' },
331
+ }));
405
332
  });
406
333
  // Slot range of a walk over input asset copies. Both bounds are required: the caller names what
407
334
  // moves. Null after the request was rejected.
@@ -422,41 +349,51 @@ module.exports = (srv) => {
422
349
  }
423
350
  return data.slotWindow == null ? range : { ...range, slotWindow: Number(data.slotWindow) };
424
351
  };
425
- const copyWalkRunning = () => copyPrune.status === 'running' || copyRestore.status === 'running';
352
+ /** Why a copy walk cannot start now; null when it can. */
353
+ const copyWalkConflict = () => {
354
+ if (copyWalkBusy())
355
+ return 'A prune or restore of input asset copies is already running';
356
+ if (transactionRun.isBusy())
357
+ return 'A transaction backfill is running; it rewrites the inputs this walk moves';
358
+ return null;
359
+ };
426
360
  // pruneInputAssetCopies: moves the inputs of a slot range from asset copies to the output they
427
361
  // spent and deletes those copies. Needs no backend and runs detached.
428
362
  srv.on('pruneInputAssetCopies', async (req) => {
429
363
  const range = copyRange(req, 'pruneInputAssetCopies');
430
364
  if (!range)
431
365
  return;
432
- if (copyWalkRunning())
433
- return (0, errors_1.rejectInvalid)(req, 'pruneInputAssetCopies', 'A prune or restore of input asset copies is already running');
434
- copyPrune = { ...IDLE, status: 'running', startedAt: new Date().toISOString(), atSlot: 0, toSlot: 0, referenced: 0, kept: 0, deleted: 0 };
435
- void (0, input_asset_copies_1.pruneInputAssetCopies)({ ...range, onProgress: (p) => { Object.assign(copyPrune, p); } })
436
- .then((r) => { Object.assign(copyPrune, r, { status: 'done', finishedAt: new Date().toISOString() }); })
437
- .catch((err) => {
438
- const message = err instanceof Error ? err.message : String(err);
439
- Object.assign(copyPrune, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
440
- logger.error(`Prune of input asset copies failed: ${message}`);
441
- });
442
- return { accepted: true, message: 'Prune of input asset copies started; poll getStatus().copyPrune.' };
366
+ const conflict = copyWalkConflict();
367
+ if (conflict)
368
+ return (0, errors_1.rejectInvalid)(req, 'pruneInputAssetCopies', conflict);
369
+ return pruneRun.start(() => ({
370
+ run: (ctl) => (0, input_asset_copies_1.pruneInputAssetCopies)({ ...range, onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
371
+ answer: { accepted: true, message: 'Prune of input asset copies started; poll getStatus().copyPrune.' },
372
+ }));
443
373
  });
444
374
  // restoreInputAssetCopies: the way back, copies written from the outputs.
445
375
  srv.on('restoreInputAssetCopies', async (req) => {
446
376
  const range = copyRange(req, 'restoreInputAssetCopies');
447
377
  if (!range)
448
378
  return;
449
- if (copyWalkRunning())
450
- return (0, errors_1.rejectInvalid)(req, 'restoreInputAssetCopies', 'A prune or restore of input asset copies is already running');
451
- copyRestore = { ...IDLE, status: 'running', startedAt: new Date().toISOString(), atSlot: 0, toSlot: 0, restored: 0, rows: 0 };
452
- void (0, input_asset_copies_1.restoreInputAssetCopies)({ ...range, onProgress: (p) => { Object.assign(copyRestore, p); } })
453
- .then((r) => { Object.assign(copyRestore, r, { status: 'done', finishedAt: new Date().toISOString() }); })
454
- .catch((err) => {
455
- const message = err instanceof Error ? err.message : String(err);
456
- Object.assign(copyRestore, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
457
- logger.error(`Restore of input asset copies failed: ${message}`);
458
- });
459
- return { accepted: true, message: 'Restore of input asset copies started; poll getStatus().copyRestore.' };
379
+ const conflict = copyWalkConflict();
380
+ if (conflict)
381
+ return (0, errors_1.rejectInvalid)(req, 'restoreInputAssetCopies', conflict);
382
+ return restoreRun.start(() => ({
383
+ run: (ctl) => (0, input_asset_copies_1.restoreInputAssetCopies)({ ...range, onProgress: ctl.progress, shouldStop: ctl.shouldStop }),
384
+ answer: { accepted: true, message: 'Restore of input asset copies started; poll getStatus().copyRestore.' },
385
+ }));
386
+ });
387
+ // cancelMaintenance: asks a running backfill or walk of this process to stop at its next window,
388
+ // page or batch. What it wrote so far stays; a new start begins again at its first slot or key.
389
+ srv.on('cancelMaintenance', async (req) => {
390
+ const name = String(req.data?.run ?? '');
391
+ const run = Object.hasOwn(CANCELLABLE, name) ? CANCELLABLE[name] : null;
392
+ if (!run)
393
+ return (0, errors_1.rejectInvalid)(req, 'cancelMaintenance', `run must be one of ${Object.keys(CANCELLABLE).join(', ')}`, 'run');
394
+ if (!run.cancel())
395
+ return { accepted: false, message: `${run.label} is not running in this process.` };
396
+ return { accepted: true, message: `${run.label} stops at its next step; poll getStatus().${name}.` };
460
397
  });
461
398
  // importUtxoSet: one-off snapshot import that anchors crawler.utxoSet.
462
399
  // Runs detached. Progress is in getStatus().utxoSet.
@@ -465,46 +402,52 @@ module.exports = (srv) => {
465
402
  if (data.source === 'aggregates') {
466
403
  if ((0, crawler_1.isCrawlerRunning)())
467
404
  return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'Crawler is running in this process. Run pauseCrawler first');
468
- if (utxoSetImportInFlight)
405
+ if (utxoSetRun.isBusy())
469
406
  return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'A UTxO set import is already running');
470
- return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
407
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => utxoSetRun.start(async () => {
471
408
  const cursor = await (0, sync_state_1.readCursor)(db);
472
409
  const { anchorSlot, anchorHash } = cursor?.utxoSet ?? {};
473
410
  if (anchorSlot == null || !anchorHash)
474
411
  throw new errors_1.TransactionValidationError('No imported UTxO set to rebuild the sums from. Run importUtxoSet first.');
475
- utxoSetImportInFlight = (0, utxo_set_import_1.rebuildUtxoSetAggregates)({ indexer: (0, server_1.getCardanoIndexer)() })
476
- .then((r) => logger.info(`UTxO set sums rebuilt: ${r.utxos} rows at ${r.anchor.slot}/${r.anchor.hash}`))
477
- .catch((err) => logger.error(`UTxO set aggregate rebuild failed: ${err instanceof Error ? err.message : String(err)}`))
478
- .finally(() => { utxoSetImportInFlight = null; });
479
412
  return {
480
- accepted: true,
481
- anchorSlot: String(anchorSlot),
482
- anchorHash,
483
- message: 'UTxO set sums are rebuilt from the imported rows; poll getStatus().utxoSet, then resumeCrawler.',
413
+ label: 'UTxO set aggregate rebuild',
414
+ run: async () => {
415
+ const r = await (0, utxo_set_import_1.rebuildUtxoSetAggregates)({ indexer: (0, server_1.getCardanoIndexer)() });
416
+ logger.info(`UTxO set sums rebuilt: ${r.utxos} rows at ${r.anchor.slot}/${r.anchor.hash}`);
417
+ },
418
+ answer: {
419
+ accepted: true,
420
+ anchorSlot: String(anchorSlot),
421
+ anchorHash,
422
+ message: 'UTxO set sums are rebuilt from the imported rows; poll getStatus().utxoSet, then resumeCrawler.',
423
+ },
484
424
  };
485
- });
425
+ }));
486
426
  }
487
427
  if (data.source === 'scripts') {
488
428
  if ((0, crawler_1.isCrawlerRunning)())
489
429
  return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'Crawler is running in this process. Run pauseCrawler first');
490
- if (utxoSetImportInFlight)
430
+ if (utxoSetRun.isBusy())
491
431
  return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'A UTxO set import is already running');
492
- return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
432
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => utxoSetRun.start(async () => {
493
433
  const cursor = await (0, sync_state_1.readCursor)(db);
494
434
  const { anchorSlot, anchorHash } = cursor?.utxoSet ?? {};
495
435
  if (anchorSlot == null || !anchorHash)
496
436
  throw new errors_1.TransactionValidationError('No imported UTxO set to fill. Run importUtxoSet first.');
497
- utxoSetImportInFlight = (0, utxo_set_import_1.refreshUtxoSetReferenceScripts)({ filePath: data.filePath, client: (0, server_1.getCardanoClient)() })
498
- .then((r) => logger.info(`UTxO set reference scripts filled: ${r.updated} of ${r.candidates} rows`))
499
- .catch((err) => logger.error(`UTxO set reference-script fill failed: ${err instanceof Error ? err.message : String(err)}`))
500
- .finally(() => { utxoSetImportInFlight = null; });
501
437
  return {
502
- accepted: true,
503
- anchorSlot: String(anchorSlot),
504
- anchorHash,
505
- message: `Reference-script columns of the UTxO set are being filled (${data.filePath ? 'from the dump' : 'from the node'}); watch the log, then resumeCrawler.`,
438
+ label: 'UTxO set reference-script fill',
439
+ run: async () => {
440
+ const r = await (0, utxo_set_import_1.refreshUtxoSetReferenceScripts)({ filePath: data.filePath, client: (0, server_1.getCardanoClient)() });
441
+ logger.info(`UTxO set reference scripts filled: ${r.updated} of ${r.candidates} rows`);
442
+ },
443
+ answer: {
444
+ accepted: true,
445
+ anchorSlot: String(anchorSlot),
446
+ anchorHash,
447
+ message: `Reference-script columns of the UTxO set are being filled (${data.filePath ? 'from the dump' : 'from the node'}); watch the log, then resumeCrawler.`,
448
+ },
506
449
  };
507
- });
450
+ }));
508
451
  }
509
452
  // the model rejects an unknown source and a negative anchorSlot
510
453
  const source = data.source;
@@ -521,9 +464,9 @@ module.exports = (srv) => {
521
464
  }
522
465
  if ((0, crawler_1.isCrawlerRunning)())
523
466
  return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'Crawler is running in this process. Run pauseCrawler first');
524
- if (utxoSetImportInFlight)
467
+ if (utxoSetRun.isBusy())
525
468
  return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'A UTxO set import is already running');
526
- return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
469
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => utxoSetRun.start(async () => {
527
470
  const cursor = await (0, sync_state_1.readCursor)(db);
528
471
  if (!cursor)
529
472
  throw new errors_1.TransactionValidationError('No crawler cursor yet. Start the crawler once before importing.');
@@ -537,22 +480,24 @@ module.exports = (srv) => {
537
480
  if (cursor.lastSlot > anchor.slot) {
538
481
  throw new errors_1.TransactionValidationError(`Crawler cursor (slot ${cursor.lastSlot}) is past the anchor (slot ${anchor.slot}). Dump the set at or after the cursor.`);
539
482
  }
540
- utxoSetImportInFlight = (0, utxo_set_import_1.importUtxoSet)({
541
- source, filePath: data.filePath, anchor,
542
- client: (0, server_1.getCardanoClient)(), indexer: (0, server_1.getCardanoIndexer)(),
543
- onProgress: (n) => { if (n % 100_000 === 0)
544
- logger.info(`UTxO set import: ${n} entries`); },
545
- })
546
- .then((r) => logger.info(`UTxO set import done: ${r.utxos} entries at ${r.anchor.slot}/${r.anchor.hash}`))
547
- .catch((err) => logger.error(`UTxO set import failed: ${err instanceof Error ? err.message : String(err)}`))
548
- .finally(() => { utxoSetImportInFlight = null; });
549
483
  return {
550
- accepted: true,
551
- anchorSlot: String(anchor.slot),
552
- anchorHash: anchor.hash,
553
- message: `UTxO set import started (source=${source}); poll getStatus().utxoSet, then resumeCrawler.`,
484
+ run: async () => {
485
+ const r = await (0, utxo_set_import_1.importUtxoSet)({
486
+ source, filePath: data.filePath, anchor,
487
+ client: (0, server_1.getCardanoClient)(), indexer: (0, server_1.getCardanoIndexer)(),
488
+ onProgress: (n) => { if (n % 100_000 === 0)
489
+ logger.info(`UTxO set import: ${n} entries`); },
490
+ });
491
+ logger.info(`UTxO set import done: ${r.utxos} entries at ${r.anchor.slot}/${r.anchor.hash}`);
492
+ },
493
+ answer: {
494
+ accepted: true,
495
+ anchorSlot: String(anchor.slot),
496
+ anchorHash: anchor.hash,
497
+ message: `UTxO set import started (source=${source}); poll getStatus().utxoSet, then resumeCrawler.`,
498
+ },
554
499
  };
555
- });
500
+ }));
556
501
  });
557
502
  // pauseCrawler: stops the stream. The cursor is kept, so resume continues from it.
558
503
  srv.on('pauseCrawler', async (req) => {