@odatano/core 1.9.5 → 1.10.0

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.
@@ -14,7 +14,8 @@ const external_signer_1 = require("./blockchain/signing/external-signer");
14
14
  const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
15
15
  const cose_verifier_1 = require("./blockchain/signing/cose-verifier");
16
16
  const signing_helper_1 = require("./utils/signing-helper");
17
- const tx_build_helper_1 = require("./utils/tx-build-helper");
17
+ const tx_utils_1 = require("./utils/tx-utils");
18
+ const submission_finalizer_1 = require("./blockchain/signing/submission-finalizer");
18
19
  const { SELECT, UPDATE } = cds_1.default.ql;
19
20
  const logger = cds_1.default.log('CardanoSignService');
20
21
  /**
@@ -83,62 +84,8 @@ async function resolveRequiredSigners(db, signingRequest, TransactionBuilds) {
83
84
  }
84
85
  return signers.size > 0 ? [...signers] : undefined;
85
86
  }
86
- /**
87
- * Submit a verified+claimed signing request to the blockchain and persist the
88
- * outcome — DELIBERATELY outside the caller's request transaction.
89
- *
90
- * The caller must already have durably committed `status:'submitting'` (the
91
- * claim). This function then:
92
- * 1. submits with NO DB write-lock held (the lock was the reason concurrent
93
- * submits serialized and the SQLite busy-timeout could fire mid-network),
94
- * 2. on submit failure: marks the request 'failed' in its own committed tx
95
- * and rethrows (NOT rolled back to a pre-submit status — losing the
96
- * attempt would hide a tx the node may have accepted),
97
- * 3. on success: persists the submission + 'submitted' status in a committed
98
- * transaction.
99
- *
100
- * Crash window: a process death between (1) and (3) leaves the request durably
101
- * at 'submitting' — the operator/poller checks the chain — instead of silently
102
- * reverting to 'pending'/'verified' with no on-chain trace.
103
- */
104
- async function submitAndFinalize(SigningRequests, params, afterFinalize) {
105
- // Persist the submission + 'submitted' status in its own committed transaction.
106
- const finalizeSubmitted = () => cds_1.default.tx(async (db) => {
107
- const submission = await (0, server_1.getCardanoIndexer)().indexVerifiedTransactionSubmission(db, params);
108
- if (afterFinalize)
109
- await afterFinalize(db);
110
- // Invalidate stale UTxO cache (spent inputs + output addresses) — best-effort,
111
- // must never roll back the durable submission record.
112
- try {
113
- await (0, server_1.getCardanoIndexer)().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(params.fullSignedTxCbor));
114
- }
115
- catch (invalidateErr) {
116
- logger.warn(`UTxO cache invalidation failed (submit unaffected): ${invalidateErr instanceof Error ? invalidateErr.message : String(invalidateErr)}`);
117
- }
118
- return submission;
119
- });
120
- try {
121
- await (0, server_1.getCardanoClient)().submitTransaction(params.fullSignedTxCbor);
122
- }
123
- catch (submitErr) {
124
- // Already-submitted means the tx reached the mempool — e.g. the first backend accepted
125
- // it but its response was lost and a fallback observed the duplicate. That is SUCCESS,
126
- // not failure: finalize it as 'submitted' (same as the happy path) instead of durably
127
- // recording a spurious 'failed' for a tx the node already holds.
128
- if (submitErr instanceof errors_1.TransactionAlreadySubmittedError) {
129
- logger.info({ signingRequestId: params.signingRequestId, txHash: params.txHash }, 'Submit reported already-submitted — finalizing as submitted (tx already in mempool)');
130
- return finalizeSubmitted();
131
- }
132
- try {
133
- await cds_1.default.tx((db) => db.run(UPDATE.entity(SigningRequests).set({ status: 'failed' }).where({ id: params.signingRequestId })));
134
- }
135
- catch (markErr) {
136
- logger.error({ err: markErr, signingRequestId: params.signingRequestId }, 'Could not durably mark signing request failed after submit error');
137
- }
138
- throw submitErr;
139
- }
140
- return finalizeSubmitted();
141
- }
87
+ // submitAndFinalize + FinalizeParams moved to blockchain/signing/submission-finalizer.ts
88
+ // (shared with the boot-time redrive of interrupted deferred submissions).
142
89
  /**
143
90
  * Enforce HSM role check if hsm.requiresRole is configured.
144
91
  * Rejects with 403 if the user lacks the required role.
@@ -311,6 +258,7 @@ module.exports = (srv) => {
311
258
  srv.on('SubmitVerifiedTransaction', async (req) => {
312
259
  logger.debug('SubmitVerifiedTransaction Action handler called');
313
260
  const { signingRequestId, signedTxCbor, signerType, signerInfo, address } = req.data;
261
+ const deferSubmit = req.data.deferSubmit === true;
314
262
  const errors = (0, validators_1.validateTransactionInputs)({ signingRequestId, signedTxCbor }, ['signingRequestId', 'signedTxCbor']);
315
263
  (0, errors_1.throwIfValidationErrors)(req, 'SubmitVerifiedTransaction', errors);
316
264
  if (address && !(0, validators_1.isValidBech32Address)(address))
@@ -318,30 +266,29 @@ module.exports = (srv) => {
318
266
  // Three committed phases instead of one request-long transaction (see
319
267
  // submitAndFinalize): the network submit must NOT run inside an open DB
320
268
  // transaction. Errors are mapped the same way handleRequest would.
269
+ //
270
+ // deferSubmit (KNOWN_ISSUES #11, Layer 2): phase 1 instead JOINS the
271
+ // caller's transaction (claim + signed CBOR commit with the caller), the
272
+ // response returns immediately with the tx hash (= body hash), and the
273
+ // network submit runs detached after the caller's commit.
321
274
  try {
322
- // PHASE 1 (committed): atomically claim → 'submitting' and fully verify.
323
- // A reject/verification failure here rolls the claim back, so a bad
324
- // signature never strands the request in 'submitting'.
325
- const prep = await cds_1.default.tx(async (db) => {
275
+ // PHASE 1 (committed): fully verify, then atomically claim → 'submitting'.
276
+ // The claim is deliberately the LAST statement: on the deferred path
277
+ // these statements run on the CALLER's transaction, and a verification
278
+ // failure whose error the caller swallows (and then commits) must not
279
+ // leave a stranded 'submitting' claim behind — everything before the
280
+ // claim is read-only. The guarded UPDATE (status still pending/verified)
281
+ // remains the atomic gate against concurrent submits on both paths.
282
+ const phase1 = async (db) => {
326
283
  const now = new Date().toISOString();
327
- const claimed = await db.run(UPDATE.entity(SigningRequests)
328
- .set({ status: 'submitting' })
329
- .where({
330
- id: signingRequestId,
331
- status: { in: ['pending', 'verified'] },
332
- expiresAt: { '>': now },
333
- }));
334
- if (claimed === 0) {
335
- // Claim failed — fetch to provide a specific error message
336
- const existing = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
337
- if (!existing)
338
- (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request not found', 'signingRequestId');
339
- if (existing.expiresAt <= now)
340
- (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request has expired', 'signingRequestId');
341
- (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', `Signing request status is '${existing.status}', expected 'pending' or 'verified'`, 'signingRequestId');
342
- }
343
- // Re-fetch the full record (now with status='submitting')
344
284
  const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
285
+ if (!signingRequest)
286
+ (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request not found', 'signingRequestId');
287
+ if (signingRequest.expiresAt <= now)
288
+ (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request has expired', 'signingRequestId');
289
+ if (!['pending', 'verified'].includes(signingRequest.status)) {
290
+ (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', `Signing request status is '${signingRequest.status}', expected 'pending' or 'verified'`, 'signingRequestId');
291
+ }
345
292
  // Ownership check: verify address matches build owner (defense-in-depth)
346
293
  if (address && signingRequest.build_id) {
347
294
  await verifyBuildOwnership(req, db, signingRequest.build_id, address, TransactionBuilds, 'SubmitVerifiedTransaction');
@@ -358,11 +305,25 @@ module.exports = (srv) => {
358
305
  // actually witness this transaction (required_signers + fee payer)
359
306
  const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
360
307
  const verificationResult = (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(fullSignedTxCbor, signingRequest.txBodyHash, { requiredSigners });
308
+ // Atomic claim — last statement, see above. Deferred path: persist the
309
+ // signed CBOR + signer metadata with the claim, so an interrupted
310
+ // submission can be re-driven after a restart.
311
+ const claimed = await db.run(UPDATE.entity(SigningRequests)
312
+ .set({
313
+ status: 'submitting',
314
+ ...(deferSubmit ? { signedTxCbor: fullSignedTxCbor, signerType, signerInfo } : {}),
315
+ })
316
+ .where({
317
+ id: signingRequestId,
318
+ status: { in: ['pending', 'verified'] },
319
+ expiresAt: { '>': now },
320
+ }));
321
+ if (claimed === 0) {
322
+ (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request was claimed by a concurrent submission', 'signingRequestId');
323
+ }
361
324
  return { buildId: signingRequest.build_id, txHash: signingRequest.txBodyHash, fullSignedTxCbor, verificationResult };
362
- });
363
- logger.info({ signingRequestId, witnessCount: prep.verificationResult.witnessCount }, 'Signature verified, proceeding with submission');
364
- // PHASES 2+3: submit outside any DB tx, then finalize in its own tx
365
- const submissionRecord = await submitAndFinalize(SigningRequests, {
325
+ };
326
+ const finalizeParams = (prep) => ({
366
327
  signingRequestId,
367
328
  buildId: prep.buildId,
368
329
  fullSignedTxCbor: prep.fullSignedTxCbor,
@@ -371,6 +332,26 @@ module.exports = (srv) => {
371
332
  signerType,
372
333
  signerInfo,
373
334
  });
335
+ if (deferSubmit) {
336
+ // Phase 1 on the CALLER's transaction: joins its pooled connection (no
337
+ // deadlock), commits together with the caller. Validation errors stay
338
+ // synchronous; the submit is scheduled for after the commit.
339
+ const prep = await phase1(cds_1.default.tx(req));
340
+ (0, submission_finalizer_1.scheduleDeferredSubmit)(req, SigningRequests, finalizeParams(prep));
341
+ logger.info({ signingRequestId, txHash: prep.txHash }, 'Verified and claimed — submit deferred until after the caller commits');
342
+ return {
343
+ id: null,
344
+ build_id: prep.buildId,
345
+ txHash: prep.txHash,
346
+ signedTxCbor: prep.fullSignedTxCbor,
347
+ status: 'pending',
348
+ submittedAt: null,
349
+ };
350
+ }
351
+ const prep = await (0, tx_utils_1.detachedTx)('claim + verify signing request', phase1);
352
+ logger.info({ signingRequestId, witnessCount: prep.verificationResult.witnessCount }, 'Signature verified, proceeding with submission');
353
+ // PHASES 2+3: submit outside any DB tx, then finalize in its own tx
354
+ const submissionRecord = await (0, submission_finalizer_1.submitAndFinalize)(SigningRequests, finalizeParams(prep));
374
355
  logger.info({ signingRequestId, txHash: prep.txHash }, 'Transaction submitted and all records updated');
375
356
  return submissionRecord;
376
357
  }
@@ -503,6 +484,7 @@ module.exports = (srv) => {
503
484
  logger.debug('SignAndSubmitWithHsm Action handler called');
504
485
  enforceHsmRole(req, 'SignAndSubmitWithHsm');
505
486
  const { buildId, address } = req.data;
487
+ const deferSubmit = req.data.deferSubmit === true;
506
488
  // Validate input
507
489
  const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
508
490
  (0, errors_1.throwIfValidationErrors)(req, 'SignAndSubmitWithHsm', errors);
@@ -515,8 +497,10 @@ module.exports = (srv) => {
515
497
  }
516
498
  try {
517
499
  // PHASE 1 (committed): fetch build, sign with HSM, verify. A failure
518
- // here rolls back the freshly-created signing request.
519
- const prep = await cds_1.default.tx(async (db) => {
500
+ // here rolls back the freshly-created signing request. (Deferred path:
501
+ // the INSERT runs on the caller's tx; a swallowed failure leaves a
502
+ // 'pending' row that expires via its TTL — harmless.)
503
+ const phase1 = async (db) => {
520
504
  // 1. Fetch the build (with ownership check)
521
505
  const build = await verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, 'SignAndSubmitWithHsm');
522
506
  // HSM can only sign builds for its own address
@@ -538,14 +522,17 @@ module.exports = (srv) => {
538
522
  logger.error({ signingRequestId: signingRequestRecord.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed — aborting submission');
539
523
  (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'HSM signature verification failed', 'signedTxCbor');
540
524
  }
541
- // Claim the request as 'submitting' in this same committed phase
542
- await db.run(UPDATE.entity(SigningRequests).set({ status: 'submitting', hsmKeyId: hsmKeyIdentifier }).where({ id: signingRequestRecord.id }));
525
+ // Claim the request as 'submitting' in this same committed phase.
526
+ // Deferred path: also persist the signed CBOR + signer metadata for
527
+ // the boot-time redrive of interrupted submissions.
528
+ await db.run(UPDATE.entity(SigningRequests).set({
529
+ status: 'submitting',
530
+ hsmKeyId: hsmKeyIdentifier,
531
+ ...(deferSubmit ? { signedTxCbor, signerType: 'hsm', signerInfo: `HSM key: ${hsmKeyIdentifier}` } : {}),
532
+ }).where({ id: signingRequestRecord.id }));
543
533
  return { signingRequestId: signingRequestRecord.id, signedTxCbor, txHash: build.txBodyHash, verificationResult, hsmKeyIdentifier };
544
- });
545
- logger.info({ signingRequestId: prep.signingRequestId, witnessCount: prep.verificationResult.witnessCount, hsmKey: prep.hsmKeyIdentifier }, 'HSM signature verified, proceeding with submission');
546
- // PHASES 2+3: submit outside any DB tx, then finalize (re-set hsmKeyId,
547
- // which indexVerifiedTransactionSubmission does not touch)
548
- const submissionRecord = await submitAndFinalize(SigningRequests, {
534
+ };
535
+ const finalizeParams = (prep) => ({
549
536
  signingRequestId: prep.signingRequestId,
550
537
  buildId,
551
538
  fullSignedTxCbor: prep.signedTxCbor,
@@ -553,7 +540,28 @@ module.exports = (srv) => {
553
540
  verificationResult: prep.verificationResult,
554
541
  signerType: 'hsm',
555
542
  signerInfo: `HSM key: ${prep.hsmKeyIdentifier}`,
556
- }, (db) => db.run(UPDATE.entity(SigningRequests).set({ hsmKeyId: prep.hsmKeyIdentifier }).where({ id: prep.signingRequestId })).then(() => undefined));
543
+ });
544
+ if (deferSubmit) {
545
+ // Phase 1 on the CALLER's transaction (KNOWN_ISSUES #11, Layer 2):
546
+ // sign + verify + claim commit with the caller; submit runs after its
547
+ // commit. See SubmitVerifiedTransaction for the full rationale.
548
+ const prep = await phase1(cds_1.default.tx(req));
549
+ (0, submission_finalizer_1.scheduleDeferredSubmit)(req, SigningRequests, finalizeParams(prep));
550
+ logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed and claimed — submit deferred until after the caller commits');
551
+ return {
552
+ id: null,
553
+ build_id: buildId,
554
+ txHash: prep.txHash,
555
+ signedTxCbor: prep.signedTxCbor,
556
+ status: 'pending',
557
+ submittedAt: null,
558
+ };
559
+ }
560
+ const prep = await (0, tx_utils_1.detachedTx)('HSM sign + claim signing request', phase1);
561
+ logger.info({ signingRequestId: prep.signingRequestId, witnessCount: prep.verificationResult.witnessCount, hsmKey: prep.hsmKeyIdentifier }, 'HSM signature verified, proceeding with submission');
562
+ // PHASES 2+3: submit outside any DB tx, then finalize (re-set hsmKeyId,
563
+ // which indexVerifiedTransactionSubmission does not touch)
564
+ const submissionRecord = await (0, submission_finalizer_1.submitAndFinalize)(SigningRequests, finalizeParams(prep), (db) => db.run(UPDATE.entity(SigningRequests).set({ hsmKeyId: prep.hsmKeyIdentifier }).where({ id: prep.signingRequestId })).then(() => undefined));
557
565
  logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed transaction submitted and all records updated');
558
566
  return submissionRecord;
559
567
  }
package/srv/server.d.ts CHANGED
@@ -86,5 +86,13 @@ export declare function loadConfigFromEnv(): CardanoClientConfig;
86
86
  * @returns HsmConfig or undefined
87
87
  */
