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

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 (208) 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 +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -7,7 +7,8 @@ exports.runWithoutAmbientTx = exports.WALLET_JOB_KINDS = exports.JOB_ERROR_CODES
7
7
  exports.dedupKeyFor = dedupKeyFor;
8
8
  exports.insertJob = insertJob;
9
9
  exports.getJobById = getJobById;
10
- exports.findDueJobs = findDueJobs;
10
+ exports.findNextDueJob = findNextDueJob;
11
+ exports.countPendingJobs = countPendingJobs;
11
12
  exports.findSubmittedJobs = findSubmittedJobs;
12
13
  exports.walletHasActiveJob = walletHasActiveJob;
13
14
  exports.findOrphanedSubmittingJob = findOrphanedSubmittingJob;
@@ -20,6 +21,7 @@ exports.recordConfirmationPoint = recordConfirmationPoint;
20
21
  exports.clearConfirmationPoint = clearConfirmationPoint;
21
22
  exports.markConfirmed = markConfirmed;
22
23
  exports.markFailed = markFailed;
24
+ exports.markFailedAfterSend = markFailedAfterSend;
23
25
  exports.markCancelled = markCancelled;
24
26
  exports.failOrphanedBuildingJobs = failOrphanedBuildingJobs;
25
27
  exports.recoverInterruptedJobs = recoverInterruptedJobs;
@@ -33,42 +35,15 @@ exports.bumpWalletStats = bumpWalletStats;
33
35
  const cds_1 = __importDefault(require("@sap/cds"));
34
36
  const node_crypto_1 = require("node:crypto");
35
37
  const cardano_1 = require("#cds-models/odatano/cardano");
38
+ const deep_json_1 = require("../../utils/deep-json");
39
+ const errors_1 = require("../../utils/errors");
40
+ const error_codes_1 = require("../../utils/error-codes");
36
41
  const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
37
42
  const logger = cds_1.default.log('CardanoWalletWorker');
38
- /**
39
- * Wallet-worker job store (v2.0).
40
- *
41
- * Persistence layer for `CardanoWalletJobs` + `CardanoWorkerWallets`. Ports the two
42
- * hard-won CAP lessons from NIGHTGATE's background-job runner:
43
- *
44
- * 1. `insertJob` runs on the CALLER's ambient transaction. CAP wraps every action
45
- * handler in its own root tx which may already hold the SQLite write lock; a
46
- * detached insert would deadlock against it. The row simply commits together
47
- * with the handler, and the worker's dispatch loop only sees it once visible.
48
- * 2. Every transition helper runs in its own short `db.tx()` (callers pass a fresh
49
- * tx or use `runWithoutAmbientTx`), so the single pooled SQLite connection is
50
- * never held across the seconds-to-minutes job execution.
51
- *
52
- * State machine (see WALLET_WORKER_DESIGN.md §5):
53
- * pending → building → submitting → submitted → confirmed
54
- * │ │ │ └────→ failed
55
- * │ │ └→ submitted (reconciled) | failed (proven absent)
56
- * │ └→ pending (transient retry) | failed
57
- * └→ cancelled
58
- *
59
- * `submitting` is the durable pre-submit state: the signed CBOR, its hash and the
60
- * fee are committed BEFORE the transaction can reach the network, so a process
61
- * death anywhere around `submitTransaction` leaves a row that can be reconciled
62
- * against the chain (or re-submitted verbatim) instead of a `building` row that
63
- * looks un-submitted. It is a NON-terminal state, so it keeps holding the
64
- * idempotency key — a caller retry gets the same job back rather than a rebuild.
65
- *
66
- * Transitions use guarded UPDATEs (WHERE includes the expected source status) with
67
- * a read-back verification — the wallet lease already fences concurrent workers,
68
- * this is defense in depth. NOTE (CAP 10): numeric columns read back as STRINGS;
69
- * all reads coerce via `num()` so callers get clean numbers.
70
- */
71
- /** Per-wallet DB lease TTL — same rationale as the crawler lease. */
43
+ // Job flow: pending, building, submitting, submitted, confirmed. Each state can also end in failed.
44
+ // submitting stores the signed CBOR before the network call. Transitions are conditional UPDATEs.
45
+ // insertJob uses the caller's tx, since a separate one would deadlock on the SQLite write lock.
46
+ /** Per-wallet DB lease TTL. */
72
47
  exports.WORKER_LEASE_TTL_MS = 15_000;
