@odatano/core 2.0.0-rc.3 → 2.0.0-rc.31

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 (162) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +294 -7
  8. package/@cds-models/CardanoODataService/index.js +33 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +52 -19
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +18 -0
  14. package/@cds-models/index.js +3 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +677 -13
  19. package/db/types.cds +27 -0
  20. package/package.json +182 -173
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +11 -10
  24. package/src/index.js +28 -14
  25. package/src/plugin.js +39 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +49 -160
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +356 -217
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +548 -197
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +78 -205
  39. package/srv/blockchain/cardano-client.js +186 -242
  40. package/srv/blockchain/cardano-indexer.d.ts +302 -242
  41. package/srv/blockchain/cardano-indexer.js +1193 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +43 -81
  43. package/srv/blockchain/cardano-tx-builder.js +177 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  68. package/srv/blockchain/signing/signature-verifier.js +13 -54
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +115 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +651 -287
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +48 -24
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +56 -1
  102. package/srv/cardano-service.js +52 -113
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +55 -173
  105. package/srv/cardano-tx-service.cds +439 -364
  106. package/srv/cardano-tx-service.js +305 -209
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/parse.js +13 -1
  110. package/srv/server.d.ts +28 -86
  111. package/srv/server.js +130 -135
  112. package/srv/utils/agent-grants-config.d.ts +37 -0
  113. package/srv/utils/agent-grants-config.js +138 -0
  114. package/srv/utils/agent-grants.d.ts +262 -0
  115. package/srv/utils/agent-grants.js +922 -0
  116. package/srv/utils/agent-token-auth.d.ts +16 -0
  117. package/srv/utils/agent-token-auth.js +78 -0
  118. package/srv/utils/backend-request-handler.d.ts +2 -16
  119. package/srv/utils/backend-request-handler.js +3 -18
  120. package/srv/utils/collections.d.ts +4 -8
  121. package/srv/utils/collections.js +4 -8
  122. package/srv/utils/const.d.ts +30 -67
  123. package/srv/utils/const.js +32 -72
  124. package/srv/utils/crypto.d.ts +3 -12
  125. package/srv/utils/crypto.js +5 -18
  126. package/srv/utils/db-indexes.d.ts +25 -0
  127. package/srv/utils/db-indexes.js +94 -0
  128. package/srv/utils/db-sanitize.d.ts +27 -0
  129. package/srv/utils/db-sanitize.js +85 -0
  130. package/srv/utils/epoch-slots.d.ts +13 -0
  131. package/srv/utils/epoch-slots.js +25 -0
  132. package/srv/utils/error-codes.d.ts +20 -73
  133. package/srv/utils/error-codes.js +19 -70
  134. package/srv/utils/errors.d.ts +50 -177
  135. package/srv/utils/errors.js +94 -218
  136. package/srv/utils/liveness.d.ts +16 -0
  137. package/srv/utils/liveness.js +40 -0
  138. package/srv/utils/mappers.d.ts +128 -214
  139. package/srv/utils/mappers.js +354 -299
  140. package/srv/utils/network-context.js +2 -11
  141. package/srv/utils/pg-inline-json.d.ts +8 -0
  142. package/srv/utils/pg-inline-json.js +62 -0
  143. package/srv/utils/pg-order-nulls.d.ts +14 -0
  144. package/srv/utils/pg-order-nulls.js +56 -0
  145. package/srv/utils/plutus-placeholders.d.ts +23 -16
  146. package/srv/utils/plutus-placeholders.js +63 -27
  147. package/srv/utils/rate-limiter.d.ts +46 -0
  148. package/srv/utils/rate-limiter.js +116 -0
  149. package/srv/utils/service-events.d.ts +2 -22
  150. package/srv/utils/service-events.js +3 -23
  151. package/srv/utils/signing-helper.d.ts +3 -18
  152. package/srv/utils/signing-helper.js +10 -32
  153. package/srv/utils/tx-build-helper.d.ts +26 -92
  154. package/srv/utils/tx-build-helper.js +68 -123
  155. package/srv/utils/tx-request-parsers.d.ts +107 -21
  156. package/srv/utils/tx-request-parsers.js +433 -34
  157. package/srv/utils/tx-utils.d.ts +4 -23
  158. package/srv/utils/tx-utils.js +12 -41
  159. package/srv/utils/types.d.ts +238 -169
  160. package/srv/utils/types.js +2 -6
  161. package/srv/utils/validators.d.ts +24 -90
  162. package/srv/utils/validators.js +50 -147
