@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.
- package/@cds-models/CardanoBackendService/index.d.ts +14 -3
- package/@cds-models/CardanoBackendService/index.js +1 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
- package/@cds-models/CardanoIndexerService/index.js +10 -0
- package/@cds-models/CardanoODataService/index.d.ts +3 -0
- package/@cds-models/CardanoSignService/index.d.ts +13 -0
- package/@cds-models/CardanoSignService/index.js +1 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
- package/@cds-models/CardanoTransactionService/index.js +1 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
- package/@cds-models/CardanoWorkerService/index.js +2 -0
- package/@cds-models/index.d.ts +13 -3
- package/@cds-models/index.js +4 -3
- package/@cds-models/odatano/cardano/index.d.ts +14 -0
- package/README.md +45 -149
- package/db/schema.cds +63 -10
- package/db/types.cds +10 -0
- package/package.json +7 -44
- package/scripts/deploy-schema.mjs +113 -0
- package/scripts/migrate-schema.mjs +209 -15
- package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
- package/srv/blockchain/backends/blockfrost-backend.js +61 -45
- package/srv/blockchain/backends/call-signal.d.ts +7 -0
- package/srv/blockchain/backends/call-signal.js +22 -0
- package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
- package/srv/blockchain/backends/koios-backend.d.ts +9 -6
- package/srv/blockchain/backends/koios-backend.js +145 -207
- package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
- package/srv/blockchain/backends/odatano-backend.js +51 -9
- package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
- package/srv/blockchain/backends/ogmios-backend.js +82 -48
- package/srv/blockchain/cardano-client.d.ts +15 -5
- package/srv/blockchain/cardano-client.js +143 -71
- package/srv/blockchain/cardano-indexer.d.ts +27 -16
- package/srv/blockchain/cardano-indexer.js +223 -102
- package/srv/blockchain/circuit-breaker.d.ts +1 -0
- package/srv/blockchain/circuit-breaker.js +6 -0
- package/srv/blockchain/crawler/account-snapshots.js +22 -2
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
- package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
- package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
- package/srv/blockchain/crawler/certificate-backfill.js +15 -3
- package/srv/blockchain/crawler/crawler.d.ts +22 -1
- package/srv/blockchain/crawler/crawler.js +223 -24
- package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/credential-backfill.js +43 -66
- package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
- package/srv/blockchain/crawler/input-asset-copies.js +17 -27
- package/srv/blockchain/crawler/key-pages.d.ts +12 -0
- package/srv/blockchain/crawler/key-pages.js +48 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
- package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
- package/srv/blockchain/crawler/sync-state.d.ts +5 -1
- package/srv/blockchain/crawler/sync-state.js +63 -106
- package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
- package/srv/blockchain/crawler/transaction-backfill.js +6 -13
- package/srv/blockchain/crawler/utxo-set-import.js +2 -2
- package/srv/blockchain/crawler/window-plan.d.ts +31 -0
- package/srv/blockchain/crawler/window-plan.js +59 -0
- package/srv/blockchain/ledger-state.d.ts +2 -2
- package/srv/blockchain/ledger-state.js +139 -37
- package/srv/blockchain/signing/external-signer.js +5 -5
- package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
- package/srv/blockchain/signing/failed-recheck.js +135 -0
- package/srv/blockchain/signing/landing-proof.d.ts +60 -0
- package/srv/blockchain/signing/landing-proof.js +224 -0
- package/srv/blockchain/signing/signature-verifier.js +10 -13
- package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
- package/srv/blockchain/signing/submission-finalizer.js +90 -29
- package/srv/blockchain/stored-chain.d.ts +1 -2
- package/srv/blockchain/stored-chain.js +36 -15
- package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
- package/srv/blockchain/transaction-presence.d.ts +8 -1
- package/srv/blockchain/transaction-presence.js +12 -12
- package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
- package/srv/blockchain/wallet-worker/build-request.js +35 -365
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
- package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
- package/srv/blockchain/wallet-worker/invalidation.js +128 -0
- package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
- package/srv/blockchain/wallet-worker/job-store.js +107 -80
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
- package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
- package/srv/cardano-agent-service.cds +1 -1
- package/srv/cardano-agent-service.js +8 -0
- package/srv/cardano-backend-service.cds +4 -1
- package/srv/cardano-backend-service.js +26 -9
- package/srv/cardano-indexer-service.cds +448 -387
- package/srv/cardano-indexer-service.js +226 -281
- package/srv/cardano-service.cds +7 -5
- package/srv/cardano-service.js +404 -69
- package/srv/cardano-sign-service.cds +11 -1
- package/srv/cardano-sign-service.js +161 -108
- package/srv/cardano-tx-service.cds +15 -4
- package/srv/cardano-tx-service.js +105 -604
- package/srv/cardano-worker-service.cds +25 -2
- package/srv/cardano-worker-service.js +56 -4
- package/srv/config.d.ts +4 -0
- package/srv/config.js +10 -0
- package/srv/server.js +5 -7
- package/srv/utils/agent-access.d.ts +4 -2
- package/srv/utils/agent-access.js +26 -7
- package/srv/utils/agent-grants.d.ts +1 -1
- package/srv/utils/agent-grants.js +7 -8
- package/srv/utils/agent-token-auth.js +45 -5
- package/srv/utils/build-request.d.ts +52 -0
- package/srv/utils/build-request.js +487 -0
- package/srv/utils/collections.d.ts +1 -0
- package/srv/utils/collections.js +11 -0
- package/srv/utils/const.d.ts +10 -2
- package/srv/utils/const.js +13 -6
- package/srv/utils/crypto.js +5 -4
- package/srv/utils/db-indexes.d.ts +5 -1
- package/srv/utils/db-indexes.js +79 -14
- package/srv/utils/db-kind.d.ts +23 -0
- package/srv/utils/db-kind.js +42 -0
- package/srv/utils/detached-run.d.ts +41 -0
- package/srv/utils/detached-run.js +101 -0
- package/srv/utils/epoch-slots.d.ts +1 -0
- package/srv/utils/epoch-slots.js +7 -0
- package/srv/utils/error-codes.d.ts +4 -0
- package/srv/utils/error-codes.js +4 -0
- package/srv/utils/errors.d.ts +10 -1
- package/srv/utils/errors.js +51 -9
- package/srv/utils/lease.d.ts +20 -0
- package/srv/utils/lease.js +62 -0
- package/srv/utils/mappers.d.ts +9 -0
- package/srv/utils/mappers.js +57 -67
- package/srv/utils/navigation.d.ts +17 -0
- package/srv/utils/navigation.js +52 -0
- package/srv/utils/network-context.d.ts +0 -1
- package/srv/utils/network-context.js +8 -3
- package/srv/utils/pg-inline-json.js +3 -3
- package/srv/utils/pg-order-nulls.js +3 -3
- package/srv/utils/resolution.d.ts +13 -0
- package/srv/utils/resolution.js +47 -0
- package/srv/utils/row-values.d.ts +7 -0
- package/srv/utils/row-values.js +27 -0
- package/srv/utils/tx-build-helper.d.ts +15 -0
- package/srv/utils/tx-build-helper.js +28 -13
- package/srv/utils/types.d.ts +35 -43
- package/srv/utils/types.js +1 -17
- package/srv/utils/validators.d.ts +2 -2
- package/srv/utils/validators.js +14 -25
package/srv/utils/db-indexes.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.DROPPED_DB_INDEXES = exports.DB_INDEXES = void 0;
|
|
6
|
+
exports.INDEX_UNLOCK_STATEMENT = exports.INDEX_LOCK_STATEMENT = exports.INVALID_INDEXES_STATEMENT = exports.DROPPED_DB_INDEXES = exports.DB_INDEXES = void 0;
|
|
7
7
|
exports.indexStatement = indexStatement;
|
|
8
8
|
exports.ensureDbIndexes = ensureDbIndexes;
|
|
9
9
|
// Secondary indexes the CDS model cannot declare, created at start. Temporal keys start with validFrom,
|
|
@@ -42,6 +42,13 @@ exports.DB_INDEXES = Object.freeze([
|
|
|
42
42
|
{ name: 'odatano_cardano_addressutxos_address', table: 'odatano_cardano_AddressUTxOs', columns: 'address_address' },
|
|
43
43
|
{ name: 'odatano_cardano_addressassets_address', table: 'odatano_cardano_AddressAssets', columns: 'address_address' },
|
|
44
44
|
{ name: 'odatano_cardano_utxoassets_address', table: 'odatano_cardano_UTxOAssets', columns: 'utxo_address_address' },
|
|
45
|
+
// rollback `hash in` / `utxo_hash in`: the keys start with validFrom and the address
|
|
46
|
+
{ name: 'odatano_cardano_addressutxos_hash', table: 'odatano_cardano_AddressUTxOs', columns: 'hash' },
|
|
47
|
+
{ name: 'odatano_cardano_utxoassets_hash', table: 'odatano_cardano_UTxOAssets', columns: 'utxo_hash' },
|
|
48
|
+
// rollback `snapshotSlot >`: the keys start with the epoch
|
|
49
|
+
{ name: 'odatano_cardano_poolepochsnapshots_slot', table: 'odatano_cardano_PoolEpochSnapshots', columns: 'snapshotSlot' },
|
|
50
|
+
{ name: 'odatano_cardano_drepepochsnapshots_slot', table: 'odatano_cardano_DrepEpochSnapshots', columns: 'snapshotSlot' },
|
|
51
|
+
{ name: 'odatano_cardano_epochledgersnapshots_slot', table: 'odatano_cardano_EpochLedgerSnapshots', columns: 'snapshotSlot' },
|
|
45
52
|
{ name: 'odatano_cardano_addresstransactions_tx', table: 'odatano_cardano_AddressTransactions', columns: 'tx_hash' },
|
|
46
53
|
{ name: 'odatano_cardano_accounts_stake', table: 'odatano_cardano_Accounts', columns: 'stakeAddress' },
|
|
47
54
|
{ name: 'odatano_cardano_pools_poolid', table: 'odatano_cardano_Pools', columns: 'poolId' },
|
|
@@ -83,9 +90,35 @@ exports.DROPPED_DB_INDEXES = Object.freeze([
|
|
|
83
90
|
]);
|
|
84
91
|
/** The statement for one entry; exported so tests pin the shape. */
|
|
85
92
|
function indexStatement(spec, kind = 'sqlite') {
|
|
86
|
-
|
|
87
|
-
|
|
93
|
+
if (kind !== 'postgres')
|
|
94
|
+
return `CREATE INDEX IF NOT EXISTS ${spec.name} ON ${spec.table} (${spec.columns})`;
|
|
95
|
+
// CONCURRENTLY keeps the table writable while a large index builds
|
|
96
|
+
return `CREATE INDEX CONCURRENTLY IF NOT EXISTS ${spec.name} ON ${spec.table} (${spec.postgres ?? spec.columns})`;
|
|
88
97
|
}
|
|
98
|
+
// PostgreSQL builds an index CONCURRENTLY only outside a transaction, and every statement of the
|
|
99
|
+
// service runs inside one. A connection from the service's own factory runs it outside.
|
|
100
|
+
async function withOwnConnection(db, fn) {
|
|
101
|
+
const factory = db.factory;
|
|
102
|
+
if (!factory)
|
|
103
|
+
throw new Error('the PostgreSQL service has no connection factory');
|
|
104
|
+
const dbc = await factory.create();
|
|
105
|
+
try {
|
|
106
|
+
const schema = db.options?.credentials?.schema;
|
|
107
|
+
if (schema)
|
|
108
|
+
await dbc.query(`SET search_path TO "${schema.replace(/"/g, '""')}", public`);
|
|
109
|
+
return await fn(async (sql, params) => (await dbc.query(sql, params)).rows);
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
await factory.destroy(dbc);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** Names of our indexes in this schema that are invalid; only a failed concurrent build leaves one. */
|
|
116
|
+
exports.INVALID_INDEXES_STATEMENT = 'SELECT c.relname AS name FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid JOIN pg_namespace n ON n.oid = c.relnamespace ' +
|
|
117
|
+
'WHERE NOT i.indisvalid AND n.nspname = current_schema() AND c.relname = ANY($1)';
|
|
118
|
+
// One instance at a time builds the indexes. An index another instance is still building is
|
|
119
|
+
// invalid too, so without this lock a second start would drop it and kill that build.
|
|
120
|
+
exports.INDEX_LOCK_STATEMENT = "SELECT pg_try_advisory_lock(hashtext('odatano_db_indexes.' || current_schema())) AS locked";
|
|
121
|
+
exports.INDEX_UNLOCK_STATEMENT = "SELECT pg_advisory_unlock(hashtext('odatano_db_indexes.' || current_schema()))";
|
|
89
122
|
/** Creates every missing index; a failing statement is logged and skipped, the others still run. */
|
|
90
123
|
async function ensureDbIndexes(runner = cds_1.default.db) {
|
|
91
124
|
const ensured = [];
|
|
@@ -99,19 +132,51 @@ async function ensureDbIndexes(runner = cds_1.default.db) {
|
|
|
99
132
|
logger.info('HANA: secondary indexes not created (column store, no IF NOT EXISTS)');
|
|
100
133
|
return { ensured, failed };
|
|
101
134
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
135
|
+
const ensure = async (run) => {
|
|
136
|
+
const concurrently = kind === 'postgres' ? 'CONCURRENTLY ' : '';
|
|
137
|
+
if (kind === 'postgres') {
|
|
138
|
+
const invalid = await run(exports.INVALID_INDEXES_STATEMENT, [exports.DB_INDEXES.map(s => s.name)]);
|
|
139
|
+
for (const { name } of invalid ?? []) {
|
|
140
|
+
logger.warn(`index ${name} is invalid after an interrupted build; rebuilding it`);
|
|
141
|
+
await run(`DROP INDEX CONCURRENTLY IF EXISTS ${name}`)
|
|
142
|
+
.catch((err) => logger.warn(`invalid index ${name} not dropped: ${String(err?.message ?? err)}`));
|
|
143
|
+
}
|
|
110
144
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
145
|
+
for (const name of exports.DROPPED_DB_INDEXES) {
|
|
146
|
+
await run(`DROP INDEX ${concurrently}IF EXISTS ${name}`)
|
|
147
|
+
.catch((err) => logger.warn(`index ${name} not dropped: ${String(err?.message ?? err)}`));
|
|
114
148
|
}
|
|
149
|
+
for (const spec of exports.DB_INDEXES) {
|
|
150
|
+
try {
|
|
151
|
+
await run(indexStatement(spec, kind));
|
|
152
|
+
ensured.push(spec.name);
|
|
153
|
+
}
|
|
154
|
+
catch (err) {
|
|
155
|
+
failed.push(spec.name);
|
|
156
|
+
logger.warn(`index ${spec.name} on ${spec.table} not ensured: ${String(err?.message ?? err)}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
if (kind === 'postgres') {
|
|
161
|
+
const skipped = await withOwnConnection(runner, async (run) => {
|
|
162
|
+
const [lock] = await run(exports.INDEX_LOCK_STATEMENT);
|
|
163
|
+
if (!lock?.locked)
|
|
164
|
+
return true;
|
|
165
|
+
try {
|
|
166
|
+
await ensure(run);
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
await run(exports.INDEX_UNLOCK_STATEMENT).catch(() => undefined);
|
|
170
|
+
}
|
|
171
|
+
return false;
|
|
172
|
+
});
|
|
173
|
+
if (skipped) {
|
|
174
|
+
logger.info('another instance is building the indexes; skipped here');
|
|
175
|
+
return { ensured, failed };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
await ensure((sql, params) => runner.run(sql, params));
|
|
115
180
|
}
|
|
116
181
|
if (failed.length === 0)
|
|
117
182
|
logger.info(`${ensured.length} indexes ensured`);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Kind of the connected database; '' before it connects. */
|
|
2
|
+
export declare function connectedDbKind(): string;
|
|
3
|
+
/** Kind the configuration names, known before the database connects. */
|
|
4
|
+
export declare function configuredDbKind(): string;
|
|
5
|
+
/** Dialect of the hand-written bulk statements. */
|
|
6
|
+
export type BulkSqlKind = 'postgres' | 'sqlite';
|
|
7
|
+
/** The bulk dialect of `kind`; null for a database the statements are not written for. */
|
|
8
|
+
export declare function bulkSqlKind(kind?: string): BulkSqlKind | null;
|
|
9
|
+
/** A column of a JSON fill record and its PostgreSQL type. */
|
|
10
|
+
export type FillColumn = [column: string, pgType: string];
|
|
11
|
+
export interface JsonFillSpec {
|
|
12
|
+
table: string;
|
|
13
|
+
/** Key columns, matched between the table row `t` and the record `v`. */
|
|
14
|
+
keys: FillColumn[];
|
|
15
|
+
/** Further columns the records carry. */
|
|
16
|
+
values: FillColumn[];
|
|
17
|
+
/** SET list; refers to the table as `t` and to the record as `v`. */
|
|
18
|
+
set: string;
|
|
19
|
+
/** Extra condition on `t`. */
|
|
20
|
+
where?: string;
|
|
21
|
+
}
|
|
22
|
+
export declare function jsonFillUpdate(kind: BulkSqlKind, spec: JsonFillSpec): string;
|
|
23
|
+
//# sourceMappingURL=db-kind.d.ts.map
|
|
@@ -0,0 +1,42 @@
|
|
|
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.connectedDbKind = connectedDbKind;
|
|
7
|
+
exports.configuredDbKind = configuredDbKind;
|
|
8
|
+
exports.bulkSqlKind = bulkSqlKind;
|
|
9
|
+
exports.jsonFillUpdate = jsonFillUpdate;
|
|
10
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
11
|
+
/** Kind of the connected database; '' before it connects. */
|
|
12
|
+
function connectedDbKind() {
|
|
13
|
+
return cds_1.default.db?.kind ?? '';
|
|
14
|
+
}
|
|
15
|
+
/** Kind the configuration names, known before the database connects. */
|
|
16
|
+
function configuredDbKind() {
|
|
17
|
+
const db = cds_1.default.env.requires?.db;
|
|
18
|
+
return typeof db?.kind === 'string' ? db.kind : '';
|
|
19
|
+
}
|
|
20
|
+
/** The bulk dialect of `kind`; null for a database the statements are not written for. */
|
|
21
|
+
function bulkSqlKind(kind = connectedDbKind()) {
|
|
22
|
+
if (kind === 'postgres')
|
|
23
|
+
return 'postgres';
|
|
24
|
+
if (kind === 'sqlite' || kind === 'better-sqlite')
|
|
25
|
+
return 'sqlite';
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
// One UPDATE that joins a JSON array of records on the key, bound as the single parameter.
|
|
29
|
+
// The record fields are the column names in lower case.
|
|
30
|
+
function jsonFillUpdate(kind, spec) {
|
|
31
|
+
const columns = [...spec.keys, ...spec.values];
|
|
32
|
+
const extra = spec.where ? ` AND ${spec.where}` : '';
|
|
33
|
+
if (kind === 'postgres') {
|
|
34
|
+
const record = columns.map(([c, type]) => `${c.toLowerCase()} ${type}`).join(', ');
|
|
35
|
+
const match = spec.keys.map(([c]) => `t.${c} = v.${c.toLowerCase()}`).join(' AND ');
|
|
36
|
+
return `UPDATE ${spec.table} AS t SET ${spec.set} FROM json_to_recordset($1::json) AS v(${record}) WHERE ${match}${extra}`;
|
|
37
|
+
}
|
|
38
|
+
const record = columns.map(([c]) => `json_extract(value, '$.${c.toLowerCase()}') AS ${c}`).join(', ');
|
|
39
|
+
const match = spec.keys.map(([c]) => `t.${c} = v.${c}`).join(' AND ');
|
|
40
|
+
return `UPDATE ${spec.table} AS t SET ${spec.set} FROM (SELECT ${record} FROM json_each(?)) AS v WHERE ${match}${extra}`;
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=db-kind.js.map
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** none: never started in this process. cancelled: stopped on request, the work done so far is kept. */
|
|
2
|
+
export type RunStatus = 'none' | 'running' | 'done' | 'failed' | 'cancelled';
|
|
3
|
+
export interface RunLifecycle {
|
|
4
|
+
status: RunStatus;
|
|
5
|
+
startedAt: string | null;
|
|
6
|
+
finishedAt: string | null;
|
|
7
|
+
error: string | null;
|
|
8
|
+
}
|
|
9
|
+
export interface RunControl<P> {
|
|
10
|
+
/** Records progress of this run. */
|
|
11
|
+
progress(p: Partial<P>): void;
|
|
12
|
+
/** True once the run was asked to stop. */
|
|
13
|
+
shouldStop(): boolean;
|
|
14
|
+
}
|
|
15
|
+
/** What a start hands back once its checks passed: the work, and the answer to the caller. */
|
|
16
|
+
export interface PreparedRun<P, A> {
|
|
17
|
+
initial?: Partial<P>;
|
|
18
|
+
run: (ctl: RunControl<P>) => Promise<Partial<P> | void>;
|
|
19
|
+
answer: A;
|
|
20
|
+
/** Name in the log line of a failure; default the run's own label. */
|
|
21
|
+
label?: string;
|
|
22
|
+
}
|
|
23
|
+
export declare class DetachedRun<P extends object> {
|
|
24
|
+
readonly label: string;
|
|
25
|
+
private readonly idle;
|
|
26
|
+
/** Fields shown as text, like the Int64 values of the other answers. */
|
|
27
|
+
private readonly textFields;
|
|
28
|
+
private state;
|
|
29
|
+
private stopRequested;
|
|
30
|
+
private readonly logger;
|
|
31
|
+
constructor(label: string, idle: P,
|
|
32
|
+
/** Fields shown as text, like the Int64 values of the other answers. */
|
|
33
|
+
textFields?: ReadonlyArray<keyof P>);
|
|
34
|
+
isBusy(): boolean;
|
|
35
|
+
/** The status fields of the last run; text fields as strings. */
|
|
36
|
+
snapshot(): Record<string, unknown>;
|
|
37
|
+
start<A>(prepare: () => Promise<PreparedRun<P, A>> | PreparedRun<P, A>): Promise<A>;
|
|
38
|
+
/** Asks a running run to stop at its next check. False when nothing runs. */
|
|
39
|
+
cancel(): boolean;
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=detached-run.d.ts.map
|
|
@@ -0,0 +1,101 @@
|
|
|
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.DetachedRun = void 0;
|
|
7
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
8
|
+
/** Longest error text a status keeps. */
|
|
9
|
+
const ERROR_TEXT_MAX = 500;
|
|
10
|
+
// One long maintenance run per kind and process, run detached from the request that started it.
|
|
11
|
+
// A start marks the run as running before its first await, so a second start sees it busy.
|
|
12
|
+
class DetachedRun {
|
|
13
|
+
label;
|
|
14
|
+
idle;
|
|
15
|
+
textFields;
|
|
16
|
+
state;
|
|
17
|
+
stopRequested = false;
|
|
18
|
+
logger = cds_1.default.log('MaintenanceRun');
|
|
19
|
+
constructor(label, idle,
|
|
20
|
+
/** Fields shown as text, like the Int64 values of the other answers. */
|
|
21
|
+
textFields = []) {
|
|
22
|
+
this.label = label;
|
|
23
|
+
this.idle = idle;
|
|
24
|
+
this.textFields = textFields;
|
|
25
|
+
this.state = { ...idle, status: 'none', startedAt: null, finishedAt: null, error: null };
|
|
26
|
+
}
|
|
27
|
+
isBusy() {
|
|
28
|
+
return this.state.status === 'running';
|
|
29
|
+
}
|
|
30
|
+
/** The status fields of the last run; text fields as strings. */
|
|
31
|
+
snapshot() {
|
|
32
|
+
const out = {};
|
|
33
|
+
for (const key of Object.keys(this.idle)) {
|
|
34
|
+
const value = this.state[key];
|
|
35
|
+
out[key] = this.textFields.includes(key) && value != null ? String(value) : value;
|
|
36
|
+
}
|
|
37
|
+
for (const key of ['status', 'startedAt', 'finishedAt', 'error'])
|
|
38
|
+
out[key] = this.state[key];
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
// Runs `prepare` for its checks, then the work detached. A check that throws leaves the previous
|
|
42
|
+
// state in place and reaches the caller.
|
|
43
|
+
async start(prepare) {
|
|
44
|
+
if (this.isBusy())
|
|
45
|
+
throw new Error(`${this.label} is already running`);
|
|
46
|
+
const previous = this.state;
|
|
47
|
+
const current = { ...this.idle, status: 'running', startedAt: new Date().toISOString(), finishedAt: null, error: null };
|
|
48
|
+
this.state = current;
|
|
49
|
+
this.stopRequested = false;
|
|
50
|
+
let prepared;
|
|
51
|
+
try {
|
|
52
|
+
prepared = await prepare();
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
this.state = previous;
|
|
56
|
+
throw err;
|
|
57
|
+
}
|
|
58
|
+
Object.assign(current, prepared.initial ?? {});
|
|
59
|
+
const label = prepared.label ?? this.label;
|
|
60
|
+
// cancelled only when the run saw the request: one that ended first is done
|
|
61
|
+
let stopped = false;
|
|
62
|
+
const ctl = {
|
|
63
|
+
progress: (p) => { Object.assign(current, pickKnown(this.idle, p)); },
|
|
64
|
+
shouldStop: () => (stopped ||= this.stopRequested && this.state === current),
|
|
65
|
+
};
|
|
66
|
+
// a run that throws before it returns a promise fails like one that rejects
|
|
67
|
+
void Promise.resolve()
|
|
68
|
+
.then(() => prepared.run(ctl))
|
|
69
|
+
.then((result) => {
|
|
70
|
+
Object.assign(current, pickKnown(this.idle, result ?? {}), {
|
|
71
|
+
status: stopped ? 'cancelled' : 'done', finishedAt: new Date().toISOString(),
|
|
72
|
+
});
|
|
73
|
+
if (current.status === 'cancelled')
|
|
74
|
+
this.logger.info(`${label} cancelled`);
|
|
75
|
+
})
|
|
76
|
+
.catch((err) => {
|
|
77
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
78
|
+
Object.assign(current, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, ERROR_TEXT_MAX) });
|
|
79
|
+
this.logger.error(`${label} failed: ${message}`);
|
|
80
|
+
});
|
|
81
|
+
return prepared.answer;
|
|
82
|
+
}
|
|
83
|
+
/** Asks a running run to stop at its next check. False when nothing runs. */
|
|
84
|
+
cancel() {
|
|
85
|
+
if (!this.isBusy())
|
|
86
|
+
return false;
|
|
87
|
+
this.stopRequested = true;
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
exports.DetachedRun = DetachedRun;
|
|
92
|
+
/** The fields of `p` the status declares; a result may carry more. */
|
|
93
|
+
function pickKnown(idle, p) {
|
|
94
|
+
const out = {};
|
|
95
|
+
for (const [key, value] of Object.entries(p)) {
|
|
96
|
+
if (key in idle)
|
|
97
|
+
out[key] = value;
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
//# sourceMappingURL=detached-run.js.map
|
|
@@ -5,6 +5,7 @@ export declare function epochOfSlot(network: EpochNetwork, slot: number): number
|
|
|
5
5
|
/** First absolute slot of an epoch, from the network's Shelley anchor. */
|
|
6
6
|
export declare function epochStartSlot(network: EpochNetwork, epoch: number): number;
|
|
7
7
|
export declare function slotToPosixMs(network: EpochNetwork, slot: number): number;
|
|
8
|
+
export declare function rollbackHorizonSlots(network: EpochNetwork): number;
|
|
8
9
|
/** Absolute POSIX seconds for a slot, rounded down. */
|
|
9
10
|
export declare function slotToPosixSeconds(network: EpochNetwork, slot: number): number;
|
|
10
11
|
/** Slot that contains a POSIX time. Throws RangeError before Shelley, where slots were 20 s long. */
|
package/srv/utils/epoch-slots.js
CHANGED
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.epochOfSlot = epochOfSlot;
|
|
4
4
|
exports.epochStartSlot = epochStartSlot;
|
|
5
5
|
exports.slotToPosixMs = slotToPosixMs;
|
|
6
|
+
exports.rollbackHorizonSlots = rollbackHorizonSlots;
|
|
6
7
|
exports.slotToPosixSeconds = slotToPosixSeconds;
|
|
7
8
|
exports.posixToSlot = posixToSlot;
|
|
8
9
|
const const_1 = require("./const");
|
|
@@ -22,6 +23,12 @@ function slotToPosixMs(network, slot) {
|
|
|
22
23
|
const genesis = const_1.GENESIS_INFOS_BY_NETWORK[network];
|
|
23
24
|
return genesis.systemStartPosixMs + (slot - genesis.startSlotNo) * genesis.slotLengthMs;
|
|
24
25
|
}
|
|
26
|
+
// Slots after which a block can no longer be rolled back: 3k/f, the stability window of the
|
|
27
|
+
// ledger. k blocks have followed by then with overwhelming probability.
|
|
28
|
+
function rollbackHorizonSlots(network) {
|
|
29
|
+
const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[network];
|
|
30
|
+
return Math.ceil((3 * cfg.securityParam) / cfg.activeSlotsCoeff);
|
|
31
|
+
}
|
|
25
32
|
/** Absolute POSIX seconds for a slot, rounded down. */
|
|
26
33
|
function slotToPosixSeconds(network, slot) {
|
|
27
34
|
return Math.floor(slotToPosixMs(network, slot) / 1000);
|
|
@@ -20,6 +20,10 @@ export declare const ERROR_CODES: {
|
|
|
20
20
|
readonly TX_ALREADY_SUBMITTED: "ODATANO_TX_ALREADY_SUBMITTED";
|
|
21
21
|
/** 409: the idempotency key belongs to a job with another request. */
|
|
22
22
|
readonly IDEMPOTENCY_KEY_CONFLICT: "ODATANO_IDEMPOTENCY_KEY_CONFLICT";
|
|
23
|
+
/** 409: an outcome cannot be set to failed while the transaction can still land. */
|
|
24
|
+
readonly OUTCOME_STILL_OPEN: "ODATANO_OUTCOME_STILL_OPEN";
|
|
25
|
+
/** 409: another call resolved the record first. */
|
|
26
|
+
readonly RESOLVED_CONCURRENTLY: "ODATANO_RESOLVED_CONCURRENTLY";
|
|
23
27
|
/** 429: provider rate limit hit. */
|
|
24
28
|
readonly PROVIDER_RATE_LIMITED: "ODATANO_PROVIDER_RATE_LIMITED";
|
|
25
29
|
/** 503: Cardano data provider unavailable. */
|
package/srv/utils/error-codes.js
CHANGED
|
@@ -23,6 +23,10 @@ exports.ERROR_CODES = {
|
|
|
23
23
|
TX_ALREADY_SUBMITTED: 'ODATANO_TX_ALREADY_SUBMITTED',
|
|
24
24
|
/** 409: the idempotency key belongs to a job with another request. */
|
|
25
25
|
IDEMPOTENCY_KEY_CONFLICT: 'ODATANO_IDEMPOTENCY_KEY_CONFLICT',
|
|
26
|
+
/** 409: an outcome cannot be set to failed while the transaction can still land. */
|
|
27
|
+
OUTCOME_STILL_OPEN: 'ODATANO_OUTCOME_STILL_OPEN',
|
|
28
|
+
/** 409: another call resolved the record first. */
|
|
29
|
+
RESOLVED_CONCURRENTLY: 'ODATANO_RESOLVED_CONCURRENTLY',
|
|
26
30
|
/** 429: provider rate limit hit. */
|
|
27
31
|
PROVIDER_RATE_LIMITED: 'ODATANO_PROVIDER_RATE_LIMITED',
|
|
28
32
|
/** 503: Cardano data provider unavailable. */
|
package/srv/utils/errors.d.ts
CHANGED
|
@@ -50,13 +50,13 @@ export declare class ProviderUnavailableError extends BackendError {
|
|
|
50
50
|
export declare class RateLimitError extends BackendError {
|
|
51
51
|
constructor(message: string, backendName?: string, retryAfter?: number, originalError?: unknown);
|
|
52
52
|
}
|
|
53
|
-
/** Every backend failed; carries the last error's status, or 503 when all were skipped. */
|
|
54
53
|
export declare class AllBackendsFailedError extends BackendError {
|
|
55
54
|
readonly errors: BackendError[];
|
|
56
55
|
/** @param skipped why backends were not called at all, e.g. `koios: circuit open` */
|
|
57
56
|
constructor(errors: BackendError[], originalError?: unknown, skipped?: string[]);
|
|
58
57
|
}
|
|
59
58
|
export declare function isNotFoundOnAllBackends(err: unknown): boolean;
|
|
59
|
+
export declare function isBackendVerdict(err: unknown): boolean;
|
|
60
60
|
export declare function isSubmitRejection(err: unknown): boolean;
|
|
61
61
|
/** A submit failed without a verdict (503). The record stays open and the server keeps resolving it. */
|
|
62
62
|
export declare class SubmitOutcomeUnknownError extends BackendError {
|
|
@@ -68,6 +68,8 @@ export interface HttpErrorLike {
|
|
|
68
68
|
message?: string;
|
|
69
69
|
code?: string;
|
|
70
70
|
status?: number;
|
|
71
|
+
/** Blockfrost SDK errors carry the HTTP status here. */
|
|
72
|
+
status_code?: number;
|
|
71
73
|
response?: {
|
|
72
74
|
status?: number;
|
|
73
75
|
headers?: Record<string, unknown>;
|
|
@@ -85,6 +87,13 @@ export declare function isPostgrestServerErrorCode(code: unknown): boolean;
|
|
|
85
87
|
export declare function getErrorStatus(err: HttpErrorLike | unknown): number;
|
|
86
88
|
/** Message of an HttpErrorLike: `response.data.error` (Koios), else `message`. */
|
|
87
89
|
export declare function getErrorMessage(err: HttpErrorLike | unknown): string;
|
|
90
|
+
/** Characters of an error text kept in a stored status or log line. */
|
|
91
|
+
export declare const ERROR_TEXT_MAX = 500;
|
|
92
|
+
/** Message of any thrown value, at most ERROR_TEXT_MAX characters. */
|
|
93
|
+
export declare function errorText(err: unknown): string;
|
|
94
|
+
/** The `error` entries of a cardano-submit-api rejection, else the body as text. */
|
|
95
|
+
export declare function nodeRejectionReason(body: unknown): string;
|
|
96
|
+
export declare function submitRejection(reason: string, backendName: string, err: unknown): BackendError;
|
|
88
97
|
export declare function normalizeBackendError(err: unknown, backendName?: string): BackendError;
|
|
89
98
|
/** HSM operation failed (session, key access, signing). */
|
|
90
99
|
export declare class HsmError extends BackendError {
|
package/srv/utils/errors.js
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.AllBackendsInitFailedError = exports.BackendInitError = exports.ChainSyncFrameError = exports.ChainSyncStalledError = exports.ChainSyncClosedError = exports.ConfigError = exports.HsmError = exports.SubmitOutcomeUnknownError = exports.AllBackendsFailedError = exports.RateLimitError = exports.ProviderUnavailableError = exports.MixedAssetsError = exports.InsufficientFundsError = exports.TransactionAlreadySubmittedError = exports.ChainPointMismatchError = exports.ScriptValidationError = exports.TransactionValidationError = exports.NotFoundError = exports.BackendError = void 0;
|
|
3
|
+
exports.AllBackendsInitFailedError = exports.BackendInitError = exports.ChainSyncFrameError = exports.ChainSyncStalledError = exports.ChainSyncClosedError = exports.ConfigError = exports.HsmError = exports.ERROR_TEXT_MAX = exports.SubmitOutcomeUnknownError = exports.AllBackendsFailedError = exports.RateLimitError = exports.ProviderUnavailableError = exports.MixedAssetsError = exports.InsufficientFundsError = exports.TransactionAlreadySubmittedError = exports.ChainPointMismatchError = exports.ScriptValidationError = exports.TransactionValidationError = exports.NotFoundError = exports.BackendError = void 0;
|
|
4
4
|
exports.isNotFoundOnAllBackends = isNotFoundOnAllBackends;
|
|
5
|
+
exports.isBackendVerdict = isBackendVerdict;
|
|
5
6
|
exports.isSubmitRejection = isSubmitRejection;
|
|
6
7
|
exports.isPostgrestServerErrorCode = isPostgrestServerErrorCode;
|
|
7
8
|
exports.getErrorStatus = getErrorStatus;
|
|
8
9
|
exports.getErrorMessage = getErrorMessage;
|
|
10
|
+
exports.errorText = errorText;
|
|
11
|
+
exports.nodeRejectionReason = nodeRejectionReason;
|
|
12
|
+
exports.submitRejection = submitRejection;
|
|
9
13
|
exports.normalizeBackendError = normalizeBackendError;
|
|
10
14
|
exports.rejectInvalid = rejectInvalid;
|
|
11
15
|
exports.rejectMissing = rejectMissing;
|
|
@@ -118,16 +122,15 @@ class RateLimitError extends BackendError {
|
|
|
118
122
|
}
|
|
119
123
|
}
|
|
120
124
|
exports.RateLimitError = RateLimitError;
|
|
121
|
-
|
|
125
|
+
// Every backend failed. It answers 404 only when every backend said 404, else the last other error.
|
|
126
|
+
// With no error at all every backend was skipped, so 503.
|
|
122
127
|
class AllBackendsFailedError extends BackendError {
|
|
123
128
|
errors;
|
|
124
129
|
/** @param skipped why backends were not called at all, e.g. `koios: circuit open` */
|
|
125
130
|
constructor(errors, originalError, skipped = []) {
|
|
126
|
-
const
|
|
131
|
+
const decisive = [...errors].reverse().find((e) => e.statusCode !== 404) ?? errors[errors.length - 1];
|
|
127
132
|
const noneCalled = skipped.length ? `no backend available (${skipped.join('; ')})` : 'unknown error';
|
|
128
|
-
super(
|
|
129
|
-
// Empty errors: every backend was skipped (method unsupported), nothing failed upstream, so 503
|
|
130
|
-
`All backends failed: ${lastError?.message ?? noneCalled}`, lastError?.statusCode ?? 503, lastError?.code ?? error_codes_1.ERROR_CODES.PROVIDER_UNAVAILABLE, undefined, originalError);
|
|
133
|
+
super(`All backends failed: ${decisive?.message ?? noneCalled}`, decisive?.statusCode ?? 503, decisive?.code ?? error_codes_1.ERROR_CODES.PROVIDER_UNAVAILABLE, undefined, originalError);
|
|
131
134
|
this.errors = errors;
|
|
132
135
|
}
|
|
133
136
|
}
|
|
@@ -140,6 +143,8 @@ function isNotFoundOnAllBackends(err) {
|
|
|
140
143
|
&& err.errors.length > 0
|
|
141
144
|
&& err.errors.every((e) => e instanceof NotFoundError || e.statusCode === 404);
|
|
142
145
|
}
|
|
146
|
+
// A 4xx a healthy backend gave about the request itself. A rate limit is not one, and 401, 402
|
|
147
|
+
// and 403 arrive as 503 from normalizeBackendError.
|
|
143
148
|
function isBackendVerdict(err) {
|
|
144
149
|
return err instanceof BackendError && !(err instanceof AllBackendsFailedError)
|
|
145
150
|
&& err.statusCode >= 400 && err.statusCode < 500 && err.statusCode !== 429;
|
|
@@ -171,7 +176,7 @@ function isPostgrestServerErrorCode(code) {
|
|
|
171
176
|
/** HTTP status of an HttpErrorLike, default 500. */
|
|
172
177
|
function getErrorStatus(err) {
|
|
173
178
|
const e = (err ?? {});
|
|
174
|
-
return e.status ?? e.response?.status ?? 500;
|
|
179
|
+
return e.status ?? e.status_code ?? e.response?.status ?? 500;
|
|
175
180
|
}
|
|
176
181
|
/** Message of an HttpErrorLike: `response.data.error` (Koios), else `message`. */
|
|
177
182
|
function getErrorMessage(err) {
|
|
@@ -182,6 +187,42 @@ function getErrorMessage(err) {
|
|
|
182
187
|
return e.message;
|
|
183
188
|
return 'Unknown error';
|
|
184
189
|
}
|
|
190
|
+
/** Characters of an error text kept in a stored status or log line. */
|
|
191
|
+
exports.ERROR_TEXT_MAX = 500;
|
|
192
|
+
/** Message of any thrown value, at most ERROR_TEXT_MAX characters. */
|
|
193
|
+
function errorText(err) {
|
|
194
|
+
return (err instanceof Error ? err.message : String(err)).slice(0, exports.ERROR_TEXT_MAX);
|
|
195
|
+
}
|
|
196
|
+
/** The `error` entries of a cardano-submit-api rejection, else the body as text. */
|
|
197
|
+
function nodeRejectionReason(body) {
|
|
198
|
+
const errors = [];
|
|
199
|
+
const walk = (v) => {
|
|
200
|
+
if (!v || typeof v !== 'object')
|
|
201
|
+
return;
|
|
202
|
+
const o = v;
|
|
203
|
+
if (Array.isArray(o.error))
|
|
204
|
+
errors.push(...o.error.map(String));
|
|
205
|
+
else if (typeof o.error === 'string')
|
|
206
|
+
errors.push(o.error);
|
|
207
|
+
for (const child of Object.values(o))
|
|
208
|
+
walk(child);
|
|
209
|
+
};
|
|
210
|
+
walk(typeof body === 'string' ? (() => { try {
|
|
211
|
+
return JSON.parse(body);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return undefined;
|
|
215
|
+
} })() : body);
|
|
216
|
+
const text = errors.length > 0 ? errors.join('; ') : (typeof body === 'string' ? body : JSON.stringify(body));
|
|
217
|
+
return text.slice(0, 1000);
|
|
218
|
+
}
|
|
219
|
+
// A node's refusal of a submitted transaction. Already-submitted and script failures keep their class.
|
|
220
|
+
function submitRejection(reason, backendName, err) {
|
|
221
|
+
const known = normalizeBackendError(new Error(reason), backendName);
|
|
222
|
+
if (known.statusCode === 409 || known instanceof ScriptValidationError)
|
|
223
|
+
return known;
|
|
224
|
+
return new TransactionValidationError(`node rejected the transaction: ${reason}`, err);
|
|
225
|
+
}
|
|
185
226
|
/** Ogmios JSON-RPC code of a failed script evaluation. */
|
|
186
227
|
const OGMIOS_SCRIPT_EXECUTION_FAILURE = 3010;
|
|
187
228
|
/** Characters of Ogmios error data kept in a message. */
|
|
@@ -300,8 +341,9 @@ function normalizeBackendError(err, backendName) {
|
|
|
300
341
|
if (status === 400 || status === 422) {
|
|
301
342
|
return new TransactionValidationError(message || `Provider returned ${status}: invalid request`, err);
|
|
302
343
|
}
|
|
303
|
-
|
|
304
|
-
|
|
344
|
+
// A refused key is the provider's fault, not the request's: another backend may answer.
|
|
345
|
+
if (status === 401 || status === 402 || status === 403) {
|
|
346
|
+
return new ProviderUnavailableError(`Provider authentication failed (${status}): ${message}`, backendName, undefined, err);
|
|
305
347
|
}
|
|
306
348
|
if (status >= 400) {
|
|
307
349
|
return new ProviderUnavailableError(message || 'Provider request failed', backendName, undefined, err);
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Transaction as CapTransaction } from '@sap/cds';
|
|
2
|
+
/** The row that holds a lease. */
|
|
3
|
+
export interface LeaseRow {
|
|
4
|
+
entity: unknown;
|
|
5
|
+
key: Record<string, unknown>;
|
|
6
|
+
/** Column values every acquire and renewal requires in its WHERE. */
|
|
7
|
+
requires?: Record<string, unknown>;
|
|
8
|
+
/** The same requirement on a row read back, for the adapters' own value forms. */
|
|
9
|
+
holds?: (row: Record<string, unknown>) => boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface LeaseTiming {
|
|
12
|
+
now?: Date;
|
|
13
|
+
ttlMs: number;
|
|
14
|
+
}
|
|
15
|
+
export declare function tryAcquireLease(db: CapTransaction, lease: LeaseRow, owner: string, timing: LeaseTiming, admit?: (row: Record<string, unknown>) => boolean): Promise<boolean>;
|
|
16
|
+
/** Extends the caller's lease, with `set` written in the same statement. False when it is lost. */
|
|
17
|
+
export declare function renewLease(db: CapTransaction, lease: LeaseRow, owner: string, timing: LeaseTiming, set?: Record<string, unknown>): Promise<boolean>;
|
|
18
|
+
/** Gives up only the caller's lease, so a former owner never clears its successor. */
|
|
19
|
+
export declare function releaseLease(db: CapTransaction, lease: LeaseRow, owner: string, set?: Record<string, unknown>): Promise<void>;
|
|
20
|
+
//# sourceMappingURL=lease.d.ts.map
|
|
@@ -0,0 +1,62 @@
|
|
|
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.tryAcquireLease = tryAcquireLease;
|
|
7
|
+
exports.renewLease = renewLease;
|
|
8
|
+
exports.releaseLease = releaseLease;
|
|
9
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
10
|
+
const row_values_1 = require("./row-values");
|
|
11
|
+
const { SELECT, UPDATE } = cds_1.default.ql;
|
|
12
|
+
async function readLease(db, lease) {
|
|
13
|
+
const row = await db.run(SELECT.one.from(lease.entity).where(lease.key));
|
|
14
|
+
if (!row)
|
|
15
|
+
return null;
|
|
16
|
+
return { leaseOwner: row.leaseOwner ?? null, leaseUntil: (0, row_values_1.timestamp)(row.leaseUntil), row };
|
|
17
|
+
}
|
|
18
|
+
// True when `owner` holds the lease until at least `expectedMs`. One second of tolerance covers
|
|
19
|
+
// adapters that store the timestamp with less precision.
|
|
20
|
+
function heldUntil(stored, lease, owner, expectedMs) {
|
|
21
|
+
if (!stored || stored.leaseOwner !== owner || !stored.leaseUntil)
|
|
22
|
+
return false;
|
|
23
|
+
if (lease.holds && !lease.holds(stored.row))
|
|
24
|
+
return false;
|
|
25
|
+
const actualMs = Date.parse(stored.leaseUntil);
|
|
26
|
+
return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
|
|
27
|
+
}
|
|
28
|
+
// Takes a free or expired lease, or renews the caller's own. A foreign lease is taken only when the
|
|
29
|
+
// UPDATE itself still sees it expired, so a renewal that commits first wins. `admit` can refuse the row.
|
|
30
|
+
async function tryAcquireLease(db, lease, owner, timing, admit) {
|
|
31
|
+
const now = timing.now ?? new Date();
|
|
32
|
+
const stored = await readLease(db, lease);
|
|
33
|
+
if (!stored)
|
|
34
|
+
return false;
|
|
35
|
+
if ((lease.holds && !lease.holds(stored.row)) || (admit && !admit(stored.row)))
|
|
36
|
+
return false;
|
|
37
|
+
const deadline = stored.leaseUntil ? Date.parse(stored.leaseUntil) : Number.NEGATIVE_INFINITY;
|
|
38
|
+
const foreign = stored.leaseOwner != null && stored.leaseOwner !== owner;
|
|
39
|
+
if (foreign && deadline > now.getTime())
|
|
40
|
+
return false;
|
|
41
|
+
const where = { ...lease.key, ...lease.requires, leaseOwner: stored.leaseOwner };
|
|
42
|
+
if (foreign)
|
|
43
|
+
where.leaseUntil = stored.leaseUntil == null ? null : { '<': now.toISOString() };
|
|
44
|
+
const until = now.getTime() + timing.ttlMs;
|
|
45
|
+
await db.run(UPDATE.entity(lease.entity).set({ leaseOwner: owner, leaseUntil: new Date(until).toISOString() }).where(where));
|
|
46
|
+
return heldUntil(await readLease(db, lease), lease, owner, until);
|
|
47
|
+
}
|
|
48
|
+
/** Extends the caller's lease, with `set` written in the same statement. False when it is lost. */
|
|
49
|
+
async function renewLease(db, lease, owner, timing, set = {}) {
|
|
50
|
+
const until = (timing.now ?? new Date()).getTime() + timing.ttlMs;
|
|
51
|
+
await db.run(UPDATE.entity(lease.entity)
|
|
52
|
+
.set({ ...set, leaseUntil: new Date(until).toISOString() })
|
|
53
|
+
.where({ ...lease.key, ...lease.requires, leaseOwner: owner }));
|
|
54
|
+
return heldUntil(await readLease(db, lease), lease, owner, until);
|
|
55
|
+
}
|
|
56
|
+
/** Gives up only the caller's lease, so a former owner never clears its successor. */
|
|
57
|
+
async function releaseLease(db, lease, owner, set = {}) {
|
|
58
|
+
await db.run(UPDATE.entity(lease.entity)
|
|
59
|
+
.set({ ...set, leaseOwner: null, leaseUntil: null })
|
|
60
|
+
.where({ ...lease.key, leaseOwner: owner }));
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=lease.js.map
|
package/srv/utils/mappers.d.ts
CHANGED
|
@@ -104,6 +104,15 @@ export declare function mapAddressSigningRequest(addr: string, signingRequestId:
|
|
|
104
104
|
export declare function mapAddressTransactionBuild(addr: string, buildId: string): AddressTransactionBuildRow;
|
|
105
105
|
export declare function normalizeCostModels(raw: Record<string, unknown>): Record<string, number[]>;
|
|
106
106
|
export declare function decodeAssetName(hex: string): string;
|
|
107
|
+
/** The AssetSlice columns of one asset row, as every table that holds asset rows stores them. */
|
|
108
|
+
export interface AssetSliceColumns {
|
|
109
|
+
asset_quantity: string;
|
|
110
|
+
asset_policyId: string | null;
|
|
111
|
+
asset_assetNameHex: string | null;
|
|
112
|
+
asset_assetName: string | null;
|
|
113
|
+
asset_fingerprint: string | null;
|
|
114
|
+
}
|
|
115
|
+
export declare function assetSlice(unit: string, quantity: string | number | bigint): AssetSliceColumns;
|
|
107
116
|
/** CIP-14 fingerprint: bech32("asset", blake2b_160(policyId_bytes + assetName_bytes)). */
|
|
108
117
|
export declare function computeCip14Fingerprint(policyIdHex: string, assetNameHex: string): string;
|
|
109
118
|
/** Enterprise script address: header 0x71 (mainnet) / 0x70 (testnet) + 28-byte script hash, bech32. */
|