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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +15 -4
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +35 -43
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -47,6 +47,11 @@ export function rebuiltTableSql(createSql, table, newName) {
47
47
  return retyped.replace(new RegExp(`^(\\s*CREATE TABLE\\s+)"?${table}"?`, 'i'), `$1${newName}`);
48
48
  }
49
49
 
50
+ // What a SAP HANA user does instead: an HDI container takes no DDL from the runtime user.
51
+ export const HANA_UPGRADE = 'SAP HANA: this script cannot migrate an HDI container. Deploy this version into a new HDI container '
52
+ + 'and point the application at it. The chain data is read again on demand; the records of your own transactions stay in the '
53
+ + 'old container. docs/guides/UPGRADE_2.0.md has the steps.';
54
+
50
55
  // Tables that moved from the transaction hash to Transactions.txSeq as their key.
51
56
  // `to` is the entity that holds the rows in the model of this version.
52
57
  const TX_SEQ_TABLES = [
@@ -71,6 +76,69 @@ async function count(tx, table) {
71
76
  return Number(row.n);
72
77
  }
73
78
 
79
+ /** Name of the unique constraint that holds one idempotency key per job. */
80
+ const WALLET_JOBS_DEDUP = 'odatano_cardano_CardanoWalletJobs_dedup';
81
+
82
+ /** An allow list as stored: a JSON array of names, anything else is empty. */
83
+ function grantList(raw) {
84
+ try {
85
+ const list = JSON.parse(String(raw ?? '[]'));
86
+ return Array.isArray(list) ? list.filter(n => typeof n === 'string') : [];
87
+ } catch {
88
+ return [];
89
+ }
90
+ }
91
+
92
+ /** The grantable operations of a model, `Service.operation`, by their name without the service. */
93
+ export function grantableByName(model) {
94
+ const definitions = Object.entries(model?.definitions ?? {});
95
+ const services = definitions.filter(([, def]) => def.kind === 'service').map(([name]) => name);
96
+ const byName = new Map();
97
+ const add = (service, operation, def) => {
98
+ if (def?.['@odatano.agent'] !== 'grant') return;
99
+ byName.set(operation, [...(byName.get(operation) ?? []), `${service}.${operation}`]);
100
+ };
101
+ for (const [name, def] of definitions) {
102
+ const service = services.find(s => name.startsWith(`${s}.`));
103
+ if (!service) continue;
104
+ if (def.kind === 'action' || def.kind === 'function') add(service, name.slice(service.length + 1), def);
105
+ for (const [bound, action] of Object.entries(def.actions ?? {})) add(service, bound, action);
106
+ }
107
+ return byName;
108
+ }
109
+
110
+ // A stored allow list with every name qualified. A name without a service allowed the operation of
111
+ // that name in every service, so it becomes all of them; a name nothing declares any more is dropped.
112
+ export function qualifiedGrantList(list, byName) {
113
+ const grantable = new Set([...byName.values()].flat());
114
+ const out = list.flatMap(name => (name.includes('.') ? (grantable.has(name) ? [name] : []) : (byName.get(name) ?? [])));
115
+ return [...new Set(out)];
116
+ }
117
+
118
+ /** Lower-cased columns of a unique constraint, in order; null when the table or the constraint is missing. */
119
+ // Where one idempotency key is held by several jobs, every job but one releases it: a job still in
120
+ // flight keeps it, else the newest. createdAt, then ID, break a tie the same way on every database.
121
+ export function releaseSharedClaimsSql(table) {
122
+ const flight = (alias) => `CASE WHEN ${alias}.status IN ('submitting', 'submitted') THEN 1 ELSE 0 END`;
123
+ return `UPDATE ${table} SET dedupKey = ID WHERE dedupKey <> ID AND EXISTS (`
124
+ + `SELECT 1 FROM ${table} o WHERE o.dedupKey = ${table}.dedupKey AND o.ID <> ${table}.ID AND (`
125
+ + `${flight('o')} > ${flight(table)} OR (${flight('o')} = ${flight(table)} AND (`
126
+ + `o.createdAt > ${table}.createdAt OR (o.createdAt = ${table}.createdAt AND o.ID > ${table}.ID)))))`;
127
+ }
128
+
129
+ export async function uniqueColumns(db, table, constraint) {
130
+ if (db.kind === 'postgres') {
131
+ const rows = await db.run(`SELECT a.attname AS name FROM pg_constraint c JOIN pg_namespace n ON n.oid = c.connamespace
132
+ JOIN unnest(c.conkey) WITH ORDINALITY k(attnum, pos) ON true
133
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum
134
+ WHERE n.nspname = current_schema() AND c.conname = '${constraint.toLowerCase()}' ORDER BY k.pos`);
135
+ return rows.length ? rows.map(r => String(r.name).toLowerCase()) : null;
136
+ }
137
+ const [stored] = await db.run(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = '${table}'`);
138
+ const match = String(stored?.sql ?? '').match(new RegExp(`CONSTRAINT\\s+"?${constraint}"?\\s+UNIQUE\\s*\\(([^)]*)\\)`, 'i'));
139
+ return match ? match[1].split(',').map(c => c.trim().replace(/"/g, '').toLowerCase()) : null;
140
+ }
141
+
74
142
  // The steps, oldest first. `due` says whether the database still needs the step (`pending` names the
75
143
  // earlier steps that are due), `apply` changes the database, `model` makes the stored model say the same.
76
144
  export const STEPS = [
@@ -113,7 +181,15 @@ export const STEPS = [
113
181
  delete definitions[E('TransactionInputAssets')];
114
182
  for (const spec of TX_SEQ_TABLES) definitions[E(spec.to)] = image[E(spec.to)];
115
183
  const transactions = definitions[E('Transactions')];
116
- if (transactions?.elements) transactions.elements.txSeq = image[E('Transactions')].elements.txSeq;
184
+ const current = image[E('Transactions')].elements;
185
+ if (!transactions?.elements) return;
186
+ transactions.elements.txSeq = current.txSeq;
187
+ // the compositions into the rebuilt tables join on txSeq now; a stale join makes the
188
+ // deploy emit an empty statement for them
189
+ const rebuilt = new Set(TX_SEQ_TABLES.map(t => E(t.to)));
190
+ for (const [name, element] of Object.entries(current)) {
191
+ if (element.target && rebuilt.has(element.target)) transactions.elements[name] = element;
192
+ }
117
193
  },
118
194
  },
119
195
  {
@@ -191,6 +267,60 @@ export const STEPS = [
191
267
  delete definitions[E('TransactionInputs')]?.elements?.assets;
192
268
  },
193
269
  },
270
+ {
271
+ name: 'CardanoWalletJobs: one idempotency key per user across wallets and kinds',
272
+ async due(db) {
273
+ const columns = await uniqueColumns(db, T('CardanoWalletJobs'), WALLET_JOBS_DEDUP);
274
+ return columns !== null && columns.join(',') !== 'dedupkey';
275
+ },
276
+ async apply(tx) {
277
+ const table = T('CardanoWalletJobs');
278
+ await tx.run(releaseSharedClaimsSql(table));
279
+ if (tx.kind === 'postgres') {
280
+ await tx.run(`ALTER TABLE ${table} DROP CONSTRAINT ${WALLET_JOBS_DEDUP}`);
281
+ await tx.run(`ALTER TABLE ${table} ADD CONSTRAINT ${WALLET_JOBS_DEDUP} UNIQUE (dedupKey)`);
282
+ return;
283
+ }
284
+ // SQLite cannot change a table constraint: the table is rebuilt with the same rows
285
+ const rebuilt = `${table}_dedup_new`;
286
+ const rows = await count(tx, table);
287
+ const [stored] = await tx.run(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = '${table}'`);
288
+ const createSql = String(stored.sql).replace(/(CONSTRAINT\s+"?\w+_dedup"?\s+UNIQUE\s*)\([^)]*\)/i, '$1(dedupKey)');
289
+ if (createSql === stored.sql) throw new Error(`${table}: no constraint ${WALLET_JOBS_DEDUP} in its table definition`);
290
+ await tx.run(createSql.replace(new RegExp(`^(\\s*CREATE TABLE\\s+)"?${table}"?`, 'i'), `$1${rebuilt}`));
291
+ await tx.run(`INSERT INTO ${rebuilt} SELECT * FROM ${table}`);
292
+ const copied = await count(tx, rebuilt);
293
+ if (copied !== rows) throw new Error(`${table}: ${rows} rows, ${copied} copied`);
294
+ await tx.run(`DROP TABLE ${table}`);
295
+ await tx.run(`ALTER TABLE ${rebuilt} RENAME TO ${table}`);
296
+ },
297
+ model(definitions, image) {
298
+ const stored = definitions[E('CardanoWalletJobs')];
299
+ if (stored) stored['@assert.unique.dedup'] = image[E('CardanoWalletJobs')]['@assert.unique.dedup'];
300
+ },
301
+ },
302
+ {
303
+ name: 'CardanoAgentGrants: allow lists name Service.operation',
304
+ async due(db) {
305
+ if (!(await columnsOf(db, T('CardanoAgentGrants'))).has('allowedactions')) return false;
306
+ const rows = await db.run(`SELECT allowedActions AS actions FROM ${T('CardanoAgentGrants')}`);
307
+ const open = rows.filter(r => grantList(r.actions).some(name => !name.includes('.'))).length;
308
+ return open ? `${open} grants` : false;
309
+ },
310
+ async apply(tx, { model }) {
311
+ const byName = grantableByName(model);
312
+ const table = T('CardanoAgentGrants');
313
+ const update = tx.kind === 'postgres'
314
+ ? `UPDATE ${table} SET allowedActions = $1 WHERE ID = $2`
315
+ : `UPDATE ${table} SET allowedActions = ? WHERE ID = ?`;
316
+ for (const row of await tx.run(`SELECT ID AS id, allowedActions AS actions FROM ${table}`)) {
317
+ const list = grantList(row.actions);
318
+ if (!list.some(name => !name.includes('.'))) continue;
319
+ await tx.run(update, [JSON.stringify(qualifiedGrantList(list, byName)), row.id]);
320
+ }
321
+ },
322
+ model() {},
323
+ },
194
324
  ];