@@ -1,14 +1,6 @@
1
1
  /**
2
- * Crawler event hooks (v2.1).
3
- *
4
- * Small listener registry that lets other subsystems (currently the wallet-worker
5
- * confirmation tracker) observe crawler progress without the crawler importing
6
- * them (dependency direction stays crawler ← consumer). The crawler emits:
7
- * - `blockIndexed` after each successfully persisted block (with its tx hashes), and
8
- * - `reorg` after a completed rollback (with the fork slot).
9
- *
10
- * Listener failures are logged and swallowed — a broken consumer must never
11
- * stop the crawler.
2
+ * Listener registry for crawler progress: `blockIndexed` after each persisted block,
3
+ * `reorg` after a completed rollback. Listener failures are logged and swallowed.
12
4
  */
13
5
  export interface BlockIndexedEvent {
14
6
  hash: string;
@@ -24,10 +16,7 @@ export interface ReorgEvent {
24
16
  forkSlot: number;
25
17
  /** How many blocks the rollback removed (0 when the fork was already the tip). */
26
18
  blocksRolledBack?: number;
27
- /**
28
- * Block height of the fork point, when known. Listeners tracking confirmation
29
- * depth must clamp their tip to this — the pre-fork tip height no longer exists.
30
- */
19
+ /** Block height of the fork point, when known; depth trackers must clamp their tip to it. */
31
20
  forkHeight: number | null;
32
21
  }
33
22
  export type BlockIndexedListener = (event: BlockIndexedEvent) => void;
@@ -1,6 +1,11 @@
1
1
  import type { CardanoClient } from '../cardano-client';
2
2
  import type { CardanoIndexer } from '../cardano-indexer';
3
3
  import { CardanoCrawler, type CrawlerConfig } from './crawler';
4
+ /**
5
+ * Delay before the next standby start attempt: 5 s for a healthy standby; after a local
6
+ * error halt, exponential backoff (5 s … 5 min) driven by the shared cursor's error streak.
7
+ */
8
+ export declare function standbyDelayMs(consecutiveErrors: number): number;
4
9
  export interface StartCrawlerDeps {
5
10
  client: CardanoClient;
6
11
  indexer: CardanoIndexer;
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.standbyDelayMs = standbyDelayMs;
6
7
  exports.startCrawler = startCrawler;
7
8
  exports.stopCrawler = stopCrawler;
8
9
  exports.isCrawlerRunning = isCrawlerRunning;
@@ -14,9 +15,8 @@ const crawler_1 = require("./crawler");
14
15
  const sync_state_1 = require("./sync-state");
15
16
  const logger = cds_1.default.log('CardanoCrawler');
16
17
  /**
17
- * Module-level singleton lifecycle for the chain crawler. Mirrors NIGHTGATE's
18
- * srv/crawler/index.ts: one active crawler per process, started fire-and-forget from
19
- * the server's `served` hook and controlled (pause/resume/status) via the indexer service.
18
+ * Process-wide crawler singleton: started fire-and-forget from the `served` hook,
19
+ * controlled (pause/resume/status) via the indexer service.
20
20
  */
21
21
  let active = null;
22
22
  let lifecycleQueue = Promise.resolve();
@@ -24,6 +24,16 @@ let standbyDeps = null;
24
24
  let standbyTimer = null;
25
25
  let standbyGeneration = 0;
26
26
  const STANDBY_RETRY_MS = 5_000;
27
+ const STANDBY_MAX_BACKOFF_MS = 5 * 60_000;
28
+ /**
29
+ * Delay before the next standby start attempt: 5 s for a healthy standby; after a local
30
+ * error halt, exponential backoff (5 s … 5 min) driven by the shared cursor's error streak.
31
+ */
32
+ function standbyDelayMs(consecutiveErrors) {
33
+ if (!Number.isFinite(consecutiveErrors) || consecutiveErrors <= 1)
34
+ return STANDBY_RETRY_MS;
35
+ return Math.min(STANDBY_MAX_BACKOFF_MS, STANDBY_RETRY_MS * 2 ** Math.min(consecutiveErrors - 1, 10));
36
+ }
27
37
  /**
28
38
  * Start the crawler (idempotent — a no-op if one is already running). Fire-and-forget:
29
39
  * returns once the ingest pipeline is launched, not when catch-up completes.
@@ -113,7 +123,7 @@ function serializeLifecycle(operation) {
113
123
  return result;
114
124
  }
115
125
  /** Keep non-leader instances warm so an expired/released lease fails over automatically. */
116
- function scheduleStandby(generation) {
126
+ function scheduleStandby(generation, delayMs = STANDBY_RETRY_MS) {
117
127
  if (standbyTimer || !standbyDeps)
118
128
  return;
119
129
  standbyTimer = setTimeout(() => {
@@ -123,13 +133,31 @@ function scheduleStandby(generation) {
123
133
  const deps = standbyDeps;
124
134
  if (!deps)
125
135
  return;
136
+ // Local evidence only, taken BEFORE the attempt replaces `active`.
137
+ const failedHere = active?.haltedWithError() ?? false;
126
138
  void startCrawlerAttempt(deps, false, generation)
127
139
  .catch((err) => logger.error('standby lease attempt failed:', err))
128
- .finally(() => {
140
+ .then(() => nextStandbyDelay(failedHere))
141
+ .then((delay) => {
129
142
  if (generation === standbyGeneration)
130
- scheduleStandby(generation);
143
+ scheduleStandby(generation, delay);
131
144
  });
132
- }, STANDBY_RETRY_MS);
145
+ }, delayMs);
133
146
  standbyTimer.unref?.();
134
147
  }
148
+ /**
149
+ * Backoff from the shared cursor's error streak after a local failure; the base delay
150
+ * otherwise — a healthy tick costs no DB round-trip.
151
+ */
152
+ async function nextStandbyDelay(failedHere) {
153
+ if (!failedHere)
154
+ return STANDBY_RETRY_MS;
155
+ try {
156
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
157
+ return standbyDelayMs(cursor?.consecutiveErrors ?? 0);
158
+ }
159
+ catch {
160
+ return STANDBY_RETRY_MS;
161
+ }
162
+ }
135
163
  //# sourceMappingURL=index.js.map
@@ -1,14 +1,8 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
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.
3
+ * Cursor helpers for `CardanoSyncState`, the singleton row recording how far the crawler
4
+ * has indexed. Integer64/Decimal columns come back from the DB as strings, so every read
5
+ * coerces numeric fields; callers get a numeric `SyncCursor`.
12
6
  */
13
7
  export declare const SINGLETON_ID = "SINGLETON";
14
8
  /** Circuit-breaker threshold: pause crawling after this many back-to-back failures. */
@@ -22,6 +16,17 @@ export interface CrawlPoint {
22
16
  hash: string;
23
17
  height?: number;
24
18
  }
19
+ export type UtxoSetStatusValue = 'none' | 'importing' | 'active' | 'invalid';
20
+ /** Crawler-fed ledger state (crawler.utxoSet): the anchor the imported UTxO set describes. */
21
+ export interface UtxoSetState {
22
+ status: UtxoSetStatusValue;
23
+ anchorSlot: number | null;
24
+ anchorHash: string | null;
25
+ importedAt: string | null;
26
+ /** Slot of the last block applied to the ledger tables (null = nothing applied since the import). */
27
+ appliedSlot: number | null;
28
+ error: string | null;
29
+ }
25
30
  /** Normalized, number-typed view of the cursor row (numeric fields already coerced). */
26
31
  export interface SyncCursor {
27
32
  network: string | null;
@@ -37,12 +42,11 @@ export interface SyncCursor {
37
42
  desiredRunning: boolean;
38
43
  leaseOwner: string | null;
39
44
  leaseUntil: string | null;
45
+ utxoSet: UtxoSetState;
40
46
  }
41
47
  /**
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.
48
+ * Ensure the singleton cursor row exists and return it; a fresh DB gets the configured
49
+ * start point and status 'stopped'.
46
50
  */
47
51
  export declare function ensureSyncStateSingleton(db: CapTransaction, network: string, start?: CrawlPoint): Promise<SyncCursor>;
48
52
  /** Read the current cursor, or null if it has not been initialized yet. */
@@ -50,9 +54,8 @@ export declare function readCursor(db: CapTransaction): Promise<SyncCursor | nul
50
54
  /** Whether the shared lease currently represents a live cluster-wide crawler. */
51
55
  export declare function isCrawlerLeaseActive(cursor: SyncCursor | null, now?: Date): boolean;
52
56
  /**
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.
57
+ * Acquire an expired/unowned lease with compare-and-swap semantics. Verified by a read-back
58
+ * SELECT: affected-row return shapes differ between SQLite and HANA.
56
59
  */
57
60
  export declare function tryAcquireCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
58
61
  /**
@@ -61,26 +64,41 @@ export declare function tryAcquireCrawlerLease(db: CapTransaction, owner: string
61
64
  */
62
65
  export declare function renewCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
63
66
  /**
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.
67
+ * Release only the caller's lease. `pauseCluster` clears `desiredRunning`, which no restart
68
+ * undoes — reserve it for failures a restart cannot fix (misconfiguration, no resume point).
71
69
  */
72
70
  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. */
71
+ /**
72
+ * Persist the pause/resume intent shared by every instance. Resuming clears the error
73
+ * streak so the standby backoff restarts at its base.
74
+ */
74
75
  export declare function setCrawlerDesiredRunning(db: CapTransaction, desiredRunning: boolean): Promise<void>;
75
76
  /**
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).
77
+ * Latch the cluster off because of a poison block. Deliberately not lease-scoped: the poison
78
+ * is a property of the block, not of the instance. Only resumeCrawler brings the crawler back.
79
+ */
80
+ export declare function latchPoisonBlock(db: CapTransaction, message: string): Promise<void>;
81
+ /**
82
+ * Advance the cursor to a freshly indexed block, clear the error streak and optionally
83
+ * record the latest known tip. Pass status 'synced' when the block is at the tip.
84
+ * With `leaseOwner` the same UPDATE renews and fences the crawler lease (see renewCrawlerLease).
85
+ * @returns false when the lease is no longer held; the caller must roll back
79
86
  */
80
87
  export declare function advanceCursor(db: CapTransaction, block: CrawlPoint, tip?: {
81
88
  slot: number;
82
89
  height?: number;
83
- }, status?: CrawlSyncStatusValue): Promise<void>;
90
+ }, status?: CrawlSyncStatusValue,
91
+ /** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
92
+ extra?: Record<string, unknown>, leaseOwner?: string, now?: Date, ttlMs?: number): Promise<boolean>;
93
+ /**
94
+ * Lease for the UTxO set import, on the crawler's lease columns: a crawler start on any
95
+ * instance and a second import are refused while it is held. Does not require `desiredRunning`.
96
+ */
97
+ export declare function tryAcquireImportLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
98
+ export declare function renewImportLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
99
+ export declare function releaseImportLease(db: CapTransaction, owner: string): Promise<void>;
100
+ /** Persist the crawler-fed ledger state's anchor / validity (crawler.utxoSet). */
101
+ export declare function setUtxoSetState(db: CapTransaction, state: Partial<UtxoSetState>): Promise<void>;
84
102
  /** Reset the cursor to a rollback point (used by reorg handling). */
85
103
  export declare function resetCursorTo(db: CapTransaction, point: CrawlPoint): Promise<void>;
86
104
  /** Set the crawler status (e.g. 'synced' when caught up, 'stopped' on shutdown). */
@@ -11,7 +11,12 @@ 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;
16
21
  exports.setSyncStatus = setSyncStatus;
17
22
  exports.recordError = recordError;
@@ -21,26 +26,16 @@ const errors_1 = require("../../utils/errors");
21
26
  const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
22
27
  const logger = cds_1.default.log('CardanoCrawler');
23
28
  /**
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.
29
+ * Cursor helpers for `CardanoSyncState`, the singleton row recording how far the crawler
30
+ * has indexed. Integer64/Decimal columns come back from the DB as strings, so every read
31
+ * coerces numeric fields; callers get a numeric `SyncCursor`.
33
32
  */
34
33
  exports.SINGLETON_ID = 'SINGLETON';
35
34
  /** Circuit-breaker threshold: pause crawling after this many back-to-back failures. */
36
35
  exports.MAX_CONSECUTIVE_ERRORS = 10;
37
36
  /** A short, renewable DB lease prevents two app instances from advancing one cursor. */
38
37
  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
- */
38
+ /** Coerce a numeric-as-string (or number/bigint/null) into a JS number. */
44
39
  function optionalNum(v) {
45
40
  if (v === null || v === undefined || v === '')
46
41
  return null;
@@ -57,6 +52,16 @@ function timestamp(v) {
57
52
  return v.toISOString();
58
53
  return String(v);
59
54
  }
55
+ /**
56
+ * Import-lease read-back: ownership and deadline only. Unlike the crawler lease it does not
57
+ * require `desiredRunning`, which is cleared while an import runs.
58
+ */
59
+ function importLeaseHeld(cursor, owner, expectedMs) {
60
+ if (!cursor || cursor.leaseOwner !== owner || !cursor.leaseUntil)
61
+ return false;
62
+ const actualMs = Date.parse(cursor.leaseUntil);
63
+ return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
64
+ }
60
65
  function leaseDeadlineReached(cursor, owner, expectedMs) {
61
66
  if (cursor?.desiredRunning !== true || cursor.leaseOwner !== owner || !cursor.leaseUntil)
62
67
  return false;
@@ -81,13 +86,19 @@ function toCursor(row) {
81
86
  desiredRunning: row.desiredRunning !== false,
82
87
  leaseOwner: row.leaseOwner ?? null,
83
88
  leaseUntil: timestamp(row.leaseUntil),
89
+ utxoSet: {
90
+ status: (row.utxoSetStatus ?? 'none'),
91
+ anchorSlot: optionalNum(row.utxoAnchorSlot),
92
+ anchorHash: row.utxoAnchorHash ?? null,
93
+ importedAt: timestamp(row.utxoSetImportedAt),
94
+ appliedSlot: optionalNum(row.utxoAppliedSlot),
95
+ error: row.utxoSetError ?? null,
96
+ },
84
97
  };
85
98
  }
86
99
  /**
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.
100
+ * Ensure the singleton cursor row exists and return it; a fresh DB gets the configured
101
+ * start point and status 'stopped'.
91
102
  */
92
103
  async function ensureSyncStateSingleton(db, network, start) {
93
104
  const existing = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
@@ -113,6 +124,12 @@ async function ensureSyncStateSingleton(db, network, start) {
113
124
  desiredRunning: true,
114
125
  leaseOwner: null,
115
126
  leaseUntil: null,
127
+ utxoSetStatus: 'none',
128
+ utxoAnchorSlot: null,
129
+ utxoAnchorHash: null,
130
+ utxoSetImportedAt: null,
131
+ utxoAppliedSlot: null,
132
+ utxoSetError: null,
116
133
  };
117
134
  await db.run(INSERT.into(cardano_1.CardanoSyncState).entries(row));
118
135
  logger.info(`Sync cursor initialized (network=${network}, start=${start ? `${start.slot}/${start.hash}` : 'none'})`);
@@ -131,9 +148,8 @@ function isCrawlerLeaseActive(cursor, now = new Date()) {
131
148
  return Number.isFinite(deadline) && deadline > now.getTime();
132
149
  }
133
150
  /**
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.
151
+ * Acquire an expired/unowned lease with compare-and-swap semantics. Verified by a read-back
152
+ * SELECT: affected-row return shapes differ between SQLite and HANA.
137
153
  */
138
154
  async function tryAcquireCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
139
155
  const raw = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
@@ -145,15 +161,9 @@ async function tryAcquireCrawlerLease(db, owner, now = new Date(), ttlMs = expor
145
161
  const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
146
162
  if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
147
163
  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.
164
+ // CAS on the observed OWNER only, verified by read-back. leaseUntil is deliberately not
165
+ // compared: timestamp normalization on some adapters would make that CAS never match again
166
+ // after a leader crash. A concurrently renewing old owner is fenced by its next renew.
157
167
  const where = {
158
168
  ID: exports.SINGLETON_ID,
159
169
  leaseOwner: raw.leaseOwner ?? null,
@@ -181,13 +191,8 @@ async function renewCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CR
181
191
  return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
182
192
  }
183
193
  /**
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.
194
+ * Release only the caller's lease. `pauseCluster` clears `desiredRunning`, which no restart
195
+ * undoes — reserve it for failures a restart cannot fix (misconfiguration, no resume point).
191
196
  */
192
197
  async function releaseCrawlerLease(db, owner, status, pauseCluster = false) {
193
198
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
@@ -197,19 +202,39 @@ async function releaseCrawlerLease(db, owner, status, pauseCluster = false) {
197
202
  ...(pauseCluster ? { desiredRunning: false } : {}),
198
203
  }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
199
204
  }
200
- /** Persist the pause/resume intent shared by every app instance. */
205
+ /**
206
+ * Persist the pause/resume intent shared by every instance. Resuming clears the error
207
+ * streak so the standby backoff restarts at its base.
208
+ */
201
209
  async function setCrawlerDesiredRunning(db, desiredRunning) {
202
210
  const set = { desiredRunning };
203
- if (!desiredRunning)
211
+ if (desiredRunning)
212
+ set.consecutiveErrors = 0;
213
+ else
204
214
  set.syncStatus = 'stopped';
205
215
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
206
216
  }
207
217
  /**
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).
218
+ * Latch the cluster off because of a poison block. Deliberately not lease-scoped: the poison
219
+ * is a property of the block, not of the instance. Only resumeCrawler brings the crawler back.
211
220
  */
212
- async function advanceCursor(db, block, tip, status = 'syncing') {
221
+ async function latchPoisonBlock(db, message) {
222
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
223
+ desiredRunning: false,
224
+ syncStatus: 'error',
225
+ lastError: message.slice(0, 500),
226
+ lastErrorAt: new Date().toISOString(),
227
+ }).where({ ID: exports.SINGLETON_ID }));
228
+ }
229
+ /**
230
+ * Advance the cursor to a freshly indexed block, clear the error streak and optionally
231
+ * record the latest known tip. Pass status 'synced' when the block is at the tip.
232
+ * With `leaseOwner` the same UPDATE renews and fences the crawler lease (see renewCrawlerLease).
233
+ * @returns false when the lease is no longer held; the caller must roll back
234
+ */
235
+ async function advanceCursor(db, block, tip, status = 'syncing',
236
+ /** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
237
+ extra, leaseOwner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
213
238
  const set = {
214
239
  lastSlot: block.slot,
215
240
  lastBlockHash: block.hash,
@@ -218,12 +243,72 @@ async function advanceCursor(db, block, tip, status = 'syncing') {
218
243
  syncStatus: status,
219
244
  consecutiveErrors: 0,
220
245
  lastError: null,
246
+ ...(extra ?? {}),
221
247
  };
222
248
  if (tip) {
223
249
  set.tipSlot = tip.slot;
224
250
  if (tip.height !== undefined)
225
251
  set.tipHeight = tip.height;
226
252
  }
253
+ if (!leaseOwner) {
254
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
255
+ return true;
256
+ }
257
+ set.leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
258
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({
259
+ ID: exports.SINGLETON_ID,
260
+ leaseOwner,
261
+ desiredRunning: true,
262
+ }));
263
+ const verified = await readCursor(db);
264
+ return leaseDeadlineReached(verified, leaseOwner, now.getTime() + ttlMs);
265
+ }
266
+ /**
267
+ * Lease for the UTxO set import, on the crawler's lease columns: a crawler start on any
268
+ * instance and a second import are refused while it is held. Does not require `desiredRunning`.
269
+ */
270
+ async function tryAcquireImportLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
271
+ const raw = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
272
+ if (!raw)
273
+ return false;
274
+ const current = toCursor(raw);
275
+ const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
276
+ if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
277
+ return false;
278
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
279
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseOwner: owner, leaseUntil }).where({
280
+ ID: exports.SINGLETON_ID,
281
+ leaseOwner: raw.leaseOwner ?? null,
282
+ }));
283
+ const verified = await readCursor(db);
284
+ return importLeaseHeld(verified, owner, now.getTime() + ttlMs);
285
+ }
286
+ async function renewImportLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
287
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
288
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseUntil }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
289
+ const verified = await readCursor(db);
290
+ return importLeaseHeld(verified, owner, now.getTime() + ttlMs);
291
+ }
292
+ async function releaseImportLease(db, owner) {
293
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseOwner: null, leaseUntil: null }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
294
+ }
295
+ /** Persist the crawler-fed ledger state's anchor / validity (crawler.utxoSet). */
296
+ async function setUtxoSetState(db, state) {
297
+ const set = {};
298
+ if (state.status !== undefined)
299
+ set.utxoSetStatus = state.status;
300
+ if (state.anchorSlot !== undefined)
301
+ set.utxoAnchorSlot = state.anchorSlot;
302
+ if (state.anchorHash !== undefined)
303
+ set.utxoAnchorHash = state.anchorHash;
304
+ if (state.importedAt !== undefined)
305
+ set.utxoSetImportedAt = state.importedAt;
306
+ if (state.appliedSlot !== undefined)
307
+ set.utxoAppliedSlot = state.appliedSlot;
308
+ if (state.error !== undefined)
309
+ set.utxoSetError = state.error;
310
+ if (!Object.keys(set).length)
311
+ return;
227
312
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
228
313
  }