73
48
  exports.JOB_ERROR_CODES = {
74
49
  PROCESS_RESTART: 'PROCESS_RESTART',
@@ -78,7 +53,7 @@ exports.JOB_ERROR_CODES = {
78
53
  /** Reconciliation proved the tx is not on-chain and the node rejects it for good. */
79
54
  SUBMIT_REJECTED: 'SUBMIT_REJECTED',
80
55
  };
81
- exports.WALLET_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'submitSigned'];
56
+ exports.WALLET_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'payout', 'submitSigned'];
82
57
  function optionalNum(v) {
83
58
  if (v === null || v === undefined || v === '')
84
59
  return null;
@@ -128,6 +103,7 @@ function toWalletRow(row) {
128
103
  signerType: row.signerType,
129
104
  address: row.address ?? null,
130
105
  publicKeyHash: row.publicKeyHash ?? null,
106
+ requiresRole: row.requiresRole ?? null,
131
107
  enabled: row.enabled !== false,
132
108
  leaseOwner: row.leaseOwner ?? null,
133
109
  leaseUntil: timestamp(row.leaseUntil),
@@ -136,19 +112,10 @@ function toWalletRow(row) {
136
112
  jobsFailed: requiredNum(row.jobsFailed),
137
113
  };
138
114
  }
139
- // Moved to srv/utils/tx-utils.ts (shared with the sign-service's deadlock
140
- // guard); re-exported here so existing imports keep working.
115
+ // Re-exported from the shared tx-utils so existing imports keep working.
141
116
  var tx_utils_1 = require("../../utils/tx-utils");
142
117
  Object.defineProperty(exports, "runWithoutAmbientTx", { enumerable: true, get: function () { return tx_utils_1.runWithoutAmbientTx; } });
143
- /**
144
- * Recognize a unique-constraint rejection across the adapters we support —
145
- * SQLite (`SQLITE_CONSTRAINT_UNIQUE`, "UNIQUE constraint failed") and HANA
146
- * (code 301, "unique constraint violated").
147
- *
148
- * Errors it does not recognize are deliberately NOT treated as duplicates: they
149
- * propagate, and the caller's retry dedups through the read path. Swallowing an
150
- * unrelated insert failure as "already exists" would drop the job silently.
151
- */
118
+ /** Unique-constraint error on SQLite or HANA. Unknown errors must propagate, or the job is dropped silently. */
152
119
  function isUniqueViolation(err) {
153
120
  if (!err || typeof err !== 'object')
154
121
  return false;
@@ -160,60 +127,56 @@ function isUniqueViolation(err) {
160
127
  const text = String(message ?? '').toLowerCase();
161
128
  return text.includes('unique constraint') || text.includes('duplicate key');
162
129
  }
163
- /** The job that currently owns an idempotency key, or null when it is free. */
164
- /**
165
- * The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
166
- * submits. Two agents (two grants, two users) may both use `order-1` on the
167
- * same wallet: each must get its own job, never a "deduplicated" answer that
168
- * hands one the other's job id. A key from an owner-less caller (privileged
169
- * test context) stays as-is; an owned key becomes a hash of owner + key, which
170
- * fits the String(100) column whatever the owner id's length and never collides
171
- * with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
172
- */
130
+ /** Dedup key scoped to the submitting user. An owned key is hashed with an `o:` prefix, an owner-less key stays raw. */
173
131
  function dedupKeyFor(owner, idempotencyKey) {
174
132
  const scope = owner?.trim() ?? '';
175
133
  if (!scope)
176
134
  return idempotencyKey;
177
- return `o:${(0, node_crypto_1.createHash)('sha256').update(`${scope}${idempotencyKey}`).digest('hex').slice(0, 48)}`;
135
+ return `o:${(0, node_crypto_1.createHash)('sha256').update(`${scope}\0${idempotencyKey}`).digest('hex').slice(0, 48)}`;
136
+ }
137
+ /** Request JSON with sorted object keys, so two spellings of one request compare equal. */
138
+ function canonicalRequest(json) {
139
+ const sorted = (v) => {
140
+ if (Array.isArray(v))
141
+ return v.map(sorted);
142
+ if (v === null || typeof v !== 'object')
143
+ return v;
144
+ const entries = Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
145
+ return Object.fromEntries(entries.map(([key, value]) => [key, sorted(value)]));
146
+ };
147
+ if (json == null)
148
+ return '';
149
+ try {
150
+ return (0, deep_json_1.stringifyJson)(sorted((0, deep_json_1.parseJson)(json)));
151
+ }
152
+ catch {
153
+ return json;
154
+ }
155
+ }
156
+ /** The holder of the key answers a retry of the same request. Another request under the key is a 409. */
157
+ function answerFromHolder(holder, args) {
158
+ if (canonicalRequest(holder.request) !== canonicalRequest(args.request)) {
159
+ throw new errors_1.BackendError(`idempotencyKey "${args.idempotencyKey}" belongs to job ${holder.ID} with a different request`, 409, error_codes_1.ERROR_CODES.IDEMPOTENCY_KEY_CONFLICT, undefined, undefined, 'idempotencyKey');
160
+ }
161
+ return { jobId: holder.ID, status: holder.status, deduplicated: true };
178
162
  }
179
163
  async function readDedupHolder(db, walletId, kind, dedupKey) {
180
164
  const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ walletId, kind, dedupKey }));