88
88
  export declare function loadHsmConfigFromEnv(): HsmConfig | undefined;
89
+ /**
90
+ * Re-drive deferred submissions that were claimed (status 'submitting' with
91
+ * persisted signedTxCbor) but whose detached submit never ran because the
92
+ * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
93
+ * submitted tx finalizes via the TransactionAlreadySubmittedError path.
94
+ * Non-fatal.
95
+ */
96
+ export declare function redriveInterruptedSubmissionsIfConfigured(): Promise<void>;
89
97
  export {};
90
98
  //# sourceMappingURL=server.d.ts.map
package/srv/server.js CHANGED
@@ -1,4 +1,37 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
37
  };
@@ -14,6 +47,7 @@ exports.createTestContext = createTestContext;
14
47
  exports.shutdownAppContext = shutdownAppContext;
15
48
  exports.loadConfigFromEnv = loadConfigFromEnv;
16
49
  exports.loadHsmConfigFromEnv = loadHsmConfigFromEnv;
50
+ exports.redriveInterruptedSubmissionsIfConfigured = redriveInterruptedSubmissionsIfConfigured;
17
51
  const cds_1 = __importDefault(require("@sap/cds"));
18
52
  const cardano_client_1 = require("./blockchain/cardano-client");
19
53
  const cardano_indexer_1 = require("./blockchain/cardano-indexer");