229
314
  /** Reset the cursor to a rollback point (used by reorg handling). */
@@ -0,0 +1,52 @@
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
+ /**
7
+ * Completes transactions the crawl already holds from a second chain-sync stream: input
8
+ * outpoints (spentTxHash / spentOutputIndex), the spent output's datum and reference-script
9
+ * hash, a missing input address, and the redeemers. Only empty input fields are filled; a
10
+ * transaction whose stored inputs do not line up with the stream is left as it is.
11
+ */
12
+ export declare class TransactionBackfillError extends Error {
13
+ constructor(message: string);
14
+ }
15
+ export interface TransactionBackfillProgress {
16
+ /** Slot of the last block handled. */
17
+ atSlot: number;
18
+ blocks: number;
19
+ transactions: number;
20
+ /** Input rows that got at least one field. */
21
+ inputs: number;
22
+ redeemers: number;
23
+ /** Transactions whose stored rows differed from the ledger view (order, inputs or outputs the ledger did not apply) and were rewritten. */
24
+ rewritten: number;
25
+ /** Transactions left as they are: stored inputs differ from the stream. */
26
+ skipped: number;
27
+ }
28
+ /** Resolves bare chain-sync inputs from the index (CardanoIndexer.resolveInputs). */
29
+ export interface InputResolver {
30
+ resolveInputs(tx: CapTransaction, txs: Transaction[], ledger?: LedgerLookup): Promise<void>;
31
+ }
32
+ export interface TransactionBackfillOptions {
33
+ client: CardanoClient;
34
+ indexer: InputResolver;
35
+ fromSlot: number;
36
+ toSlot: number;
37
+ batchBlocks?: number;
38
+ onProgress?: (p: TransactionBackfillProgress) => void;
39
+ }
40
+ export interface TransactionBackfillResult extends TransactionBackfillProgress {
41
+ fromSlot: number;
42
+ toSlot: number;
43
+ intersection: ChainPoint | 'origin';
44
+ }
45
+ /**
46
+ * One UPDATE per chunk: the fills travel as a JSON array and are joined on (txSeq, inputIndex).
47
+ * COALESCE keeps any value that is already there. Postgres and SQLite; other databases get one
48
+ * UPDATE per row.
49
+ */
50
+ export declare function inputFillStatement(kind: string): string | null;
51
+ export declare function backfillTransactions(opts: TransactionBackfillOptions): Promise<TransactionBackfillResult>;
52
+ //# sourceMappingURL=transaction-backfill.d.ts.map