181
165
  return row ? toJobRow(row) : null;
182
166
  }
183
- /**
184
- * Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
185
- * docs). Idempotency: an active-or-successful row with the same (walletId, kind,
186
- * idempotencyKey) is returned instead of creating a duplicate. `failed` AND
187
- * `cancelled` rows do NOT block a retry — both are terminal states in which the
188
- * intended work never reached the chain, so re-using the key must be able to
189
- * actually execute it (a cancelled job would otherwise burn its key forever).
190
- *
191
- * The deduplication is enforced by the `dedup` UNIQUE constraint on
192
- * (walletId, kind, dedupKey), NOT by the read below: two concurrent retries — two
193
- * app instances, or two HANA sessions — can both read "no such job" before either
194
- * commits, and would both insert. The read is only a fast path; the constraint is
195
- * what makes it correct, and the loser of the race returns the winner's job.
196
- *
197
- * `dedupKey` holds the caller's key while the job owns it and the job's own ID
198
- * otherwise, so keyless jobs never collide and terminated jobs free their key
199
- * (see releaseDedupClaim) — without depending on how a database treats NULLs
200
- * inside a unique index.
201
- */
167
+ /** Inserts a job, or returns the job that holds the dedup key. The UNIQUE constraint settles races. */
202
168
  async function insertJob(db, args) {
203
169
  const idempotencyKey = args.idempotencyKey ?? null;
204
170
  // The claim is per principal: the same key from another owner is another job.
205
171
  const claim = idempotencyKey ? dedupKeyFor(args.createdBy, idempotencyKey) : null;
206
172
  if (claim) {
207
- // Fast path: an owner exists (by construction it is non-terminal). Terminal
208
- // jobs release their claim, so they never show up here.
173
+ // A failed holder kept its key because its transaction may have been sent.
209
174
  const holder = await readDedupHolder(db, args.walletId, args.kind, claim);
210
175
  if (holder) {
211
- if (holder.status !== 'failed' && holder.status !== 'cancelled') {
212
- return { jobId: holder.ID, status: holder.status, deduplicated: true };
213
- }
214
- // Defensive: a terminal row that still owns the key would block retries
215
- // forever. Free it and continue with a fresh job.
216
- logger.warn(`Job ${holder.ID} is ${holder.status} but still held idempotency key "${idempotencyKey}" — releasing it`);
176
+ if (holder.status !== 'cancelled')
177
+ return answerFromHolder(holder, args);
178
+ // Defensive: a cancelled job frees its key, so this row would block retries forever.
179
+ logger.warn(`Job ${holder.ID} is cancelled but still held idempotency key "${idempotencyKey}", releasing it`);
217
180
  await releaseDedupClaim(db, holder.ID);
218
181
  }
219
182
  }
@@ -224,8 +187,7 @@ async function insertJob(db, args) {
224
187
  kind: args.kind,
225
188
  status: 'pending',
226
189
  idempotencyKey,
227
- // No key → the row's own ID: unique by construction, so keyless jobs never
228
- // contend for the constraint.
190
+ // No key → the row's own ID, so keyless jobs never contend for the constraint.
229
191
  dedupKey: claim ?? jobId,
230
192
  request: args.request,
231
193
  priority: args.priority ?? 100,
@@ -239,15 +201,14 @@ async function insertJob(db, args) {
239
201
  await db.run(INSERT.into(cardano_1.CardanoWalletJobs).entries(entry));
240
202
  }
241
203
  catch (err) {
242
- // Lost the race: another transaction committed the same key first. Its job is
243
- // the one and only job for this key — hand it back instead of paying twice.
204
+ // Lost the race to another transaction with the same key. Return its job.
244
205
  if (!claim || !isUniqueViolation(err))
245
206
  throw err;
246
207
  const winner = await readDedupHolder(db, args.walletId, args.kind, claim);
247
208
  if (!winner)
248
- throw err; // constraint fired for some other reason — do not mask it
249
- logger.info(`Concurrent submission for idempotency key "${idempotencyKey}" — returning job ${winner.ID}`);
250
- return { jobId: winner.ID, status: winner.status, deduplicated: true };
209
+ throw err; // constraint fired for another reason, do not mask it
210
+ logger.info(`Concurrent submission for idempotency key "${idempotencyKey}", returning job ${winner.ID}`);
211
+ return answerFromHolder(winner, args);
251
212
  }
252
213
  return { jobId, status: 'pending', deduplicated: false };
253
214
  }
@@ -256,16 +217,20 @@ async function getJobById(db, jobId) {
256
217
  const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ ID: jobId }));