195
325
 
196
326
  /** Names of all views of the schema, the ones created last first. */
@@ -202,6 +332,17 @@ async function viewNames(db) {
202
332
  return rows.map(r => r.name);
203
333
  }
204
334
 
335
+ /** Database names of the views the models define, lower-cased. */
336
+ export function modelViewNames(...models) {
337
+ const names = new Set();
338
+ for (const model of models) {
339
+ for (const [name, def] of Object.entries(model?.definitions ?? {})) {
340
+ if (def.kind === 'entity' && isView(def)) names.add(name.replace(/\./g, '_').toLowerCase());
341
+ }
342
+ }
343
+ return names;
344
+ }
345
+
205
346
  async function hasModelTable(db) {
206
347
  const [found] = await db.run(db.kind === 'postgres'
207
348
  ? `SELECT 1 AS x FROM pg_tables WHERE tablename = 'cds_model' AND schemaname = current_schema()`
@@ -220,24 +361,47 @@ async function modelOfThisVersion(db) {
220
361
  if (!found) throw new Error(`the model has no table ${T(name)}`);
221
362
  return found;
222
363
  };
223
- return { image: cds.compile.to.sql.delta(model, options).afterImage, ddl };
364
+ return { model, options, image: cds.compile.to.sql.delta(model, options).afterImage, ddl };
224
365
  }
225
366
 
226
367
  const isView = (def) => Boolean(def.query || def.projection);
227
368
 
369
+ /** PostgreSQL columns of a table with length, precision and scale, by lower-cased name. */
370
+ async function columnSizes(db, table) {
371
+ const rows = await db.run(`SELECT column_name AS name, character_maximum_length AS length, numeric_precision AS precision, numeric_scale AS scale
372
+ FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = '${table.toLowerCase()}'`);
373
+ return new Map(rows.map(r => [String(r.name).toLowerCase(), r]));
374
+ }
375
+
376
+ /** `element` with the length, precision and scale its PostgreSQL column has. */
377
+ export function sizedAsStored(element, column) {
378
+ if (!column) return element;
379
+ const sized = { ...element };
380
+ if (element.type === 'cds.Decimal' && column.precision != null) {
381
+ sized.precision = Number(column.precision);
382
+ sized.scale = Number(column.scale ?? 0);
383
+ }
384
+ if (element.type === 'cds.String' && column.length != null) sized.length = Number(column.length);
385
+ return sized;
386
+ }
387
+
228
388
  // The model of this version cut down to what the database holds: its tables and their columns,
229
- // no views. The schema deploy then adds exactly what is missing.
389
+ // no views. On PostgreSQL the sizes are the stored ones, so the deploy widens what this version widened.
230
390
  export async function modelOfDatabase(db, image) {
231
391
  const definitions = {};
232
392
  for (const [name, def] of Object.entries(image.definitions)) {
233
393
  if (def.kind !== 'entity') { definitions[name] = def; continue; }
234
394
  if (isView(def)) continue;
235
- const columns = await columnsOf(db, name.replace(/\./g, '_'));
395
+ const table = name.replace(/\./g, '_');
396
+ const columns = await columnsOf(db, table);
236
397
  if (!columns.size) continue;
237
- const elements = Object.fromEntries(Object.entries(def.elements ?? {}).filter(([, element]) => {
398
+ const sizes = db.kind === 'postgres' ? await columnSizes(db, table) : new Map();
399
+ const elements = {};
400
+ for (const [elementName, element] of Object.entries(def.elements ?? {})) {
238
401
  const column = element['@cds.persistence.name'];
239
- return column === undefined || columns.has(String(column).toLowerCase());
240
- }));
402
+ if (column !== undefined && !columns.has(String(column).toLowerCase())) continue;
403
+ elements[elementName] = column === undefined ? element : sizedAsStored(element, sizes.get(String(column).toLowerCase()));
404
+ }
241
405
  definitions[name] = { ...def, elements };
242
406
  }
243
407
  return { ...image, definitions };
@@ -250,10 +414,33 @@ async function connected(db) {
250
414
  return await db.run('SELECT 1 AS x');
251
415
  } catch (err) {
252
416
  if (attempt === 15) throw err;
417
+ await new Promise(resolve => setTimeout(resolve, Math.min(500 * attempt, 5000)));
253
418
  }
254
419
  }
255
420
  }
