@odatano/core 2.0.0-rc.51 → 2.0.0-rc.53
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/package.json +1 -1
- package/srv/blockchain/crawler/certificate-backfill.js +2 -2
- package/srv/cardano-backend-service.js +2 -0
- package/srv/cardano-service.js +4 -0
- package/srv/cardano-tx-service.cds +8 -8
- package/srv/config.d.ts +3 -0
- package/srv/config.js +17 -1
- package/srv/server.js +2 -0
- package/srv/utils/db-indexes.d.ts +1 -1
- package/srv/utils/db-indexes.js +7 -2
- package/srv/utils/error-codes.d.ts +4 -0
- package/srv/utils/error-codes.js +4 -0
- package/srv/utils/mappers.js +4 -0
- package/srv/utils/read-guard.d.ts +62 -0
- package/srv/utils/read-guard.js +179 -0
- package/srv/utils/read-limits.d.ts +25 -0
- package/srv/utils/read-limits.js +77 -0
- package/srv/utils/tx-utils.js +10 -1
- package/srv/utils/types.d.ts +1 -1
package/package.json
CHANGED
|
@@ -32,8 +32,8 @@ async function intersectionBefore(db, slot) {
|
|
|
32
32
|
let row = null;
|
|
33
33
|
if (floor == null || slot - 1 >= floor) {
|
|
34
34
|
const q = SELECT.one.from(cardano_1.Block).columns('hash', 'slot', 'height').where({ slot: range });
|
|
35
|
-
// nulls
|
|
36
|
-
q.SELECT.orderBy = [{ ref: ['slot'], sort: 'desc', nulls: '
|
|
35
|
+
// nulls last is the order the slot index (NULLS FIRST) is read backwards in; the range excludes null
|
|
36
|
+
q.SELECT.orderBy = [{ ref: ['slot'], sort: 'desc', nulls: 'last' }];
|
|
37
37
|
row = (await db.run(q));
|
|
38
38
|
}
|
|
39
39
|
if (row?.hash && row.slot != null)
|
|
@@ -8,6 +8,7 @@ const deep_json_1 = require("./utils/deep-json");
|
|
|
8
8
|
const backend_request_handler_1 = require("./utils/backend-request-handler");
|
|
9
9
|
const tx_utils_1 = require("./utils/tx-utils");
|
|
10
10
|
const result_numbers_1 = require("./utils/result-numbers");
|
|
11
|
+
const read_limits_1 = require("./utils/read-limits");
|
|
11
12
|
const errors_1 = require("./utils/errors");
|
|
12
13
|
const validators_1 = require("./utils/validators");
|
|
13
14
|
const server_1 = require("./server");
|
|
@@ -20,6 +21,7 @@ const MAX_LIST = 500;
|
|
|
20
21
|
// Nothing is written here, so every database read runs outside the request transaction.
|
|
21
22
|
module.exports = (srv) => {
|
|
22
23
|
(0, result_numbers_1.answerNumbersAsText)(srv);
|
|
24
|
+
(0, read_limits_1.limitApiReads)(srv);
|
|
23
25
|
const client = () => (0, server_1.getCardanoClient)();
|
|
24
26
|
const indexer = () => (0, server_1.getCardanoIndexer)();
|
|
25
27
|
/** Register an operation: validate, run, answer the JSON of the result. */
|
package/srv/cardano-service.js
CHANGED
|
@@ -14,6 +14,8 @@ const CardanoODataService_1 = require("#cds-models/CardanoODataService");
|
|
|
14
14
|
const mappers_1 = require("./utils/mappers");
|
|
15
15
|
const tx_utils_1 = require("./utils/tx-utils");
|
|
16
16
|
const result_numbers_1 = require("./utils/result-numbers");
|
|
17
|
+
const read_limits_1 = require("./utils/read-limits");
|
|
18
|
+
const read_guard_1 = require("./utils/read-guard");
|
|
17
19
|
const navigation_1 = require("./utils/navigation");
|
|
18
20
|
const cardano_indexer_1 = require("./blockchain/cardano-indexer");
|
|
19
21
|
/** Pause between two reads of a waiting GetLatestTransactionsByAddress call. */
|
|
@@ -219,6 +221,8 @@ function addressChildRead(isIndexed, index) {
|
|
|
219
221
|
/** CardanoODataService handlers: blockchain read queries with index-on-miss. */
|
|
220
222
|
module.exports = (srv) => {
|
|
221
223
|
(0, result_numbers_1.answerNumbersAsText)(srv);
|
|
224
|
+
(0, read_limits_1.limitApiReads)(srv);
|
|
225
|
+
(0, read_guard_1.guardLargeReads)(srv);
|
|
222
226
|
logger.debug('Module loaded - registering handlers');
|
|
223
227
|
// For plural-shaped names (NetworkInformation, TransactionMetadata, AssetHistory) cds-typer
|
|
224
228
|
// exports the singular class under the plain name and the entity-set class with a trailing
|
|
@@ -132,14 +132,14 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
|
|
|
132
132
|
@description: 'Optional Plutus V3 validator CBOR hex to attach as referenceScript on the primary recipient output (CIP-33 reference script deploy). Significantly increases the output min-ADA; lovelaceAmount must cover the inflated requirement.'
|
|
133
133
|
referenceScriptHex: String,
|
|
134
134
|
@title: 'Validity Start (Posix ms)'
|
|
135
|
-
@description: 'Optional. Validity-interval start in Posix milliseconds.
|
|
135
|
+
@description: 'Optional. Validity-interval start in Posix milliseconds. No start is set when omitted.'
|
|
136
136
|
validityStartMs: String,
|
|
137
137
|
@title: 'Validity End (Posix ms)'
|
|
138
|
-
@description: 'Optional. Validity-interval end in Posix milliseconds.
|
|
138
|
+
@description: 'Optional. Validity-interval end in Posix milliseconds. Defaults to now + 3 600 000 ms, or to validityStartMs + 3 600 000 ms when that start lies in the future. At most 24 hours ahead, else 400.'
|
|
139
139
|
validityEndMs: String) returns TransactionBuilds;
|
|
140
140
|
|
|
141
141
|
@title : 'Build Transaction with Metadata'
|
|
142
|
-
@description: 'Build a transaction with custom metadata from sender to recipient with specified amount and change address'
|
|
142
|
+
@description: 'Build a transaction with custom metadata from sender to recipient with specified amount and change address. The transaction expires one hour after the build.'
|
|
143
143
|
@odatano.agent: 'grant'
|
|
144
144
|
action BuildTransactionWithMetadata(
|
|
145
145
|
@title: 'Sender Address'
|
|
@@ -190,10 +190,10 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
|
|
|
190
190
|
@description: 'Optional Plutus V3 validator CBOR hex to attach as referenceScript on the primary recipient output (CIP-33 reference script deploy). Significantly increases the output min-ADA; lovelaceAmount must cover the inflated requirement.'
|
|
191
191
|
referenceScriptHex: String,
|
|
192
192
|
@title: 'Validity Start (Posix ms)'
|
|
193
|
-
@description: 'Optional. Validity-interval start in Posix milliseconds.
|
|
193
|
+
@description: 'Optional. Validity-interval start in Posix milliseconds. No start is set when omitted.'
|
|
194
194
|
validityStartMs: String,
|
|
195
195
|
@title: 'Validity End (Posix ms)'
|
|
196
|
-
@description: 'Optional. Validity-interval end in Posix milliseconds.
|
|
196
|
+
@description: 'Optional. Validity-interval end in Posix milliseconds. Defaults to now + 3 600 000 ms, or to validityStartMs + 3 600 000 ms when that start lies in the future. At most 24 hours ahead, else 400.'
|
|
197
197
|
validityEndMs: String) returns TransactionBuilds;
|
|
198
198
|
|
|
199
199
|
@title : 'Build Minting Transaction'
|
|
@@ -255,7 +255,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
|
|
|
255
255
|
@description: 'Optional. Sets the transaction validity-interval start in Posix milliseconds. Required finite value for Plutus validators that call expect Finite(lower) on tx.validity_range.lower_bound. Defaults to now − 120 000 ms when omitted.'
|
|
256
256
|
validityStartMs: String,
|
|
257
257
|
@title: 'Validity End (Posix ms)'
|
|
258
|
-
@description: 'Optional. Sets the transaction validity-interval end in Posix milliseconds. Required finite value for Plutus validators that call expect Finite(upper) on tx.validity_range.upper_bound. Defaults to now + 3 600 000 ms when
|
|
258
|
+
@description: 'Optional. Sets the transaction validity-interval end in Posix milliseconds. Required finite value for Plutus validators that call expect Finite(upper) on tx.validity_range.upper_bound. Defaults to now + 3 600 000 ms, or to validityStartMs + 3 600 000 ms when that start lies in the future. At most 24 hours ahead, else 400.'
|
|
259
259
|
validityEndMs: String) returns TransactionBuilds;
|
|
260
260
|
|
|
261
261
|
@title : 'Get Build Details'
|
|
@@ -360,7 +360,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
|
|
|
360
360
|
@description: 'Optional. Sets the transaction validity-interval start in Posix milliseconds. Required finite value for Plutus validators that call expect Finite(lower) on tx.validity_range.lower_bound. Defaults to now − 120 000 ms when omitted.'
|
|
361
361
|
validityStartMs: String,
|
|
362
362
|
@title: 'Validity End (Posix ms)'
|
|
363
|
-
@description: 'Optional. Sets the transaction validity-interval end in Posix milliseconds. Required finite value for Plutus validators that call expect Finite(upper) on tx.validity_range.upper_bound. Defaults to now + 3 600 000 ms when
|
|
363
|
+
@description: 'Optional. Sets the transaction validity-interval end in Posix milliseconds. Required finite value for Plutus validators that call expect Finite(upper) on tx.validity_range.upper_bound. Defaults to now + 3 600 000 ms, or to validityStartMs + 3 600 000 ms when that start lies in the future. At most 24 hours ahead, else 400.'
|
|
364
364
|
validityEndMs: String) returns TransactionBuilds;
|
|
365
365
|
|
|
366
366
|
@title : 'Build Plutus Transaction'
|
|
@@ -404,7 +404,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
|
|
|
404
404
|
@description: 'Optional validity-interval start in Posix milliseconds; defaults to now - 120 000 ms.'
|
|
405
405
|
validityStartMs: String,
|
|
406
406
|
@title: 'Validity End (Posix ms)'
|
|
407
|
-
@description: 'Optional validity-interval end in Posix milliseconds; defaults to now + 3 600 000 ms.'
|
|
407
|
+
@description: 'Optional validity-interval end in Posix milliseconds; defaults to now + 3 600 000 ms, or to validityStartMs + 3 600 000 ms when that start lies in the future. At most 24 hours ahead, else 400.'
|
|
408
408
|
validityEndMs: String) returns TransactionBuilds;
|
|
409
409
|
|
|
410
410
|
@title : 'Set Collateral'
|
package/srv/config.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ export interface OdatanoCoreCdsConfig {
|
|
|
16
16
|
fallbackTimeoutMs?: number;
|
|
17
17
|
indexTtlMs?: number;
|
|
18
18
|
poolMetadataFetch?: CdsBoolean;
|
|
19
|
+
readTimeoutMs?: CdsNumber;
|
|
19
20
|
hsm?: HsmCdsSection;
|
|
20
21
|
crawler?: CrawlerCdsSection;
|
|
21
22
|
walletWorker?: WalletWorkerCdsSection;
|
|
@@ -81,6 +82,8 @@ export declare function encryptionSecret(): string | undefined;
|
|
|
81
82
|
export declare function autoInitSkipped(): boolean;
|
|
82
83
|
/** ODATANO_DETACHED_TX_TIMEOUT_MS when it is a positive number; read per call. */
|
|
83
84
|
export declare function detachedTxTimeoutMs(): number | undefined;
|
|
85
|
+
export declare const READ_TIMEOUT_MS_DEFAULT = 15000;
|
|
86
|
+
export declare function loadReadTimeoutMs(vars?: Record<string, string | undefined>): number;
|
|
84
87
|
/** Blockchain components created once at bootstrap and shared across services. */
|
|
85
88
|
/** Backends and their credentials. Throws ConfigError for an invalid value. */
|
|
86
89
|
export declare function loadConfigFromEnv(): CardanoClientConfig;
|
package/srv/config.js
CHANGED
|
@@ -3,13 +3,14 @@ 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.AGENT_AUTH_IMPL = exports.AGENT_GRANT_USAGE_RETENTION_DAYS_DEFAULT = exports.AGENT_TOKEN_CACHE_MS_DEFAULT = exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = exports.AGENT_GRANTS_DELEGATES = void 0;
|
|
6
|
+
exports.AGENT_AUTH_IMPL = exports.AGENT_GRANT_USAGE_RETENTION_DAYS_DEFAULT = exports.AGENT_TOKEN_CACHE_MS_DEFAULT = exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = exports.AGENT_GRANTS_DELEGATES = exports.READ_TIMEOUT_MS_DEFAULT = void 0;
|
|
7
7
|
exports.coreCdsConfig = coreCdsConfig;
|
|
8
8
|
exports.configuredNetworkName = configuredNetworkName;
|
|
9
9
|
exports.isProduction = isProduction;
|
|
10
10
|
exports.encryptionSecret = encryptionSecret;
|
|
11
11
|
exports.autoInitSkipped = autoInitSkipped;
|
|
12
12
|
exports.detachedTxTimeoutMs = detachedTxTimeoutMs;
|
|
13
|
+
exports.loadReadTimeoutMs = loadReadTimeoutMs;
|
|
13
14
|
exports.loadConfigFromEnv = loadConfigFromEnv;
|
|
14
15
|
exports.loadPoolMetadataFetchFromEnv = loadPoolMetadataFetchFromEnv;
|
|
15
16
|
exports.loadHsmConfigFromEnv = loadHsmConfigFromEnv;
|
|
@@ -55,6 +56,21 @@ function detachedTxTimeoutMs() {
|
|
|
55
56
|
const fromEnv = Number(process_1.env.ODATANO_DETACHED_TX_TIMEOUT_MS);
|
|
56
57
|
return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : undefined;
|
|
57
58
|
}
|
|
59
|
+
exports.READ_TIMEOUT_MS_DEFAULT = 15_000;
|
|
60
|
+
// Statement timeout for API reads on PostgreSQL. 0 turns it off; an invalid value logs a warning
|
|
61
|
+
// and falls back to the default.
|
|
62
|
+
function loadReadTimeoutMs(vars = process_1.env) {
|
|
63
|
+
const configured = coreCdsConfig().readTimeoutMs;
|
|
64
|
+
const raw = configured !== undefined ? configured : vars.READ_TIMEOUT_MS;
|
|
65
|
+
if (raw === undefined || raw === null || String(raw).trim() === '')
|
|
66
|
+
return exports.READ_TIMEOUT_MS_DEFAULT;
|
|
67
|
+
const n = Number(raw);
|
|
68
|
+
if (!Number.isInteger(n) || n < 0) {
|
|
69
|
+
logger.warn(`READ_TIMEOUT_MS "${String(raw)}" is not an integer >= 0; using ${exports.READ_TIMEOUT_MS_DEFAULT}`);
|
|
70
|
+
return exports.READ_TIMEOUT_MS_DEFAULT;
|
|
71
|
+
}
|
|
72
|
+
return n;
|
|
73
|
+
}
|
|
58
74
|
const VALID_BACKENDS = ['blockfrost', 'koios', 'ogmios', 'odatano'];
|
|
59
75
|
const CRAWLER_LIMITS = {
|
|
60
76
|
batchSize: { min: 1, max: 100 },
|
package/srv/server.js
CHANGED
|
@@ -26,6 +26,7 @@ const network_context_1 = require("./utils/network-context");
|
|
|
26
26
|
const db_sanitize_1 = require("./utils/db-sanitize");
|
|
27
27
|
const db_indexes_1 = require("./utils/db-indexes");
|
|
28
28
|
const pg_order_nulls_1 = require("./utils/pg-order-nulls");
|
|
29
|
+
const read_limits_1 = require("./utils/read-limits");
|
|
29
30
|
const pg_inline_json_1 = require("./utils/pg-inline-json");
|
|
30
31
|
const crawler_1 = require("./blockchain/crawler");
|
|
31
32
|
const wallet_worker_1 = require("./blockchain/wallet-worker");
|
|
@@ -42,6 +43,7 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
|
|
|
42
43
|
// then the secondary indexes the model cannot declare.
|
|
43
44
|
(0, pg_order_nulls_1.installPostgresOrderNulls)();
|
|
44
45
|
(0, pg_inline_json_1.installPostgresInlineJson)();
|
|
46
|
+
(0, read_limits_1.installReadTimeout)();
|
|
45
47
|
// PostgreSQL builds its indexes CONCURRENTLY, so the service answers while a large one builds.
|
|
46
48
|
const indexes = (0, db_indexes_1.ensureDbIndexes)().catch((err) => { logger.warn('secondary indexes not ensured (non-fatal):', err); });
|
|
47
49
|
if (cds_1.default.db?.kind !== 'postgres')
|
|
@@ -10,7 +10,7 @@ export interface IndexSpec {
|
|
|
10
10
|
}
|
|
11
11
|
/** Every entry answers a query the service or the crawler actually runs. */
|
|
12
12
|
export declare const DB_INDEXES: readonly IndexSpec[];
|
|
13
|
-
/** Indexes
|
|
13
|
+
/** Indexes an entry above replaces; dropped at start. */
|
|
14
14
|
export declare const DROPPED_DB_INDEXES: readonly string[];
|
|
15
15
|
/** The statement for one entry; exported so tests pin the shape. */
|
|
16
16
|
export declare function indexStatement(spec: IndexSpec, kind?: string): string;
|
package/srv/utils/db-indexes.js
CHANGED
|
@@ -18,7 +18,8 @@ exports.DB_INDEXES = Object.freeze([
|
|
|
18
18
|
// CAP renders `$orderby=height desc` as DESC NULLS LAST, which the plain ASC NULLS LAST
|
|
19
19
|
// index cannot serve backwards; the plain one stays for ASC and equality.
|
|
20
20
|
{ name: 'odatano_cardano_blocks_height_desc', table: 'odatano_cardano_Blocks', columns: 'height DESC', postgres: 'height DESC NULLS LAST' },
|
|
21
|
-
|
|
21
|
+
// NULLS FIRST serves both orders CAP renders by default: ASC NULLS FIRST and, read backwards, DESC NULLS LAST
|
|
22
|
+
{ name: 'odatano_cardano_blocks_slot_nf', table: 'odatano_cardano_Blocks', columns: 'slot', postgres: 'slot NULLS FIRST' },
|
|
22
23
|
{ name: 'odatano_cardano_blocks_epoch', table: 'odatano_cardano_Blocks', columns: 'epochNumber' },
|
|
23
24
|
// the first block at or after a point in time (`$filter=time ge …&$orderby=time`)
|
|
24
25
|
// CAP sorts a nullable column as ASC NULLS FIRST or DESC NULLS LAST on PostgreSQL; this serves both
|
|
@@ -48,6 +49,9 @@ exports.DB_INDEXES = Object.freeze([
|
|
|
48
49
|
// rollback `snapshotSlot >`: the keys start with the epoch
|
|
49
50
|
{ name: 'odatano_cardano_poolepochsnapshots_slot', table: 'odatano_cardano_PoolEpochSnapshots', columns: 'snapshotSlot' },
|
|
50
51
|
{ name: 'odatano_cardano_drepepochsnapshots_slot', table: 'odatano_cardano_DrepEpochSnapshots', columns: 'snapshotSlot' },
|
|
52
|
+
// every pool or DRep of one epoch; the keys start with the pool or DRep
|
|
53
|
+
{ name: 'odatano_cardano_poolepochsnapshots_epoch', table: 'odatano_cardano_PoolEpochSnapshots', columns: 'epoch' },
|
|
54
|
+
{ name: 'odatano_cardano_drepepochsnapshots_epoch', table: 'odatano_cardano_DrepEpochSnapshots', columns: 'epoch' },
|
|
51
55
|
{ name: 'odatano_cardano_epochledgersnapshots_slot', table: 'odatano_cardano_EpochLedgerSnapshots', columns: 'snapshotSlot' },
|
|
52
56
|
{ name: 'odatano_cardano_addresstransactions_tx', table: 'odatano_cardano_AddressTransactions', columns: 'tx_hash' },
|
|
53
57
|
{ name: 'odatano_cardano_accounts_stake', table: 'odatano_cardano_Accounts', columns: 'stakeAddress' },
|
|
@@ -82,11 +86,12 @@ exports.DB_INDEXES = Object.freeze([
|
|
|
82
86
|
{ name: 'odatano_cardano_cardanowalletjobs_status', table: 'odatano_cardano_CardanoWalletJobs', columns: 'status' },
|
|
83
87
|
{ name: 'odatano_cardano_cardanowalletjobs_next', table: 'odatano_cardano_CardanoWalletJobs', columns: 'walletId, status, priority, createdAt' },
|
|
84
88
|
]);
|
|
85
|
-
/** Indexes
|
|
89
|
+
/** Indexes an entry above replaces; dropped at start. */
|
|
86
90
|
exports.DROPPED_DB_INDEXES = Object.freeze([
|
|
87
91
|
'odatano_cardano_transactions_block',
|
|
88
92
|
'odatano_cardano_cardanowalletjobs_due',
|
|
89
93
|
'odatano_cardano_cardanowalletjobs_wallet',
|
|
94
|
+
'odatano_cardano_blocks_slot',
|
|
90
95
|
]);
|
|
91
96
|
/** The statement for one entry; exported so tests pin the shape. */
|
|
92
97
|
function indexStatement(spec, kind = 'sqlite') {
|
|
@@ -30,6 +30,10 @@ export declare const ERROR_CODES: {
|
|
|
30
30
|
readonly PROVIDER_UNAVAILABLE: "ODATANO_PROVIDER_UNAVAILABLE";
|
|
31
31
|
/** 503: a submit failed without a verdict; the transaction may still reach the chain. */
|
|
32
32
|
readonly SUBMIT_OUTCOME_UNKNOWN: "ODATANO_SUBMIT_OUTCOME_UNKNOWN";
|
|
33
|
+
/** 503: an API read ran longer than the read timeout and was cancelled. */
|
|
34
|
+
readonly QUERY_TIMEOUT: "ODATANO_QUERY_TIMEOUT";
|
|
35
|
+
/** 400: a read the indexes cannot answer without scanning a large table. */
|
|
36
|
+
readonly QUERY_NOT_INDEXED: "ODATANO_QUERY_NOT_INDEXED";
|
|
33
37
|
/** 500: unexpected internal error. */
|
|
34
38
|
readonly INTERNAL_ERROR: "ODATANO_INTERNAL_ERROR";
|
|
35
39
|
/** 503: HSM device or session not available. */
|
package/srv/utils/error-codes.js
CHANGED
|
@@ -33,6 +33,10 @@ exports.ERROR_CODES = {
|
|
|
33
33
|
PROVIDER_UNAVAILABLE: 'ODATANO_PROVIDER_UNAVAILABLE',
|
|
34
34
|
/** 503: a submit failed without a verdict; the transaction may still reach the chain. */
|
|
35
35
|
SUBMIT_OUTCOME_UNKNOWN: 'ODATANO_SUBMIT_OUTCOME_UNKNOWN',
|
|
36
|
+
/** 503: an API read ran longer than the read timeout and was cancelled. */
|
|
37
|
+
QUERY_TIMEOUT: 'ODATANO_QUERY_TIMEOUT',
|
|
38
|
+
/** 400: a read the indexes cannot answer without scanning a large table. */
|
|
39
|
+
QUERY_NOT_INDEXED: 'ODATANO_QUERY_NOT_INDEXED',
|
|
36
40
|
/** 500: unexpected internal error. */
|
|
37
41
|
INTERNAL_ERROR: 'ODATANO_INTERNAL_ERROR',
|
|
38
42
|
/** 503: HSM device or session not available. */
|
package/srv/utils/mappers.js
CHANGED
|
@@ -61,6 +61,7 @@ const deep_json_1 = require("./deep-json");
|
|
|
61
61
|
const cardano_costmodels_ts_1 = require("@harmoniclabs/cardano-costmodels-ts");
|
|
62
62
|
const logger = cds_1.default.log('mappers');
|
|
63
63
|
const errors_1 = require("./errors");
|
|
64
|
+
const read_limits_1 = require("./read-limits");
|
|
64
65
|
const const_1 = require("./const");
|
|
65
66
|
/** Key of a transaction's input/output rows: chain position, ascending, below 2^53 for any real slot. */
|
|
66
67
|
exports.TX_SEQ_SLOT_FACTOR = 65536;
|
|
@@ -684,6 +685,9 @@ function mapError(req, err, ctx) {
|
|
|
684
685
|
if (err instanceof errors_1.BackendError) {
|
|
685
686
|
return req.reject({ status: err.statusCode, code: err.code, message: fmt(err.code, ctx, err.message), target: err.target });
|
|
686
687
|
}
|
|
688
|
+
const timeout = (0, read_limits_1.queryTimeoutError)(err);
|
|
689
|
+
if (timeout)
|
|
690
|
+
return req.reject({ status: timeout.statusCode, code: timeout.code, message: fmt(timeout.code, ctx, timeout.message) });
|
|
687
691
|
const internalMsg = err instanceof Error ? err.message : String(err);
|
|
688
692
|
logger.error({ error: internalMsg }, `Unexpected error in ${ctx}`);
|
|
689
693
|
return req.reject(500, fmt('INTERNAL_ERROR', ctx, 'An internal error occurred'));
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import cds from '@sap/cds';
|
|
2
|
+
/** Entities of the read service whose tables grow with the chain. */
|
|
3
|
+
export declare const GUARDED_ENTITIES: readonly string[];
|
|
4
|
+
type Token = {
|
|
5
|
+
ref?: unknown[];
|
|
6
|
+
val?: unknown;
|
|
7
|
+
func?: string;
|
|
8
|
+
xpr?: Token[];
|
|
9
|
+
list?: Token[];
|
|
10
|
+
SELECT?: unknown;
|
|
11
|
+
} | string;
|
|
12
|
+
type OrderTerm = {
|
|
13
|
+
ref?: unknown[];
|
|
14
|
+
implicit?: boolean;
|
|
15
|
+
func?: string;
|
|
16
|
+
xpr?: unknown;
|
|
17
|
+
};
|
|
18
|
+
type Select = {
|
|
19
|
+
from?: {
|
|
20
|
+
ref?: unknown[];
|
|
21
|
+
};
|
|
22
|
+
where?: Token[];
|
|
23
|
+
orderBy?: OrderTerm[];
|
|
24
|
+
search?: unknown;
|
|
25
|
+
groupBy?: unknown[];
|
|
26
|
+
having?: unknown;
|
|
27
|
+
count?: boolean;
|
|
28
|
+
columns?: Array<{
|
|
29
|
+
func?: string;
|
|
30
|
+
as?: string;
|
|
31
|
+
}>;
|
|
32
|
+
};
|
|
33
|
+
type EntityDef = {
|
|
34
|
+
elements?: Record<string, {
|
|
35
|
+
key?: boolean;
|
|
36
|
+
isAssociation?: boolean;
|
|
37
|
+
keys?: Array<{
|
|
38
|
+
ref: string[];
|
|
39
|
+
}>;
|
|
40
|
+
'@cds.valid.from'?: boolean;
|
|
41
|
+
}>;
|
|
42
|
+
};
|
|
43
|
+
/** Primary key columns in table order; a managed association key becomes its foreign key columns. */
|
|
44
|
+
export declare function keyColumns(entity: EntityDef | undefined): string[];
|
|
45
|
+
/** Column lists of the primary key and of every secondary index on the table, lower case. */
|
|
46
|
+
export declare function indexColumnLists(entityName: string, entity: EntityDef | undefined): string[][];
|
|
47
|
+
interface WhereShape {
|
|
48
|
+
columns: Set<string>;
|
|
49
|
+
fixed: Set<string>;
|
|
50
|
+
narrowing: Set<string>;
|
|
51
|
+
unsupported: string | null;
|
|
52
|
+
}
|
|
53
|
+
/** The shape of a filter as the guard needs it. */
|
|
54
|
+
export declare function whereShape(where: Token[] | undefined): WhereShape;
|
|
55
|
+
/** The reason a read on `entityName` would scan its table, or null when an index answers it. */
|
|
56
|
+
export declare function unindexedReason(entityName: string, select: Select, entity: EntityDef | undefined): string | null;
|
|
57
|
+
/** The fields a filter may start with on `entityName`; named in the refusal. */
|
|
58
|
+
export declare function filterableFields(entityName: string, entity: EntityDef | undefined): string[];
|
|
59
|
+
/** Registers the guard on the read service; refuses with 400 before any handler reads. */
|
|
60
|
+
export declare function guardLargeReads(srv: Pick<cds.Service, 'before' | 'prepend'>): void;
|
|
61
|
+
export {};
|
|
62
|
+
//# sourceMappingURL=read-guard.d.ts.map
|
|
@@ -0,0 +1,179 @@
|
|
|
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.GUARDED_ENTITIES = void 0;
|
|
7
|
+
exports.keyColumns = keyColumns;
|
|
8
|
+
exports.indexColumnLists = indexColumnLists;
|
|
9
|
+
exports.whereShape = whereShape;
|
|
10
|
+
exports.unindexedReason = unindexedReason;
|
|
11
|
+
exports.filterableFields = filterableFields;
|
|
12
|
+
exports.guardLargeReads = guardLargeReads;
|
|
13
|
+
// Refuses reads on the large tables that no index can answer, so a client cannot make the
|
|
14
|
+
// database scan a whole table. Keyed reads, navigations and expands go by key and pass.
|
|
15
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
16
|
+
const errors_1 = require("./errors");
|
|
17
|
+
const error_codes_1 = require("./error-codes");
|
|
18
|
+
const db_indexes_1 = require("./db-indexes");
|
|
19
|
+
/** Entities of the read service whose tables grow with the chain. */
|
|
20
|
+
exports.GUARDED_ENTITIES = Object.freeze([
|
|
21
|
+
'Blocks', 'Transactions', 'TransactionInputs', 'TransactionOutputs', 'TransactionInputAssets',
|
|
22
|
+
'TransactionOutputAssets', 'TransactionMetadata', 'TransactionCertificates', 'TransactionWithdrawals',
|
|
23
|
+
'TransactionRedeemers', 'TransactionDatums', 'AssetHistory', 'Assets',
|
|
24
|
+
'LedgerUTxOs', 'LedgerUTxOAssets', 'LedgerAddresses', 'LedgerAddressAssets',
|
|
25
|
+
]);
|
|
26
|
+
const DB_NAMESPACE = 'odatano.cardano';
|
|
27
|
+
const lower = (s) => s.toLowerCase();
|
|
28
|
+
/** Primary key columns in table order; a managed association key becomes its foreign key columns. */
|
|
29
|
+
function keyColumns(entity) {
|
|
30
|
+
const elements = Object.entries(entity?.elements ?? {});
|
|
31
|
+
// a temporal table's primary key starts with validFrom, which the model does not mark as key
|
|
32
|
+
const out = elements.filter(([, el]) => el['@cds.valid.from']).map(([name]) => name);
|
|
33
|
+
for (const [name, el] of elements) {
|
|
34
|
+
if (!el.key)
|
|
35
|
+
continue;
|
|
36
|
+
if (el.isAssociation) {
|
|
37
|
+
for (const fk of el.keys ?? []) {
|
|
38
|
+
const col = `${name}_${fk.ref.join('_')}`;
|
|
39
|
+
if (!out.includes(col))
|
|
40
|
+
out.push(col);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
else if (!out.includes(name))
|
|
44
|
+
out.push(name);
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
/** Column lists of the primary key and of every secondary index on the table, lower case. */
|
|
49
|
+
function indexColumnLists(entityName, entity) {
|
|
50
|
+
const table = lower(`${DB_NAMESPACE}.${entityName}`.replace(/\./g, '_'));
|
|
51
|
+
const lists = [keyColumns(entity).map(lower)];
|
|
52
|
+
for (const spec of db_indexes_1.DB_INDEXES) {
|
|
53
|
+
if (lower(spec.table) !== table)
|
|
54
|
+
continue;
|
|
55
|
+
lists.push(spec.columns.split(',').map(c => lower(c.trim().split(/\s+/)[0])));
|
|
56
|
+
}
|
|
57
|
+
return lists.filter(l => l.length > 0);
|
|
58
|
+
}
|
|
59
|
+
const columnOf = (ref) => Array.isArray(ref) && ref.every(r => typeof r === 'string') ? lower(ref.join('_')) : null;
|
|
60
|
+
/** The shape of a filter as the guard needs it. */
|
|
61
|
+
function whereShape(where) {
|
|
62
|
+
const shape = { columns: new Set(), fixed: new Set(), narrowing: new Set(), unsupported: null };
|
|
63
|
+
const walk = (tokens) => {
|
|
64
|
+
for (const t of tokens) {
|
|
65
|
+
if (typeof t === 'string')
|
|
66
|
+
continue;
|
|
67
|
+
if (t.func)
|
|
68
|
+
shape.unsupported ??= `function ${t.func}`;
|
|
69
|
+
else if (t.SELECT)
|
|
70
|
+
shape.unsupported ??= 'subquery';
|
|
71
|
+
else if (t.ref) {
|
|
72
|
+
const col = columnOf(t.ref);
|
|
73
|
+
if (col)
|
|
74
|
+
shape.columns.add(col);
|
|
75
|
+
else
|
|
76
|
+
shape.unsupported ??= 'expression path';
|
|
77
|
+
}
|
|
78
|
+
if (t.xpr)
|
|
79
|
+
walk(t.xpr);
|
|
80
|
+
if (t.list)
|
|
81
|
+
walk(t.list);
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
walk(where ?? []);
|
|
85
|
+
const tokens = where ?? [];
|
|
86
|
+
const topLevelAnd = tokens.every(t => typeof t !== 'string' || !['or', 'not'].includes(lower(t)));
|
|
87
|
+
if (topLevelAnd) {
|
|
88
|
+
for (let i = 0; i + 2 < tokens.length; i++) {
|
|
89
|
+
const [a, op, b] = [tokens[i], tokens[i + 1], tokens[i + 2]];
|
|
90
|
+
if (op === 'is' && b === 'null' && typeof a === 'object' && a.ref) {
|
|
91
|
+
const col = columnOf(a.ref);
|
|
92
|
+
if (col)
|
|
93
|
+
shape.fixed.add(col);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (op !== '=')
|
|
97
|
+
continue;
|
|
98
|
+
const left = typeof a === 'object' && a.ref && typeof b === 'object' && 'val' in b ? columnOf(a.ref) : null;
|
|
99
|
+
const right = typeof b === 'object' && b.ref && typeof a === 'object' && 'val' in a ? columnOf(b.ref) : null;
|
|
100
|
+
const col = left ?? right;
|
|
101
|
+
const value = (typeof a === 'object' && 'val' in a ? a.val : typeof b === 'object' && 'val' in b ? b.val : null);
|
|
102
|
+
if (col)
|
|
103
|
+
shape.fixed.add(col);
|
|
104
|
+
if (col && value !== null)
|
|
105
|
+
shape.narrowing.add(col);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return shape;
|
|
109
|
+
}
|
|
110
|
+
/** True when `column` sits right after a prefix of an index that the filter fixes. */
|
|
111
|
+
function reachable(column, lists, fixed) {
|
|
112
|
+
return lists.some(list => {
|
|
113
|
+
const k = list.indexOf(column);
|
|
114
|
+
return k >= 0 && list.slice(0, k).every(c => fixed.has(c));
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
/** True when the sort columns continue an index after its fixed prefix, so the index delivers the order. */
|
|
118
|
+
function orderServed(order, lists, fixed) {
|
|
119
|
+
return lists.some(list => {
|
|
120
|
+
let k = 0;
|
|
121
|
+
while (k < list.length && fixed.has(list[k]) && list[k] !== order[0])
|
|
122
|
+
k++;
|
|
123
|
+
return order.every((c, i) => list[k + i] === c);
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
/** The reason a read on `entityName` would scan its table, or null when an index answers it. */
|
|
127
|
+
function unindexedReason(entityName, select, entity) {
|
|
128
|
+
const ref = select.from?.ref;
|
|
129
|
+
const head = ref?.[0];
|
|
130
|
+
if ((ref?.length ?? 0) > 1 || (head && typeof head === 'object' && head.where))
|
|
131
|
+
return null;
|
|
132
|
+
if (select.search)
|
|
133
|
+
return '$search is not supported on this entity set';
|
|
134
|
+
if (select.groupBy?.length || select.having)
|
|
135
|
+
return '$apply is not supported on this entity set';
|
|
136
|
+
const lists = indexColumnLists(entityName, entity);
|
|
137
|
+
const shape = whereShape(select.where);
|
|
138
|
+
if (shape.unsupported)
|
|
139
|
+
return `$filter uses a ${shape.unsupported}; filter with comparisons on indexed fields`;
|
|
140
|
+
for (const col of shape.columns) {
|
|
141
|
+
if (!reachable(col, lists, shape.fixed))
|
|
142
|
+
return `$filter on ${col} is not indexed`;
|
|
143
|
+
}
|
|
144
|
+
const counted = select.count === true || (select.columns?.some(c => c.func === 'count') ?? false);
|
|
145
|
+
if (counted && !select.where?.length)
|
|
146
|
+
return '$count needs a $filter on an indexed field';
|
|
147
|
+
const order = (select.orderBy ?? []).filter(o => !o.implicit);
|
|
148
|
+
if (order.some(o => !columnOf(o.ref)))
|
|
149
|
+
return '$orderby supports plain fields only';
|
|
150
|
+
const orderCols = order.map(o => columnOf(o.ref));
|
|
151
|
+
// after an equality on an indexed field few rows are left, so any order is cheap to sort
|
|
152
|
+
if (orderCols.length && shape.narrowing.size === 0 && !orderServed(orderCols, lists, shape.fixed)) {
|
|
153
|
+
return `$orderby on ${orderCols.join(', ')} needs an equality $filter or an index in that order`;
|
|
154
|
+
}
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
/** The fields a filter may start with on `entityName`; named in the refusal. */
|
|
158
|
+
function filterableFields(entityName, entity) {
|
|
159
|
+
const firsts = indexColumnLists(entityName, entity).map(l => l[0]);
|
|
160
|
+
return [...new Set(firsts)];
|
|
161
|
+
}
|
|
162
|
+
/** Registers the guard on the read service; refuses with 400 before any handler reads. */
|
|
163
|
+
function guardLargeReads(srv) {
|
|
164
|
+
const guarded = new Set(exports.GUARDED_ENTITIES);
|
|
165
|
+
srv.prepend(() => srv.before('READ', (req) => {
|
|
166
|
+
// in-process callers of a plugin host keep their queries; the guard covers HTTP requests
|
|
167
|
+
if (!req.context?.http)
|
|
168
|
+
return;
|
|
169
|
+
const name = req.target?.name?.split('.').pop();
|
|
170
|
+
if (!name || !guarded.has(name))
|
|
171
|
+
return;
|
|
172
|
+
const entity = cds_1.default.model?.definitions?.[`${DB_NAMESPACE}.${name}`];
|
|
173
|
+
const reason = unindexedReason(name, req.query?.SELECT ?? {}, entity);
|
|
174
|
+
if (!reason)
|
|
175
|
+
return;
|
|
176
|
+
throw new errors_1.BackendError(`${name}: ${reason} (indexed: ${filterableFields(name, entity).join(', ')})`, 400, error_codes_1.ERROR_CODES.QUERY_NOT_INDEXED);
|
|
177
|
+
}));
|
|
178
|
+
}
|
|
179
|
+
//# sourceMappingURL=read-guard.js.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import cds from '@sap/cds';
|
|
2
|
+
import { BackendError } from './errors';
|
|
3
|
+
/** PostgreSQL error code of a statement cancelled by statement_timeout. */
|
|
4
|
+
export declare const QUERY_CANCELED = "57014";
|
|
5
|
+
export declare function markLimited(context: unknown): void;
|
|
6
|
+
export declare function isLimited(context: unknown): boolean;
|
|
7
|
+
/** The 503 for a cancelled statement, or null for any other error. */
|
|
8
|
+
export declare function queryTimeoutError(err: unknown): BackendError | null;
|
|
9
|
+
/** Rewrites a cancelled statement in place, so a generic read answers 503 instead of 500. */
|
|
10
|
+
export declare function rewriteQueryTimeout(err: unknown): void;
|
|
11
|
+
type ServiceHooks = Pick<cds.Service, 'before' | 'on' | 'prepend'>;
|
|
12
|
+
/** Marks every HTTP request of `srv` as an API read; called once per service implementation. */
|
|
13
|
+
export declare function limitApiReads(srv: ServiceHooks): void;
|
|
14
|
+
type DbHooks = {
|
|
15
|
+
kind?: string;
|
|
16
|
+
after: (event: string, handler: (this: DbTx) => Promise<void>) => unknown;
|
|
17
|
+
};
|
|
18
|
+
type DbTx = {
|
|
19
|
+
context?: unknown;
|
|
20
|
+
exec: (sql: string) => Promise<unknown>;
|
|
21
|
+
};
|
|
22
|
+
/** Sets the timeout after BEGIN in every transaction of a marked context; PostgreSQL only. */
|
|
23
|
+
export declare function installReadTimeout(db?: DbHooks | undefined, ms?: number): boolean;
|
|
24
|
+
export {};
|
|
25
|
+
//# sourceMappingURL=read-limits.d.ts.map
|
|
@@ -0,0 +1,77 @@
|
|
|
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.QUERY_CANCELED = void 0;
|
|
7
|
+
exports.markLimited = markLimited;
|
|
8
|
+
exports.isLimited = isLimited;
|
|
9
|
+
exports.queryTimeoutError = queryTimeoutError;
|
|
10
|
+
exports.rewriteQueryTimeout = rewriteQueryTimeout;
|
|
11
|
+
exports.limitApiReads = limitApiReads;
|
|
12
|
+
exports.installReadTimeout = installReadTimeout;
|
|
13
|
+
// Statement timeout for reads that come in over the API. Crawler, backfills and worker run in
|
|
14
|
+
// contexts without an HTTP request and keep running without a limit.
|
|
15
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
16
|
+
const errors_1 = require("./errors");
|
|
17
|
+
const error_codes_1 = require("./error-codes");
|
|
18
|
+
const config_1 = require("../config");
|
|
19
|
+
const logger = cds_1.default.log('ReadLimits');
|
|
20
|
+
const INSTALLED = Symbol.for('odatano.readTimeout');
|
|
21
|
+
/** Contexts of API requests whose database transactions get the timeout. */
|
|
22
|
+
const limitedContexts = new WeakSet();
|
|
23
|
+
/** PostgreSQL error code of a statement cancelled by statement_timeout. */
|
|
24
|
+
exports.QUERY_CANCELED = '57014';
|
|
25
|
+
function markLimited(context) {
|
|
26
|
+
if (context && typeof context === 'object')
|
|
27
|
+
limitedContexts.add(context);
|
|
28
|
+
}
|
|
29
|
+
function isLimited(context) {
|
|
30
|
+
return Boolean(context && typeof context === 'object' && limitedContexts.has(context));
|
|
31
|
+
}
|
|
32
|
+
/** The 503 for a cancelled statement, or null for any other error. */
|
|
33
|
+
function queryTimeoutError(err) {
|
|
34
|
+
if (err?.code !== exports.QUERY_CANCELED)
|
|
35
|
+
return null;
|
|
36
|
+
return new errors_1.BackendError('The read took longer than the read timeout and was cancelled; narrow it with a filter on an indexed field', 503, error_codes_1.ERROR_CODES.QUERY_TIMEOUT);
|
|
37
|
+
}
|
|
38
|
+
/** Rewrites a cancelled statement in place, so a generic read answers 503 instead of 500. */
|
|
39
|
+
function rewriteQueryTimeout(err) {
|
|
40
|
+
const mapped = queryTimeoutError(err);
|
|
41
|
+
if (!mapped || !(err instanceof Error))
|
|
42
|
+
return;
|
|
43
|
+
const fields = err;
|
|
44
|
+
fields.status = mapped.statusCode;
|
|
45
|
+
fields.statusCode = mapped.statusCode;
|
|
46
|
+
fields.code = mapped.code;
|
|
47
|
+
fields.message = `[${mapped.code}] ${mapped.message}`;
|
|
48
|
+
}
|
|
49
|
+
/** Marks every HTTP request of `srv` as an API read; called once per service implementation. */
|
|
50
|
+
function limitApiReads(srv) {
|
|
51
|
+
// Synchronous and first, so the mark is set before any handler opens the transaction.
|
|
52
|
+
// cds.tx(req) opens its transaction with the request itself as context, so both are marked
|
|
53
|
+
srv.prepend(() => srv.before('*', (req) => {
|
|
54
|
+
const context = req.context;
|
|
55
|
+
if (!context?.http)
|
|
56
|
+
return;
|
|
57
|
+
markLimited(context);
|
|
58
|
+
markLimited(req);
|
|
59
|
+
}));
|
|
60
|
+
srv.on('error', (err) => rewriteQueryTimeout(err));
|
|
61
|
+
}
|
|
62
|
+
/** Sets the timeout after BEGIN in every transaction of a marked context; PostgreSQL only. */
|
|
63
|
+
function installReadTimeout(db = cds_1.default.db, ms = (0, config_1.loadReadTimeoutMs)()) {
|
|
64
|
+
if (!db || db.kind !== 'postgres' || ms <= 0)
|
|
65
|
+
return false;
|
|
66
|
+
const holder = db;
|
|
67
|
+
if (holder[INSTALLED])
|
|
68
|
+
return true;
|
|
69
|
+
db.after('BEGIN', async function () {
|
|
70
|
+
if (isLimited(this.context))
|
|
71
|
+
await this.exec(`SET LOCAL statement_timeout = ${ms}`);
|
|
72
|
+
});
|
|
73
|
+
holder[INSTALLED] = true;
|
|
74
|
+
logger.info(`API reads on PostgreSQL time out after ${ms} ms`);
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=read-limits.js.map
|
package/srv/utils/tx-utils.js
CHANGED
|
@@ -12,6 +12,7 @@ const cds_1 = __importDefault(require("@sap/cds"));
|
|
|
12
12
|
const errors_1 = require("./errors");
|
|
13
13
|
const config_1 = require("../config");
|
|
14
14
|
const error_codes_1 = require("./error-codes");
|
|
15
|
+
const read_limits_1 = require("./read-limits");
|
|
15
16
|
// @cap-js/sqlite has a single pooled connection held by the request transaction.
|
|
16
17
|
// A new root transaction awaited by that request would wait forever.
|
|
17
18
|
const logger = cds_1.default.log('tx-utils');
|
|
@@ -35,8 +36,16 @@ function holdsConnection(tx) {
|
|
|
35
36
|
// A transaction that already holds its connection does the read itself.
|
|
36
37
|
function readOutside(tx, read) {
|
|
37
38
|
const idle = typeof tx.begin === 'function' && !holdsConnection(tx);
|
|
39
|
+
if (!idle)
|
|
40
|
+
return read(tx);
|
|
41
|
+
// the short transaction keeps the read timeout of an API request
|
|
42
|
+
const limited = (0, read_limits_1.isLimited)(tx.context) || (0, read_limits_1.isLimited)(cds_1.default.context);
|
|
38
43
|
// cds.tx resolves to what the callback resolves to; its typing wraps that in a second promise
|
|
39
|
-
return
|
|
44
|
+
return runWithoutAmbientTx(async () => await cds_1.default.tx(async (db) => {
|
|
45
|
+
if (limited)
|
|
46
|
+
(0, read_limits_1.markLimited)(db.context);
|
|
47
|
+
return read(db);
|
|
48
|
+
}));
|
|
40
49
|
}
|
|
41
50
|
/** Thrown inside an orphaned `cds.tx` callback after its caller already timed out. */
|
|
42
51
|
class DetachedTxAbortedError extends Error {
|
package/srv/utils/types.d.ts
CHANGED
|
@@ -426,7 +426,7 @@ export type TxBuildRequest = {
|
|
|
426
426
|
referenceScript?: string;
|
|
427
427
|
/** Validity start in Posix ms (`invalidBefore`); builder default `now - 120_000` for script builds. */
|
|
428
428
|
validityStartMs?: string;
|
|
429
|
-
/** Validity end in Posix ms (`invalidAfter`, ledger TTL); builder default `now + 3_600_000
|
|
429
|
+
/** Validity end in Posix ms (`invalidAfter`, ledger TTL); builder default `now + 3_600_000`, at most 24 h ahead. */
|
|
430
430
|
validityEndMs?: string;
|
|
431
431
|
};
|
|
432
432
|
/** Mint/burn build request: mintActions and mintingPolicyScript required */
|