257
218
  return row ? toJobRow(row) : null;
258
219
  }
259
- /**
260
- * All dispatchable jobs: status pending, ordered by (priority, createdAt).
261
- * `notBefore` gating happens in JS — queue depths are small and the JS filter
262
- * avoids adapter-specific NULL/OR predicate quirks.
263
- */
264
- async function findDueJobs(db, now = new Date()) {
265
- const rows = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).where({ status: 'pending' }).orderBy('priority', 'createdAt'));
266
- return (rows ?? [])
267
- .map(toJobRow)
268
- .filter(j => !j.notBefore || Date.parse(j.notBefore) <= now.getTime());
220
+ /** The next due pending job of a wallet by priority and age, or null. One row per call, whatever the queue holds. */
221
+ async function findNextDueJob(db, walletId, now = new Date()) {
222
+ const due = { notBefore: null, or: { notBefore: { '<=': now.toISOString() } } };
223
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).columns('ID', 'walletId', 'priority', 'createdAt')
224
+ .where({ walletId, status: 'pending', and: due })
225
+ .orderBy('priority', 'createdAt'));
226
+ if (!row)
227
+ return null;
228
+ return { ID: String(row.ID), walletId: String(row.walletId), priority: requiredNum(row.priority, 100), createdAt: timestamp(row.createdAt) };
229
+ }
230
+ /** Number of pending jobs, due or not. */
231
+ async function countPendingJobs(db) {
232
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).columns('count(*) as n').where({ status: 'pending' }));
233
+ return Number(row?.n ?? 0);
269
234
  }
270
235
  /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
271
236
  async function findSubmittedJobs(db) {
@@ -277,12 +242,7 @@ async function walletHasActiveJob(db, walletId) {
277
242
  const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ walletId, status: { in: ['building', 'submitting', 'submitted'] } }));
278
243
  return !!row;
279
244
  }
280
- /**
281
- * The oldest `submitting` row of a wallet whose lease no longer belongs to a live
282
- * executor — its submit outcome is unknown (crash, or a submit call that failed
283
- * ambiguously), so it needs chain reconciliation rather than a rebuild. Rows whose
284
- * wallet lease is still held are being worked on right now and are left alone.
285
- */
245
+ /** Oldest submitting row of a wallet without a live lease. Its submit outcome is unknown and needs a chain check. */
286
246
  async function findOrphanedSubmittingJob(db, walletId, now = new Date()) {
287
247
  const wallet = await readWallet(db, walletId);
288
248
  if (walletLeaseHeld(wallet, now))
@@ -291,30 +251,11 @@ async function findOrphanedSubmittingJob(db, walletId, now = new Date()) {
291
251
  return row ? toJobRow(row) : null;
292
252
  }
293
253
  // ---- Guarded transitions ---------------------------------------------------------
294
- /**
295
- * Give up a job's idempotency key by pointing `dedupKey` at the job's own ID
296
- * (unique by construction). Called on every terminal-but-unsuccessful transition,
297
- * which is what lets a caller re-use the key for a fresh attempt while the row
298
- * itself — including its `idempotencyKey` — stays intact for the audit trail.
299
- *
300
- * Not called for `confirmed`: a completed job keeps its key so a late duplicate
301
- * request resolves to it instead of paying again.
302
- */
254
+ /** Frees the idempotency key by pointing dedupKey at the job ID. */
303
255
  async function releaseDedupClaim(db, jobId) {
304
256
  await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs).set({ dedupKey: jobId }).where({ ID: jobId }));
305
257
  }