256
421
 
422
+ // Statements of the deploy from `prior` to this version that render as nothing. @cap-js/postgres
423
+ // names a statement by the hash of its text, so two empty ones collide and the deploy fails.
424
+ // SQLite runs an empty statement as a no-op, so only PostgreSQL counts.
425
+ export function emptyDeltaStatements(model, options, prior) {
426
+ if (options.kind !== 'postgres') return 0;
427
+ const { drops, createsAndAlters } = cds.compile.to.sql.delta(model, options, prior);
428
+ return [...drops, ...createsAndAlters].filter(sql => !String(sql).trim()).length;
429
+ }
430
+
431
+ /** Refuses a stored model the deploy cannot take, before the deploy changes anything. */
432
+ export async function assertDeployable(db) {
433
+ if (db.kind !== 'postgres') return;
434
+ if (!(await hasModelTable(db))) return;
435
+ const prior = JSON.parse((await db.run('SELECT csn FROM cds_model'))[0].csn);
436
+ const { model, options } = await modelOfThisVersion(db);
437
+ const empty = emptyDeltaStatements(model, options, prior);
438
+ if (empty) {
439
+ throw new Error(`the deploy from the stored model (cds_model) would run ${empty} empty statements, which the database refuses. `
440
+ + 'The stored model holds a change the migration steps do not cover. Nothing was changed.');
441
+ }
442
+ }
443
+
257
444
  /** The steps the database still needs, with what `due` reported for each. */
