@odatano/core 2.0.0-rc.52 → 2.0.0-rc.54

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.
@@ -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
- { name: 'odatano_cardano_blocks_slot', table: 'odatano_cardano_Blocks', columns: 'slot' },
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 a composite entry above replaces; dropped at start. */
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. */
@@ -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. */
@@ -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,186 @@
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', 'LedgerAccounts',
25
+ 'AccountEpochSnapshots', 'PoolEpochSnapshots', 'DrepEpochSnapshots',
26
+ ]);
27
+ // One row per block: counting a slot or height range reads only the index, and stays fast.
28
+ const RANGE_COUNTS = new Set(['Blocks']);
29
+ const DB_NAMESPACE = 'odatano.cardano';
30
+ const lower = (s) => s.toLowerCase();
31
+ /** Primary key columns in table order; a managed association key becomes its foreign key columns. */
32
+ function keyColumns(entity) {
33
+ const elements = Object.entries(entity?.elements ?? {});
34
+ // a temporal table's primary key starts with validFrom, which the model does not mark as key
35
+ const out = elements.filter(([, el]) => el['@cds.valid.from']).map(([name]) => name);
36
+ for (const [name, el] of elements) {
37
+ if (!el.key)
38
+ continue;
39
+ if (el.isAssociation) {
40
+ for (const fk of el.keys ?? []) {
41
+ const col = `${name}_${fk.ref.join('_')}`;
42
+ if (!out.includes(col))
43
+ out.push(col);
44
+ }
45
+ }
46
+ else if (!out.includes(name))
47
+ out.push(name);
48
+ }
49
+ return out;
50
+ }
51
+ /** Column lists of the primary key and of every secondary index on the table, lower case. */
52
+ function indexColumnLists(entityName, entity) {
53
+ const table = lower(`${DB_NAMESPACE}.${entityName}`.replace(/\./g, '_'));
54
+ const lists = [keyColumns(entity).map(lower)];
55
+ for (const spec of db_indexes_1.DB_INDEXES) {
56
+ if (lower(spec.table) !== table)
57
+ continue;
58
+ lists.push(spec.columns.split(',').map(c => lower(c.trim().split(/\s+/)[0])));
59
+ }
60
+ return lists.filter(l => l.length > 0);
61
+ }
62
+ const columnOf = (ref) => Array.isArray(ref) && ref.every(r => typeof r === 'string') ? lower(ref.join('_')) : null;
63
+ /** The shape of a filter as the guard needs it. */
64
+ function whereShape(where) {
65
+ const shape = { columns: new Set(), fixed: new Set(), narrowing: new Set(), unsupported: null };
66
+ const walk = (tokens) => {
67
+ for (const t of tokens) {
68
+ if (typeof t === 'string')
69
+ continue;
70
+ if (t.func)
71
+ shape.unsupported ??= `function ${t.func}`;
72
+ else if (t.SELECT)
73
+ shape.unsupported ??= 'subquery';
74
+ else if (t.ref) {
75
+ const col = columnOf(t.ref);
76
+ if (col)
77
+ shape.columns.add(col);
78
+ else
79
+ shape.unsupported ??= 'expression path';
80
+ }
81
+ if (t.xpr)
82
+ walk(t.xpr);
83
+ if (t.list)
84
+ walk(t.list);
85
+ }
86
+ };
87
+ walk(where ?? []);
88
+ const tokens = where ?? [];
89
+ const topLevelAnd = tokens.every(t => typeof t !== 'string' || !['or', 'not'].includes(lower(t)));
90
+ if (topLevelAnd) {
91
+ for (let i = 0; i + 2 < tokens.length; i++) {
92
+ const [a, op, b] = [tokens[i], tokens[i + 1], tokens[i + 2]];
93
+ if (op === 'is' && b === 'null' && typeof a === 'object' && a.ref) {
94
+ const col = columnOf(a.ref);
95
+ if (col)
96
+ shape.fixed.add(col);
97
+ continue;
98
+ }
99
+ if (op !== '=')
100
+ continue;
101
+ const left = typeof a === 'object' && a.ref && typeof b === 'object' && 'val' in b ? columnOf(a.ref) : null;
102
+ const right = typeof b === 'object' && b.ref && typeof a === 'object' && 'val' in a ? columnOf(b.ref) : null;
103
+ const col = left ?? right;
104
+ const value = (typeof a === 'object' && 'val' in a ? a.val : typeof b === 'object' && 'val' in b ? b.val : null);
105
+ if (col)
106
+ shape.fixed.add(col);
107
+ if (col && value !== null)
108
+ shape.narrowing.add(col);
109
+ }
110
+ }
111
+ return shape;
112
+ }
113
+ /** True when `column` sits right after a prefix of an index that the filter fixes. */
114
+ function reachable(column, lists, fixed) {
115
+ return lists.some(list => {
116
+ const k = list.indexOf(column);
117
+ return k >= 0 && list.slice(0, k).every(c => fixed.has(c));
118
+ });
119
+ }
120
+ /** True when the sort columns continue an index after its fixed prefix, so the index delivers the order. */
121
+ function orderServed(order, lists, fixed) {
122
+ return lists.some(list => {
123
+ let k = 0;
124
+ while (k < list.length && fixed.has(list[k]) && list[k] !== order[0])
125
+ k++;
126
+ return order.every((c, i) => list[k + i] === c);
127
+ });
128
+ }
129
+ /** The reason a read on `entityName` would scan its table, or null when an index answers it. */
130
+ function unindexedReason(entityName, select, entity) {
131
+ const ref = select.from?.ref;
132
+ const head = ref?.[0];
133
+ if ((ref?.length ?? 0) > 1 || (head && typeof head === 'object' && head.where))
134
+ return null;
135
+ if (select.search)
136
+ return '$search is not supported on this entity set';
137
+ const aggregated = select.columns?.some(c => c.func && c.func !== 'count') ?? false;
138
+ if (select.groupBy?.length || select.having || aggregated)
139
+ return '$apply is not supported on this entity set';
140
+ const lists = indexColumnLists(entityName, entity);
141
+ const shape = whereShape(select.where);
142
+ if (shape.unsupported)
143
+ return `$filter uses a ${shape.unsupported}; filter with comparisons on indexed fields`;
144
+ for (const col of shape.columns) {
145
+ if (!reachable(col, lists, shape.fixed))
146
+ return `$filter on ${col} is not indexed`;
147
+ }
148
+ const counted = select.count === true || (select.columns?.some(c => c.func === 'count') ?? false);
149
+ if (counted && !select.where?.length)
150
+ return '$count needs a $filter on an indexed field';
151
+ // a range on a large table counts every row in it
152
+ if (counted && shape.narrowing.size === 0 && !RANGE_COUNTS.has(entityName))
153
+ return '$count needs an eq $filter on an indexed field';
154
+ const order = (select.orderBy ?? []).filter(o => !o.implicit);
155
+ if (order.some(o => !columnOf(o.ref)))
156
+ return '$orderby supports plain fields only';
157
+ const orderCols = order.map(o => columnOf(o.ref));
158
+ // after an equality on an indexed field few rows are left, so any order is cheap to sort
159
+ if (orderCols.length && shape.narrowing.size === 0 && !orderServed(orderCols, lists, shape.fixed)) {
160
+ return `$orderby on ${orderCols.join(', ')} needs an equality $filter or an index in that order`;
161
+ }
162
+ return null;
163
+ }
164
+ /** The fields a filter may start with on `entityName`; named in the refusal. */
165
+ function filterableFields(entityName, entity) {
166
+ const firsts = indexColumnLists(entityName, entity).map(l => l[0]);
167
+ return [...new Set(firsts)];
168
+ }
169
+ /** Registers the guard on the read service; refuses with 400 before any handler reads. */
170
+ function guardLargeReads(srv) {
171
+ const guarded = new Set(exports.GUARDED_ENTITIES);
172
+ srv.prepend(() => srv.before('READ', (req) => {
173
+ // in-process callers of a plugin host keep their queries; the guard covers HTTP requests
174
+ if (!req.context?.http)
175
+ return;
176
+ const name = req.target?.name?.split('.').pop();
177
+ if (!name || !guarded.has(name))
178
+ return;
179
+ const entity = cds_1.default.model?.definitions?.[`${DB_NAMESPACE}.${name}`];
180
+ const reason = unindexedReason(name, req.query?.SELECT ?? {}, entity);
181
+ if (!reason)
182
+ return;
183
+ throw new errors_1.BackendError(`${name}: ${reason} (indexed: ${filterableFields(name, entity).join(', ')})`, 400, error_codes_1.ERROR_CODES.QUERY_NOT_INDEXED);
184
+ }));
185
+ }
186
+ //# 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
@@ -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 idle ? runWithoutAmbientTx(async () => await cds_1.default.tx(read)) : read(tx);
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 {