306
- /**
307
- * Move a job from one of `fromStatuses` to `set.status` and report whether THIS
308
- * call did it. The guard is the conditional UPDATE; the answer is its affected
309
- * row count (every @cap-js adapter returns a number). A second caller that
310
- * finds the row already in the target state gets `false`: the transition, the
311
- * wallet-stats bump and the terminal event belong to the first one only.
312
- * Two trackers confirming the same job used to count it twice.
313
- *
314
- * Fallback for an adapter that returns something that is not a count: read
315
- * the row back, and accept the target state only if the row was NOT already
316
- * there before this call (checked with a pre-read in that branch).
317
- */
258
+ /** True only when this call made the transition. That caller owns the stats bump and the terminal event. */
318
259
  async function guardedTransition(db, jobId, fromStatuses, set) {
319
260
  const affected = await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
320
261
  .set(set)
@@ -322,8 +263,7 @@ async function guardedTransition(db, jobId, fromStatuses, set) {
322
263
  const n = typeof affected === 'number' ? affected : Number(affected);
323
264
  if (Number.isFinite(n))
324
265
  return n > 0;
325
- // Unknown return shape: the row is in the target state AND that state is not
326
- // one it could have been in before (the guard excludes it) means we moved it.
266
+ // Non-numeric return: the row is in the target state and could not have been there before.
327
267
  const row = await getJobById(db, jobId);
328
268
  return row?.status === set.status && !fromStatuses.includes(set.status);
329
269
  }
@@ -331,14 +271,7 @@ async function guardedTransition(db, jobId, fromStatuses, set) {
331
271
  async function markBuilding(db, jobId, attempt) {
332
272
  return guardedTransition(db, jobId, ['pending'], { status: 'building', attempt });
333
273
  }
334
- /**
335
- * building → submitting. Commits the signed transaction, its hash, the unsigned
336
- * CBOR and the fee BEFORE the tx is handed to a backend — the whole point of the
337
- * state: whatever happens to the process during `submitTransaction`, the exact
338
- * bytes that may be on-chain survive, and the job keeps holding its idempotency
339
- * key so a caller retry can never turn into a second, differently-built payment.
340
- * `submittedAt` is the attempt time (timeout base), not proof of acceptance.
341
- */
274
+ /** Stores the signed tx before the network call, so the exact bytes survive a crash. submittedAt is the attempt time. */
342
275
  async function markSubmitting(db, jobId, artifacts) {
343
276
  return guardedTransition(db, jobId, ['building'], {
344
277
  status: 'submitting',
@@ -349,22 +282,11 @@ async function markSubmitting(db, jobId, artifacts) {
349
282
  submittedAt: new Date().toISOString(),
350
283
  });
351
284
  }
352
- /**
353
- * submitting → submitted: a backend accepted the tx (or reconciliation found it
354
- * on-chain). The artifacts are already durable from markSubmitting; only the hash
355
- * is re-asserted, in case the backend canonicalized it.
356
- */
285
+ /** submitting → submitted (accepted by a backend or found on-chain). Re-asserts only the hash. */
357
286
  async function markSubmitted(db, jobId, txHash) {
358
287
  return guardedTransition(db, jobId, ['submitting'], { status: 'submitted', txHash });
359
288
  }
360
- /**
361
- * building → pending (transient failure, attempts left). Keeps the error visible
362
- * and defers the next attempt via `notBefore` (exponential backoff).
363
- *
364
- * Guarded on `building` ON PURPOSE: once a job is `submitting` its tx may be in a
365
- * mempool, and re-queueing it would rebuild a different transaction from the same
366
- * request — the duplicate-payment path. Those rows go to reconciliation instead.
367
- */
289
+ /** Requeues a building job after a transient error. Never a submitting job, since a rebuild could pay twice. */
368
290
  async function requeueForRetry(db, jobId, err, notBefore) {
369
291
  const message = err instanceof Error ? err.message : String(err);
370
292
  return guardedTransition(db, jobId, ['building'], {
@@ -379,7 +301,7 @@ async function recordConfirmationPoint(db, jobId, point) {
379
301
  .set({ confirmedSlot: point.slot, confirmedHeight: point.height })
380
302
  .where({ ID: jobId, status: 'submitted' }));
381
303
  }
382
- /** A rollback invalidated the recorded confirmation point — back to watching. */
304
+ /** A rollback invalidated the recorded confirmation point. */
383
305
  async function clearConfirmationPoint(db, jobId) {
384
306
  await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
385
307
  .set({ confirmedSlot: null, confirmedHeight: null })
@@ -396,19 +318,25 @@ async function markConfirmed(db, jobId) {
396
318
  errorMessage: null,
397
319
  });
398
320
  }
399
- /**
400
- * Any active state → failed (terminal). Failing a `submitting`/`submitted` row is
401
- * only safe once the chain has been consulted — a failed row releases the
402
- * idempotency key, so a premature failure invites the caller's retry to pay twice.
403
- */
321
+ /** Fails a job that never sent a transaction and frees its key for the caller's retry. */
404
322
  async function markFailed(db, jobId, code, err) {
405
323
  const message = err instanceof Error ? err.message : String(err);
406
- return guardedTransition(db, jobId, ['pending', 'building', 'submitting', 'submitted'], {
324
+ return guardedTransition(db, jobId, ['pending', 'building'], {
325
+ status: 'failed',
326
+ errorCode: code.slice(0, 50),
327
+ errorMessage: message.slice(0, 500),
328
+ finishedAt: new Date().toISOString(),
329
+ dedupKey: jobId,
330
+ });
331
+ }
332
+ // The signed bytes may still reach the chain, so the key stays: a retry gets this job, not a second payment.
333
+ async function markFailedAfterSend(db, jobId, code, err) {
334
+ const message = err instanceof Error ? err.message : String(err);
335
+ return guardedTransition(db, jobId, ['submitting', 'submitted'], {
407
336
  status: 'failed',
408
337
  errorCode: code.slice(0, 50),
409
338
  errorMessage: message.slice(0, 500),
410
339
  finishedAt: new Date().toISOString(),
411
- dedupKey: jobId, // free the idempotency key for the caller's retry
412
340
  });
413
341
  }
414
342
  /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
@@ -427,17 +355,7 @@ function walletLeaseHeld(wallet, now) {
427
355
  const deadline = Date.parse(wallet.leaseUntil);
428
356
  return Number.isFinite(deadline) && deadline > now.getTime();
429
357
  }
430
- /**
431
- * Fail one wallet's orphaned `building` row(s) — but ONLY when the wallet's lease
432
- * is expired/unowned, i.e. no live instance is executing them. Rows whose wallet
433
- * lease is held belong to a running executor (possibly on another instance) and
434
- * must not be touched.
435
- *
436
- * Safe by construction: a `building` row is pre-submit by definition — the worker
437
- * transitions to `submitting` (with the signed CBOR) before anything can reach a
438
- * backend, so nothing that is still `building` has ever been sent. Rows that made
439
- * it past that point are `submitting` and are reconciled, never failed here.
440
- */
358
+ /** Fails orphaned building rows of a wallet without a live lease. Such rows were never sent. */
441
359
  async function failOrphanedBuildingJobs(db, walletId, now = new Date()) {
442
360
  const wallet = await readWallet(db, walletId);
443
361
  if (walletLeaseHeld(wallet, now))
@@ -445,9 +363,7 @@ async function failOrphanedBuildingJobs(db, walletId, now = new Date()) {
445
363
  const building = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).columns('ID').where({ walletId, status: 'building' }));
446
364
  if (!building?.length)
447
365
  return 0;
448
- // Per row rather than one bulk UPDATE: each row releases its idempotency key to
449
- // its OWN ID (see releaseDedupClaim), which a single statement cannot express
450
- // portably. Orphan sets are one row in practice — a wallet runs one job at a time.
366
+ // Per row: each releases its idempotency key to its OWN ID, which one bulk UPDATE cannot express portably.
451
367
  for (const { ID } of building) {
452
368
  await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
453
369
  .set({
@@ -462,23 +378,8 @@ async function failOrphanedBuildingJobs(db, walletId, now = new Date()) {
462
378
  logger.warn(`Wallet ${walletId}: failed ${building.length} orphaned building job(s) as failed:PROCESS_RESTART`);
463
379
  return building.length;
464
380
  }
465
- /**
466
- * Boot-time recovery (design §8), by state:
467
- * - `building` — nothing was signed and stored yet, so nothing was submitted:
468
- * fail with PROCESS_RESTART (caller retries via idempotencyKey).
469
- * - `submitting` — the signed tx is durable but its fate is unknown: NOT failed
470
- * and NOT rebuilt. Returned so the dispatch loop reconciles it against the
471
- * chain and re-submits those exact bytes if needed.
472
- * - `submitted` — NOT failed: handed to the confirmation tracker; the chain
473
- * decides (found → confirm; absent past the timeout → TX_DROPPED).
474
- *
475
- * Multi-instance safety: a `building` row is only failed when its wallet's lease
476
- * is expired/unowned. A held lease means ANOTHER live instance is executing that
477
- * job right now (rolling deploy) — failing it here while its submit succeeds
478
- * would leave a failed row for an on-chain tx, and since failed rows don't block
479
- * idempotency dedup, the caller's documented retry would pay twice. Rows skipped
480
- * here are cleaned up later by failOrphanedBuildingJobs once the lease expires.
481
- */
381
+ // Boot recovery. Building rows without a live lease fail with PROCESS_RESTART.
382
+ // Submitting rows are checked against the chain, never rebuilt. Submitted rows go to the tracker.
482
383
  async function recoverInterruptedJobs(db, now = new Date()) {
483
384
  const building = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).columns('ID', 'walletId').where({ status: 'building' }));
484
385
  let failedBuilding = 0;
@@ -491,7 +392,7 @@ async function recoverInterruptedJobs(db, now = new Date()) {
491
392
  skippedWallets.push(walletId);
492
393
  }
493
394
  if (skippedWallets.length) {
494
- logger.info(`Recovery skipped building job(s) for wallet(s) ${skippedWallets.join(', ')} — lease still held by a live instance`);
395
+ logger.info(`Recovery skipped building job(s) for wallet(s) ${skippedWallets.join(', ')}, lease still held by a live instance`);
495
396
  }
496
397
  const submitted = await findSubmittedJobs(db);
497
398
  if (submitted.length) {
@@ -499,19 +400,21 @@ async function recoverInterruptedJobs(db, now = new Date()) {
499
400
  }
500
401
  const submitting = (await db.run(SELECT.from(cardano_1.CardanoWalletJobs).where({ status: 'submitting' })) ?? []).map(toJobRow);
501
402
  if (submitting.length) {
502
- logger.warn(`${submitting.length} job(s) interrupted around submit — the dispatch loop will reconcile them against the chain (never a rebuild)`);
403
+ logger.warn(`${submitting.length} job(s) interrupted around submit. The dispatch loop will reconcile them against the chain (never a rebuild)`);
503
404
  }
504
405
  return { failedBuilding, submittedToReconcile: submitted, submittingToReconcile: submitting };
505
406
  }
506
407
  // ---- Worker wallets --------------------------------------------------------------
507
408
  /** Idempotently register/refresh a configured wallet row (no key material). */
508
409
  async function upsertWalletRegistration(db, wallet) {
410
+ const requiresRole = wallet.requiresRole ?? null;
509
411
  const existing = await db.run(SELECT.one.from(cardano_1.CardanoWorkerWallets).where({ walletId: wallet.walletId }));
510
412
  if (existing) {
511
413
  await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({
512
414
  signerType: wallet.signerType,
513
415
  address: wallet.address,
514
416
  publicKeyHash: wallet.publicKeyHash,
417
+ requiresRole,
515
418
  }).where({ walletId: wallet.walletId }));
516
419
  return;
517
420
  }
@@ -520,6 +423,7 @@ async function upsertWalletRegistration(db, wallet) {
520
423
  signerType: wallet.signerType,
521
424
  address: wallet.address,
522
425
  publicKeyHash: wallet.publicKeyHash,
426
+ requiresRole,
523
427
  enabled: true,
524
428
  jobsConfirmed: 0,
525
429
  jobsFailed: 0,
@@ -537,14 +441,10 @@ function leaseDeadlineReached(wallet, owner, expectedMs) {
537
441
  if (!wallet || wallet.leaseOwner !== owner || !wallet.leaseUntil)
538
442
  return false;
539
443
  const actualMs = Date.parse(wallet.leaseUntil);
540
- // One second tolerance for adapter timestamp normalization (crawler lease pattern).
444
+ // One second tolerance for adapter timestamp normalization.
541
445
  return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
542
446
  }
543
- /**
544
- * Atomically acquire an expired/unowned per-wallet lease (compare-and-swap +
545
- * read-back verification, same shape as the crawler lease). At most one worker
546
- * instance may execute jobs for a wallet at any time.
547
- */
447
+ /** Takes a free wallet lease by compare-and-swap with read-back. One instance runs a wallet's jobs at a time. */
548
448
  async function tryAcquireWalletLease(db, walletId, owner, now = new Date(), ttlMs = exports.WORKER_LEASE_TTL_MS) {
549
449
  const raw = await db.run(SELECT.one.from(cardano_1.CardanoWorkerWallets).where({ walletId }));
550
450
  if (!raw)
@@ -556,8 +456,8 @@ async function tryAcquireWalletLease(db, walletId, owner, now = new Date(), ttlM
556
456
  if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
557
457
  return false;
558
458
  const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
559
- // CAS on the observed owner only — timestamp equality is adapter-fragile and
560
- // could make an expired lease permanently untakeable (see tryAcquireCrawlerLease).
459
+ // CAS on the observed owner only: timestamp equality is adapter-fragile and could
460
+ // make an expired lease permanently untakeable.
561
461
  await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({ leaseOwner: owner, leaseUntil }).where({
562
462
  walletId,
563
463
  leaseOwner: raw.leaseOwner ?? null,
@@ -1,24 +1,3 @@
1
- /**
2
- * Keeps a per-wallet lease alive for as long as a job execution runs.
3
- *
4
- * Building and signing a transaction can easily outlast WORKER_LEASE_TTL_MS (a
5
- * multi-backend build plus an HSM round-trip); a single renewal before the build
6
- * is therefore not enough. Without a heartbeat the lease silently expires
7
- * mid-execution, another instance adopts the wallet, fails this executor's row as
8
- * orphaned and starts the next job — two executors on one wallet, which is exactly
9
- * what the per-wallet lease exists to prevent.
10
- *
11
- * Renewals run at a third of the TTL, so two consecutive misses (slow DB, event
12
- * loop hiccup) are tolerated before the lease can lapse. A process that is truly
13
- * wedged stops beating and correctly loses the wallet.
14
- *
15
- * Two failure semantics, on purpose:
16
- * - the periodic `beat` is lenient: a DB error is logged and retried next tick,
17
- * only a definitive "not yours" marks the lease lost.
18
- * - `fence()` is strict: it is called right before an irreversible step, where
19
- * "cannot prove ownership" must be treated as "not ours". Aborting there is
20
- * free (nothing has been sent yet); guessing wrong is a double spend.
21
- */
22
1
  export declare const LEASE_HEARTBEAT_INTERVAL_MS: number;
23
2
  export declare class LeaseHeartbeat {
24
3
  private readonly renew;
@@ -26,14 +5,11 @@ export declare class LeaseHeartbeat {
26
5
  private readonly intervalMs;
27
6
  private timer;
28
7
  private lost;
29
- /**
30
- * @param renew renews the lease and reports whether it is (still) ours
31
- * @param label what the lease covers, for log messages
32
- */
8
+ /** renew reports whether the lease is still ours. label names the lease in logs. */
33
9
  constructor(renew: () => Promise<boolean>, label: string, intervalMs?: number);
34
10
  start(): void;
35
11
  stop(): void;
36
- /** True once a renewal proved the lease is no longer ours — abort the execution. */
12
+ /** True once a renewal proved the lease is not ours. The execution must abort. */
37
13
  isLost(): boolean;
38
14
  /** Renew now; false means "do not touch this wallet any further". */
39
15
  fence(): Promise<boolean>;
@@ -7,27 +7,8 @@ exports.LeaseHeartbeat = exports.LEASE_HEARTBEAT_INTERVAL_MS = void 0;
7
7
  const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const job_store_1 = require("./job-store");
9
9
  const logger = cds_1.default.log('CardanoWalletWorker');
10
- /**
11
- * Keeps a per-wallet lease alive for as long as a job execution runs.
12
- *
13
- * Building and signing a transaction can easily outlast WORKER_LEASE_TTL_MS (a
14
- * multi-backend build plus an HSM round-trip); a single renewal before the build
15
- * is therefore not enough. Without a heartbeat the lease silently expires
16
- * mid-execution, another instance adopts the wallet, fails this executor's row as
17
- * orphaned and starts the next job — two executors on one wallet, which is exactly
18
- * what the per-wallet lease exists to prevent.
19
- *
20
- * Renewals run at a third of the TTL, so two consecutive misses (slow DB, event
21
- * loop hiccup) are tolerated before the lease can lapse. A process that is truly
22
- * wedged stops beating and correctly loses the wallet.
23
- *
24
- * Two failure semantics, on purpose:
25
- * - the periodic `beat` is lenient: a DB error is logged and retried next tick,
26
- * only a definitive "not yours" marks the lease lost.
27
- * - `fence()` is strict: it is called right before an irreversible step, where
28
- * "cannot prove ownership" must be treated as "not ours". Aborting there is
29
- * free (nothing has been sent yet); guessing wrong is a double spend.
30
- */
10
+ // Keeps a wallet lease alive while a job runs. Renewing at a third of the TTL tolerates two misses.
11
+ // beat retries on DB errors. fence treats an unprovable lease as lost, before irreversible steps.
31
12
  exports.LEASE_HEARTBEAT_INTERVAL_MS = Math.floor(job_store_1.WORKER_LEASE_TTL_MS / 3);
32
13
  class LeaseHeartbeat {
33
14
  renew;
@@ -35,10 +16,7 @@ class LeaseHeartbeat {
35
16
  intervalMs;
36
17
  timer = null;
37
18
  lost = false;
38
- /**
39
- * @param renew renews the lease and reports whether it is (still) ours
40
- * @param label what the lease covers, for log messages
41
- */
19
+ /** renew reports whether the lease is still ours. label names the lease in logs. */
42
20
  constructor(renew, label, intervalMs = exports.LEASE_HEARTBEAT_INTERVAL_MS) {
43
21
  this.renew = renew;
44
22
  this.label = label;
@@ -56,7 +34,7 @@ class LeaseHeartbeat {
56
34
  this.timer = null;
57
35
  }
58
36
  }
59
- /** True once a renewal proved the lease is no longer ours — abort the execution. */
37
+ /** True once a renewal proved the lease is not ours. The execution must abort. */
60
38
  isLost() {
61
39
  return this.lost;
62
40
  }
@@ -71,7 +49,7 @@ class LeaseHeartbeat {
71
49
  return held;
72
50
  }
73
51
  catch (err) {
74
- logger.warn(`Lease fence for ${this.label} could not be verified — treating the lease as lost:`, err);
52
+ logger.warn(`Lease fence for ${this.label} could not be verified, treating the lease as lost:`, err);
75
53
  this.lost = true;
76
54
  return false;
77
55
  }
@@ -92,7 +70,7 @@ class LeaseHeartbeat {
92
70
  return;
93
71
  this.lost = true;
94
72
  this.stop();
95
- logger.warn(`Lease for ${this.label} was taken over by another instance — this executor must stand down`);
73
+ logger.warn(`Lease for ${this.label} was taken over by another instance, this executor must stand down`);
96
74
  }
97
75
  }
98
76
  exports.LeaseHeartbeat = LeaseHeartbeat;