258
445
  async function dueSteps(db) {
259
446
  const due = [];
@@ -268,7 +455,8 @@ async function dueSteps(db) {
268
455
  // returns the names of the steps it ran. A database without a stored model gets one here.
269
456
  // Whenever it changes something the views are gone afterwards; the deploy creates them.
270
457
  export async function migrateSchema(db, { dryRun = false, log = console.log } = {}) {
271
- if (db.kind !== 'postgres' && db.kind !== 'sqlite') return [];
458
+ if (db.kind === 'hana') throw new Error(HANA_UPGRADE);
459
+ if (db.kind !== 'postgres' && db.kind !== 'sqlite') throw new Error(`unsupported database kind ${db.kind}: PostgreSQL and SQLite are migrated`);
272
460
  await connected(db);
273
461
 
274
462
  const due = await dueSteps(db);
@@ -288,18 +476,20 @@ export async function migrateSchema(db, { dryRun = false, log = console.log } =
288
476
  const names = due.map(d => d.step.name);
289
477
  if (dryRun) { log('dry run: nothing changed'); return names; }
290
478
 
291
- const { image, ddl } = await modelOfThisVersion(db);
292
- const views = await viewNames(db);
479
+ const { model: current, options, image, ddl } = await modelOfThisVersion(db);
293
480
  await db.tx(async (tx) => {
294
481
  const started = Date.now();
295
482
  const done = (msg) => log(`[${Math.round((Date.now() - started) / 1000)}s] ${msg}`);
296
483
 
297
- for (const name of views) await tx.run(`DROP VIEW IF EXISTS "${name}"${db.kind === 'postgres' ? ' CASCADE' : ''}`);
484
+ const model = stored ? JSON.parse((await tx.run('SELECT csn FROM cds_model'))[0].csn) : null;
485
+ // only views of the models: any other view stays, and one that depends on ours makes the drop fail
486
+ const ours = modelViewNames(model, image);
487
+ const views = (await viewNames(tx)).filter(name => ours.has(String(name).toLowerCase()));
488
+ for (const name of views) await tx.run(`DROP VIEW IF EXISTS "${name}"`);
298
489
  done(`${views.length} views dropped`);
299
490
 
300
- const model = stored ? JSON.parse((await tx.run('SELECT csn FROM cds_model'))[0].csn) : null;
301
491
  for (const { step } of due) {
302
- await step.apply(tx, { ddl, log: done });
492
+ await step.apply(tx, { ddl, log: done, model: current });
303
493
  if (model) step.model(model.definitions, image.definitions);
304
494
  done(step.name);
305
495
  }
@@ -309,9 +499,14 @@ export async function migrateSchema(db, { dryRun = false, log = console.log } =
309
499
  for (const [name, def] of Object.entries(model.definitions)) {
310
500
  if (isView(def)) delete model.definitions[name];
311
501
  }
502
+ const empty = emptyDeltaStatements(current, options, model);
503
+ if (empty) throw new Error(`after the steps the deploy would run ${empty} empty statements; nothing was changed`);
312
504
  await tx.run(db.kind === 'postgres' ? 'UPDATE cds_model SET csn = $1' : 'UPDATE cds_model SET csn = ?', [JSON.stringify(model)]);
313
505
  } else {
314
- const csn = JSON.stringify(await modelOfDatabase(tx, image));
506
+ const adopted = await modelOfDatabase(tx, image);
507
+ const empty = emptyDeltaStatements(current, options, adopted);
508
+ if (empty) throw new Error(`for the stored model written from the tables the deploy would run ${empty} empty statements; nothing was changed`);
509
+ const csn = JSON.stringify(adopted);
315
510
  await tx.run(`CREATE TABLE cds_model (csn ${db.kind === 'postgres' ? 'TEXT' : 'CLOB'})`);
316
511
  await tx.run(db.kind === 'postgres' ? 'INSERT INTO cds_model VALUES ($1)' : 'INSERT INTO cds_model VALUES (?)', [csn]);
317
512
  }
@@ -322,7 +517,6 @@ export async function migrateSchema(db, { dryRun = false, log = console.log } =
322
517
 
323
518
  async function main() {
324
519
  const db = await cds.connect.to('db');
325
- if (db.kind !== 'postgres' && db.kind !== 'sqlite') throw new Error(`unsupported database kind ${db.kind}`);
326
520
  const dryRun = process.argv.includes('--dry-run');
327
521
  const ran = await migrateSchema(db, { dryRun });
328
522
  if (!ran.length) console.log('The schema needs no migration.');
@@ -6,7 +6,6 @@ export declare class BlockfrostBackend implements CardanoBackend, PaginatingBack
6
6
  readonly name = "blockfrost";
7
7
  private api;
8
8
  private network;
9
- private timeoutMs;
10
9
  constructor(network: Network, timeoutMs: number, projectId: string, customBackend?: string);
11
10
  init(): Promise<boolean>;
12
11
  /** Network information (supply, stake). */
@@ -32,7 +31,7 @@ export declare class BlockfrostBackend implements CardanoBackend, PaginatingBack
32
31
  getAssetHistory(unit: string, limit?: number): Promise<AssetHistoryEntry[]>;
33
32
  /** DRep by id (bech32). */
34
33
  getDrep(drepId: string): Promise<DrepData>;
35
- /** Account by stake address (bech32), with all its addresses and their UTxOs. */
34
+ /** Account by stake address (bech32) with the addresses under it, not their UTxOs. */
36
35
  getAccount(stakeAddress: string): Promise<AccountData>;
37
36
  /** Submit a signed transaction (CBOR hex); returns the tx hash. */
38
37
  submitTransaction(signedTxCbor: string): Promise<string>;
@@ -50,7 +49,6 @@ export declare class BlockfrostBackend implements CardanoBackend, PaginatingBack
50
49
  private static readonly MAX_CONCURRENT;
51
50
  /** Most recent tx hashes of an address (no details). */
52
51
  getAddressTransactionHashes(address: string, limit: number): Promise<string[]>;
53
- /** Transactions by hash (map hash -> Transaction); no batch endpoint, so concurrency-limited parallel calls. */
54
52
  getTransactionsBatch(txHashes: string[]): Promise<Map<string, Transaction>>;
55
53
  /** Map a Blockfrost block summary (blocks()/blocksNext()) to BlockData. */
56
54
  private toBlockData;
@@ -59,6 +57,6 @@ export declare class BlockfrostBackend implements CardanoBackend, PaginatingBack
59
57
  /** Up to `count` blocks immediately following `afterHash`, in ascending chain order. */
60
58
  getNextBlocks(afterHash: string, count: number): Promise<BlockData[]>;
61
59
  /** Full transaction list of a block in block order (hashes from blocksTxsAll, details batched). */
62
- getBlockTransactions(blockHash: string): Promise<Transaction[]>;
60
+ getBlockTransactions(blockHash: string, txCount?: number): Promise<Transaction[]>;
63
61
  }
64
62
  //# sourceMappingURL=blockfrost-backend.d.ts.map
@@ -4,15 +4,25 @@ exports.BlockfrostBackend = void 0;
4
4
  const blockfrost_js_1 = require("@blockfrost/blockfrost-js");
5
5
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
6
6
  const errors_1 = require("../../utils/errors");
7
+ const collections_1 = require("../../utils/collections");
8
+ const call_signal_1 = require("./call-signal");
7
9
  const mappers_1 = require("../../utils/mappers");
8
10
  const pool_metadata_1 = require("../pool-metadata");
9
11
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
12
+ // The client fails over to the next backend itself, so the SDK does not retry. A retry would run
13
+ // past the client's timeout and repeat a request the client has given up.
14
+ const NO_RETRY = {
15
+ limit: 0,
16
+ methods: [],
17
+ statusCodes: [],
18
+ errorCodes: [],
19
+ calculateDelay: () => 0,
20
+ };
10
21
  /** CardanoBackend + PaginatingBackend implementation on the Blockfrost API SDK. */
11
22
  class BlockfrostBackend {
12
23
  name = 'blockfrost';
13
24
  api;
14
25
  network;
15
- timeoutMs;
16
26
  constructor(network, timeoutMs, projectId, customBackend) {
17
27
  if (!projectId && !customBackend) {
18
28
  throw new errors_1.BackendInitError('blockfrost', new Error('Either projectId (BLOCKFROST_API_KEY) or customBackend (BLOCKFROST_CUSTOM_BACKEND) is required'));
@@ -20,16 +30,17 @@ class BlockfrostBackend {
20
30
  // Self-hosted Blockfrost-compatible servers reject an empty project_id header,
21
31
  // even without authentication, so a placeholder is sent.
22
32
  const effectiveProjectId = projectId || 'self-hosted';
33
+ // the SDK builds its HTTP client in the constructor, so timeout and retries are set here
23
34
  this.api = new blockfrost_js_1.BlockFrostAPI({
24
35
  projectId: effectiveProjectId,
25
36
  network,
37
+ requestTimeout: timeoutMs,
38
+ retrySettings: NO_RETRY,
26
39
  ...(customBackend ? { customBackend } : {}),
27
40
  });
28
41
  this.network = network;
29
- this.timeoutMs = timeoutMs;
30
42
  }
31
43
  async init() {
32
- this.api.options.requestTimeout = this.timeoutMs;
33
44
  // Test connection by fetching latest block
34
45
  try {
35
46
  await this.api.blocksLatest();
@@ -218,7 +229,8 @@ class BlockfrostBackend {
218
229
  liveSaturation: poolData.live_saturation,
219
230
  activeStake: poolData.active_stake || '0',
220
231
  activeSize: poolData.active_size,
221
- pledge: poolData.live_pledge || '0',
232
+ // the pledge of the certificate, as Koios and Ogmios report it; live_pledge is the owners' stake
233
+ pledge: poolData.declared_pledge || '0',
222
234
  margin: poolData.margin_cost,
223
235
  fixedCost: poolData.fixed_cost || '0',
224
236
  rewardAccount: poolData.reward_account,
@@ -263,25 +275,17 @@ class BlockfrostBackend {
263
275
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
264
276
  const count = Math.min(Math.max(1, limit), 100);
265
277
  const data = await this.api.assetsHistory(unit, { order: 'desc', count });
266
- // Backfill block metadata via concurrent tx fetches
267
- const concurrent = BlockfrostBackend.MAX_CONCURRENT;
268
278
  const blockMetaByTx = new Map();
269
- for (let i = 0; i < data.length; i += concurrent) {
270
- const chunk = data.slice(i, i + concurrent);
271
- const chunkResults = await Promise.allSettled(chunk.map(entry => this.api.txs(entry.tx_hash)));
272
- chunk.forEach((entry, idx) => {
273
- const r = chunkResults[idx];
274
- if (r.status === 'fulfilled') {
275
- blockMetaByTx.set(entry.tx_hash, {
276
- blockTime: typeof r.value.block_time === 'number' ? r.value.block_time : null,
277
- blockHeight: typeof r.value.block_height === 'number' ? r.value.block_height : null,
278
- });
279
+ const results = await (0, collections_1.settleInBatches)(data, BlockfrostBackend.MAX_CONCURRENT, entry => this.api.txs(entry.tx_hash), (0, call_signal_1.callSignal)());
280
+ data.forEach((entry, idx) => {
281
+ const r = results[idx];
282
+ blockMetaByTx.set(entry.tx_hash, r.status === 'fulfilled'
283
+ ? {
284
+ blockTime: typeof r.value.block_time === 'number' ? r.value.block_time : null,
285
+ blockHeight: typeof r.value.block_height === 'number' ? r.value.block_height : null,
279
286
  }
280
- else {
281
- blockMetaByTx.set(entry.tx_hash, { blockTime: null, blockHeight: null });
282
- }
283
- });
284
- }
287
+ : { blockTime: null, blockHeight: null });
288
+ });
285
289
  return data.map(entry => {
286
290
  const meta = blockMetaByTx.get(entry.tx_hash) ?? { blockTime: null, blockHeight: null };
287
291
  return {
@@ -310,19 +314,12 @@ class BlockfrostBackend {
310
314
  };
311
315
  }, this.name);
312
316
  }
313
- /** Account by stake address (bech32), with all its addresses and their UTxOs. */
317
+ /** Account by stake address (bech32) with the addresses under it, not their UTxOs. */
314
318
  async getAccount(stakeAddress) {
315
319
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
316
320
  const accountData = await this.api.accounts(stakeAddress);
317
321
  // *All variant paginates internally (plain accountsAddresses caps at 100 entries)
318
- const addressData = await this.api.accountsAddressesAll(stakeAddress);
319
- const addresses = [];
320
- const concurrent = BlockfrostBackend.MAX_CONCURRENT;
321
- for (let i = 0; i < addressData.length; i += concurrent) {
322
- const chunk = addressData.slice(i, i + concurrent);
323
- const chunkResults = await Promise.all(chunk.map(a => this.getAddress(a.address)));
324
- addresses.push(...chunkResults);
325
- }
322
+ const addresses = (await this.api.accountsAddressesAll(stakeAddress)).map(a => a.address);
326
323
  return {
327
324
  stakeaddress: accountData.stake_address,
328
325
  // `active` is the delegation state; registration lives in `registered`
@@ -344,8 +341,17 @@ class BlockfrostBackend {
344
341
  async submitTransaction(signedTxCbor) {
345
342
  const txBytes = Buffer.from(signedTxCbor, "hex");
346
343
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
347
- const txHash = await this.api.txSubmit(txBytes);
348
- return txHash;
344
+ try {
345
+ return await this.api.txSubmit(txBytes);
346
+ }
347
+ catch (err) {
348
+ // a 400 carries the node's rejection; the submit API forwards it in the body
349
+ if ((0, errors_1.getErrorStatus)(err) === 400) {
350
+ const e = err;
351
+ throw (0, errors_1.submitRejection)((0, errors_1.nodeRejectionReason)(e.body ?? e.message ?? ''), this.name, err);
352
+ }
353
+ throw err;
354
+ }
349
355
  }, this.name);
350
356
  }
351
357
  /** Protocol parameters of the latest epoch. */
@@ -443,7 +449,8 @@ class BlockfrostBackend {
443
449
  return await (0, backend_request_handler_1.handleBackendRequest)(async () => {
444
450
  const utxos = await this.api.txsUtxos(txHash);
445
451
  const out = utxos?.outputs?.find(o => o.output_index === outputIndex);
446
- if (!out)
452
+ // consumed_by_tx is always null on a collateral output, so its state is unknown here
453
+ if (!out || out.collateral === true)
447
454
  return false;
448
455
  // Blockfrost servers before 0.1.59 omit consumed_by_tx. Without it unspent cannot be
449
456
  // proven, so the router must fall through to another backend.
@@ -474,17 +481,17 @@ class BlockfrostBackend {
474
481
  return txs.map(tx => tx.tx_hash);
475
482
  }, this.name);
476
483
  }
477
- /** Transactions by hash (map hash -> Transaction); no batch endpoint, so concurrency-limited parallel calls. */
484
+ // Transactions by hash, at most MAX_CONCURRENT calls at once. A hash Blockfrost does not know is
485
+ // left out, as Koios does; any other failure fails the batch.
478
486
  async getTransactionsBatch(txHashes) {
479
487
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
480
488
  const result = new Map();
481
- const concurrent = BlockfrostBackend.MAX_CONCURRENT;
482
- for (let i = 0; i < txHashes.length; i += concurrent) {
483
- const chunk = txHashes.slice(i, i + concurrent);
484
- const txs = await Promise.all(chunk.map(h => this.getTransaction(h)));
485
- for (const tx of txs) {
486
- result.set(tx.hash, tx);
487
- }
489
+ const settled = await (0, collections_1.settleInBatches)(txHashes, BlockfrostBackend.MAX_CONCURRENT, h => this.getTransaction(h), (0, call_signal_1.callSignal)());
490
+ for (const r of settled) {
491
+ if (r.status === 'fulfilled')
492
+ result.set(r.value.hash, r.value);
493
+ else if (!(r.reason instanceof errors_1.NotFoundError))
494
+ throw r.reason;
488
495
  }
489
496
  return result;
490
497
  }, this.name);
@@ -505,6 +512,7 @@ class BlockfrostBackend {
505
512
  size: b.size,
506
513
  txCount: b.tx_count,
507
514
  fees: b.fees,
515
+ previousHash: b.previous_block,
508
516
  };
509
517
  }
510
518
  /** Block by height; Blockfrost's `blocks` endpoint accepts a height as well as a hash. */
@@ -532,15 +540,23 @@ class BlockfrostBackend {
532
540
  }, this.name);
533
541
  }
534
542
  /** Full transaction list of a block in block order (hashes from blocksTxsAll, details batched). */
535
- async getBlockTransactions(blockHash) {
543
+ async getBlockTransactions(blockHash, txCount) {
536
544
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
545
+ if (txCount === 0)
546
+ return [];
537
547
  const hashes = await this.api.blocksTxsAll(blockHash);
548
+ // A short list, or a transaction the batch did not find, would store the block incomplete.
549
+ if (txCount !== undefined && hashes.length !== txCount) {
550
+ throw new errors_1.ProviderUnavailableError(`Incomplete transaction list for block ${blockHash}: ${hashes.length}/${txCount} transaction(s)`, this.name);
551
+ }
538
552
  if (!hashes.length)
539
553
  return [];
540
554
  const byHash = await this.getTransactionsBatch(hashes);
541
- return hashes
542
- .map(h => byHash.get(h))
543
- .filter((t) => t !== undefined);
555
+ const missing = hashes.filter(h => !byHash.has(h));
556
+ if (missing.length > 0) {
557
+ throw new errors_1.ProviderUnavailableError(`Incomplete transaction data for block ${blockHash}: ${missing.length}/${hashes.length} transaction(s) missing`, this.name);
558
+ }
559
+ return hashes.map(h => byHash.get(h));
544
560
  }, this.name);
545
561
  }
546
562
  }
@@ -0,0 +1,7 @@
1
+ /** Runs `fn` with `signal` as the signal of the backend call. */
2
+ export declare function withCallSignal<T>(signal: AbortSignal, fn: () => Promise<T>): Promise<T>;
3
+ /** Signal of the backend call in progress, if any. */
4
+ export declare function callSignal(): AbortSignal | undefined;
5
+ /** Throws the abort reason once the backend call in progress was given up. */
6
+ export declare function throwIfCallAborted(): void;
7
+ //# sourceMappingURL=call-signal.d.ts.map
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withCallSignal = withCallSignal;
4
+ exports.callSignal = callSignal;
5
+ exports.throwIfCallAborted = throwIfCallAborted;
6
+ const node_async_hooks_1 = require("node:async_hooks");
7
+ // The abort signal of the backend call in progress. CardanoClient aborts it when the call times
8
+ // out, so the HTTP requests and batch loops the call started stop as well.
9
+ const storage = new node_async_hooks_1.AsyncLocalStorage();
10
+ /** Runs `fn` with `signal` as the signal of the backend call. */
11
+ function withCallSignal(signal, fn) {
12
+ return storage.run(signal, fn);
13
+ }
14
+ /** Signal of the backend call in progress, if any. */
15
+ function callSignal() {
16
+ return storage.getStore();
17
+ }
18
+ /** Throws the abort reason once the backend call in progress was given up. */
19
+ function throwIfCallAborted() {
20
+ callSignal()?.throwIfAborted();
21
+ }
22
+ //# sourceMappingURL=call-signal.js.map
@@ -49,6 +49,8 @@ export interface CardanoBackend {
49
49
  getTransactionsBatch?(txHashes: string[]): Promise<Map<string, Transaction>>;
50
50
  /** UTxOs of every address with this payment credential (56 hex chars), each with its address. */
51
51
  getCredentialUtxos?(credHash: string): Promise<UTxO[]>;
52
+ /** Whether a stake address is registered, as the backend itself decides; null = it cannot tell. */
53
+ isRewardAccountRegistered?(stakeAddress: string): Promise<boolean | null>;
52
54
  }
53
55
  /** Backend that can evaluate script execution units (Ogmios). */
54
56
  export interface EvaluatingBackend extends CardanoBackend {
@@ -67,8 +69,8 @@ export interface ChainPoint {
67
69
  export interface ChainSyncCallbacks {
68
70
  /** A new block with all its transactions extends the chain. `tip` is the node's tip when known. */
69
71
  rollForward(block: BlockData, txs: Transaction[], tip?: ChainPoint): Promise<void>;
70
- /** The chain rolled back to `point` (or to genesis). All blocks after it are abandoned. */
71
- rollBackward(point: ChainPoint | 'origin'): Promise<void>;
72
+ /** The chain rolled back to `point` (or to genesis). All blocks after it are abandoned. `tip` is the node's tip when known. */
73
+ rollBackward(point: ChainPoint | 'origin', tip?: ChainPoint): Promise<void>;
72
74
  /** A handler error stalled the stream. The consumer should record it and restart the stream. */
73
75
  onError?(err: unknown): Promise<void>;
74
76
  }
@@ -102,7 +104,8 @@ export interface PaginatingBackend extends CardanoBackend {
102
104
  /** Up to `count` blocks after `afterHash` in chain order. `afterHeight` saves a height lookup. */
103
105
  getNextBlocks(afterHash: string, count: number, afterHeight?: number): Promise<BlockData[]>;
104
106
  /** Fetch the full transaction list of a block, in block order. */
105
- getBlockTransactions(blockHash: string): Promise<Transaction[]>;
107
+ /** `txCount` from the block header, when known: 0 answers without a request. */
108
+ getBlockTransactions(blockHash: string, txCount?: number): Promise<Transaction[]>;
106
109
  }
107
110
  /** Type guard: can this backend be walked forward by pagination? */
108
111
  export declare function isPaginatingBackend(backend: CardanoBackend): backend is PaginatingBackend;