@@ -311,6 +345,26 @@ function loadHsmConfigFromEnv() {
311
345
  requiresRole,
312
346
  };
313
347
  }
348
+ /**
349
+ * Re-drive deferred submissions that were claimed (status 'submitting' with
350
+ * persisted signedTxCbor) but whose detached submit never ran because the
351
+ * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
352
+ * submitted tx finalizes via the TransactionAlreadySubmittedError path.
353
+ * Non-fatal.
354
+ */
355
+ async function redriveInterruptedSubmissionsIfConfigured() {
356
+ if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
357
+ return;
358
+ try {
359
+ const { redriveInterruptedSubmissions } = await Promise.resolve().then(() => __importStar(require('./blockchain/signing/submission-finalizer')));
360
+ const attempted = await redriveInterruptedSubmissions();
361
+ if (attempted > 0)
362
+ logger.info(`Re-drove ${attempted} interrupted deferred submission(s)`);
363
+ }
364
+ catch (err) {
365
+ logger.error('Failed to re-drive interrupted submissions (non-fatal):', err);
366
+ }
367
+ }
314
368
  // Bootstrap hook - runs when CAP server has loaded all services
315
369
  cds_1.default.on('served', async () => {
316
370
  // Skip if already initialized by plugin (src/plugin.ts runs first)
@@ -346,6 +400,8 @@ cds_1.default.on('served', async () => {
346
400
  process.stderr.write(`[ODATANO] Failed to initialize blockchain components — ${where}\n${msg}\n`);
347
401
  logger.error('Failed to initialize blockchain components:', err);
348
402
  }
403
+ // Re-drive deferred submissions interrupted by a restart (standalone mode). Non-fatal.
404
+ await redriveInterruptedSubmissionsIfConfigured();
349
405
  });
350
406
  // Shutdown hook - runs when CAP server is shutting down (e.g., cds.shutdown() in tests)
351
407
  cds_1.default.on('shutdown', async () => {
@@ -71,6 +71,15 @@ export declare const ERROR_CODES: {
71
71
  * Indicates HSM signing was requested but HSM is not configured
72
72
  */
73
73
  readonly HSM_NOT_CONFIGURED: "ODATANO_HSM_NOT_CONFIGURED";
74
+ /**
75
+ * 503 – Detached transaction could not begin in time
76
+ * The sign-service could not acquire a pooled DB connection for one of its
77
+ * detached bookkeeping transactions. Most common cause: an in-process
78
+ * consumer awaits SubmitVerifiedTransaction/SignAndSubmitWithHsm while its
79
+ * own request transaction holds the (single) pooled sqlite connection —
80
+ * see docs/KNOWN_ISSUES.md issue 11.
81
+ */
82
+ readonly NESTED_TX_TIMEOUT: "ODATANO_NESTED_TX_TIMEOUT";
74
83
  };
75
84
  /**
76
85
  * EnumType representing all possible error codes
@@ -74,5 +74,14 @@ exports.ERROR_CODES = {
74
74
  * Indicates HSM signing was requested but HSM is not configured
75
75
  */
76
76
  HSM_NOT_CONFIGURED: 'ODATANO_HSM_NOT_CONFIGURED',
77
+ /**
78
+ * 503 – Detached transaction could not begin in time
79
+ * The sign-service could not acquire a pooled DB connection for one of its
80
+ * detached bookkeeping transactions. Most common cause: an in-process
81
+ * consumer awaits SubmitVerifiedTransaction/SignAndSubmitWithHsm while its
82
+ * own request transaction holds the (single) pooled sqlite connection —
83
+ * see docs/KNOWN_ISSUES.md issue 11.
84
+ */
85
+ NESTED_TX_TIMEOUT: 'ODATANO_NESTED_TX_TIMEOUT',
77
86
  };
78
87
  //# sourceMappingURL=error-codes.js.map
@@ -0,0 +1,32 @@
1
+ import cds from '@sap/cds';
2
+ /** Default acquire budget for detached bookkeeping transactions. */
3
+ export declare const DETACHED_TX_TIMEOUT_MS = 10000;
4
+ /**
5
+ * Run `fn` with `cds.context` cleared, so any `db.run(...)` inside it gets a
6
+ * fresh short-lived transaction instead of joining a long-lived ambient one.
7
+ * Under @cap-js/sqlite (pool.max=1) this is what keeps the single pooled
8
+ * connection free during long awaits (e.g. the deferred network submit).
9
+ */
10
+ export declare function runWithoutAmbientTx<T>(fn: () => Promise<T>): Promise<T>;
11
+ /**
12
+ * `cds.tx(fn)` with a deadlock guard: a NEW ROOT transaction that fails fast
13
+ * instead of hanging forever when no pooled connection becomes available.
14
+ *
15
+ * Why: the sign-service must commit its submit bookkeeping (claim, finalize,
16
+ * failure marker) independently of the caller's request transaction. When an
17
+ * in-process consumer awaits the action while its own request transaction
18
+ * holds the single pooled sqlite connection, the acquire can never succeed —
19
+ * without this guard that is a silent, zero-CPU, infinite hang.
20
+ *
21
+ * Guarantees:
22
+ * - On timeout, throws `BackendError` 503 `ODATANO_NESTED_TX_TIMEOUT` with a
23
+ * diagnosis pointing at KNOWN_ISSUES #11.
24
+ * - A late connection grant (after the timeout already fired) performs NO
25
+ * work: the callback forces the acquire via an explicit `begin()` and
26
+ * checks the abort flag right after it, so it rolls back immediately and
27
+ * the caller never observes an error for work that then silently happened
28
+ * anyway. (A flag check at callback ENTRY would run long before the lazy
29
+ * acquire and miss the timeout.)
30
+ */
31
+ export declare function detachedTx<T>(label: string, fn: (db: cds.Transaction) => Promise<T>, timeoutMs?: number): Promise<T>;
32
+ //# sourceMappingURL=tx-utils.d.ts.map
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DETACHED_TX_TIMEOUT_MS = void 0;
7
+ exports.runWithoutAmbientTx = runWithoutAmbientTx;
8
+ exports.detachedTx = detachedTx;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const errors_1 = require("./errors");
11
+ const error_codes_1 = require("./error-codes");
12
+ /**
13
+ * Transaction utilities for the sign-service.
14
+ *
15
+ * Context: @cap-js/sqlite runs on a SINGLE pooled connection. A request
16
+ * transaction begins lazily on its first CQL statement and holds that
17
+ * connection until the request commits. Any code that then needs a NEW ROOT
18
+ * transaction (detached committed bookkeeping) waits on the pool — forever,
19
+ * if the waiter is awaited by the very request holding the connection
20
+ * (docs/KNOWN_ISSUES.md issue 11).
21
+ */
22
+ const logger = cds_1.default.log('tx-utils');
23
+ /** Default acquire budget for detached bookkeeping transactions. */
24
+ exports.DETACHED_TX_TIMEOUT_MS = 10_000;
25
+ /** Effective timeout: env override (ODATANO_DETACHED_TX_TIMEOUT_MS) > default. Read per call so tests can tune it. */
26
+ function effectiveTimeoutMs() {
27
+ const fromEnv = Number(process.env.ODATANO_DETACHED_TX_TIMEOUT_MS);
28
+ return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : exports.DETACHED_TX_TIMEOUT_MS;
29
+ }
30
+ /**
31
+ * Run `fn` with `cds.context` cleared, so any `db.run(...)` inside it gets a
32
+ * fresh short-lived transaction instead of joining a long-lived ambient one.
33
+ * Under @cap-js/sqlite (pool.max=1) this is what keeps the single pooled
34
+ * connection free during long awaits (e.g. the deferred network submit).
35
+ */
36
+ function runWithoutAmbientTx(fn) {
37
+ return cds_1.default._with(undefined, fn);
38
+ }
39
+ /** Thrown inside an orphaned `cds.tx` callback after its caller already timed out. */
40
+ class DetachedTxAbortedError extends Error {
41
+ constructor(label) {
42
+ super(`Detached transaction '${label}' aborted: acquire succeeded only after the caller timed out`);
43
+ this.name = 'DetachedTxAbortedError';
44
+ }
45
+ }
46
+ /**
47
+ * `cds.tx(fn)` with a deadlock guard: a NEW ROOT transaction that fails fast
48
+ * instead of hanging forever when no pooled connection becomes available.
49
+ *
50
+ * Why: the sign-service must commit its submit bookkeeping (claim, finalize,
51
+ * failure marker) independently of the caller's request transaction. When an
52
+ * in-process consumer awaits the action while its own request transaction
53
+ * holds the single pooled sqlite connection, the acquire can never succeed —
54
+ * without this guard that is a silent, zero-CPU, infinite hang.
55
+ *
56
+ * Guarantees:
57
+ * - On timeout, throws `BackendError` 503 `ODATANO_NESTED_TX_TIMEOUT` with a
58
+ * diagnosis pointing at KNOWN_ISSUES #11.
59
+ * - A late connection grant (after the timeout already fired) performs NO
60
+ * work: the callback forces the acquire via an explicit `begin()` and
61
+ * checks the abort flag right after it, so it rolls back immediately and
62
+ * the caller never observes an error for work that then silently happened
63
+ * anyway. (A flag check at callback ENTRY would run long before the lazy
64
+ * acquire and miss the timeout.)
65
+ */
66
+ async function detachedTx(label, fn, timeoutMs) {
67
+ const effectiveTimeout = timeoutMs ?? effectiveTimeoutMs();
68
+ let timedOut = false;
69
+ let timer;
70
+ const work = cds_1.default.tx(async (db) => {
71
+ // cds.tx() starts this callback immediately; the pooled connection is only
72
+ // acquired lazily by the first statement. Force the acquire NOW, then check
73
+ // the abort flag — a late grant (after the caller already received the
74
+ // timeout error) must roll back before doing any work.
75
+ await db.begin();
76
+ if (timedOut)
77
+ throw new DetachedTxAbortedError(label);
78
+ return fn(db);
79
+ });
80
+ const guard = new Promise((_, reject) => {
81
+ timer = setTimeout(() => {
82
+ timedOut = true;
83
+ reject(new errors_1.BackendError(`${label}: could not begin a detached DB transaction within ${effectiveTimeout}ms. ` +
84
+ `Most likely the calling request still holds the pooled DB connection open ` +
85
+ `(in-process nested call — do not await this action while your request ` +
86
+ `transaction is open; detach your reads into a committed cds.tx first, ` +
87
+ `see docs/KNOWN_ISSUES.md issue 11). Alternatively the connection pool is exhausted.`, 503, error_codes_1.ERROR_CODES.NESTED_TX_TIMEOUT));
88
+ }, effectiveTimeout);
89
+ });
90
+ try {
91
+ return await Promise.race([work, guard]);
92
+ }
93
+ finally {
94
+ if (timer)
95
+ clearTimeout(timer);
96
+ if (timedOut) {
97
+ // The orphaned acquire may still be granted later; its callback aborts
98
+ // itself via the flag. Observe the rejection so it never surfaces as an
99
+ // unhandled promise rejection.
100
+ work.catch((e) => {
101
+ if (!(e instanceof DetachedTxAbortedError)) {
102
+ logger.warn(`Orphaned detached tx '${label}' failed after timeout: ${e instanceof Error ? e.message : String(e)}`);
103
+ }
104
+ });
105
+ }
106
+ }
107
+ }
108
+ //# sourceMappingURL=tx-utils.js.map