@odatano/core 2.0.0-rc.15 → 2.0.0-rc.17

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/README.md CHANGED
@@ -125,6 +125,7 @@ Hand an agent a **scoped, budgeted token** instead of a user.
125
125
  AGENT_GRANTS_ENABLED=true # or cds.requires.odatano-core.agentGrants.enabled
126
126
  AGENT_GRANTS_DELEGATE=mocked # CAP auth kind that keeps authenticating non-token requests (default: configured kind)
127
127
  AGENT_GRANT_ADMIN_RATE_LIMIT=10 # grant administration calls per principal per hour (or agentGrants.adminRateLimit)
128
+ AGENT_TOKEN_CACHE_MS=10000 # a resolved token is reused this long before the row is read again; 0 = off (or agentGrants.tokenCacheMs)
128
129
  ```
129
130
 
130
131
  1. An **Admin** issues a grant (`POST /odata/v4/cardano-agent/CreateAgentGrant`): an allow list of
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.15",
3
+ "version": "2.0.0-rc.17",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
package/srv/server.js CHANGED
@@ -28,6 +28,8 @@ const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
28
28
  const errors_1 = require("./utils/errors");
29
29
  const network_context_1 = require("./utils/network-context");
30
30
  const db_sanitize_1 = require("./utils/db-sanitize");
31
+ const db_indexes_1 = require("./utils/db-indexes");
32
+ const pg_order_nulls_1 = require("./utils/pg-order-nulls");
31
33
  const crawler_1 = require("./blockchain/crawler");
32
34
  const wallet_worker_1 = require("./blockchain/wallet-worker");
33
35
  const agent_grants_config_1 = require("./utils/agent-grants-config");
@@ -180,6 +182,17 @@ async function initializeFromConfig(config, protocolParams, hsmConfig) {
180
182
  return;
181
183
  }
182
184
  hsmConfigInstance = hsmConfig;
185
+ // ORDER BY on Postgres without a NULLS clause for key / NOT NULL columns, so
186
+ // the indexes below serve `$top` and `$orderby` reads (srv/utils/pg-order-nulls.ts).
187
+ (0, pg_order_nulls_1.installPostgresOrderNulls)();
188
+ // The secondary indexes the model cannot declare (srv/utils/db-indexes.ts):
189
+ // idempotent, never fatal, before anything reads.
190
+ try {
191
+ await (0, db_indexes_1.ensureDbIndexes)();
192
+ }
193
+ catch (err) {
194
+ logger.warn('secondary indexes not ensured (non-fatal):', err);
195
+ }
183
196
  try {
184
197
  appContext = await initializeAppContext(config, protocolParams, hsmConfig);
185
198
  bootstrapError = null;
@@ -33,6 +33,17 @@ export declare const AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
33
33
  * this knob must not switch the whole feature off, unlike a wrong delegate.
34
34
  */
35
35
  export declare function loadGrantAdminRateLimit(env?: Record<string, string | undefined>): number;
36
+ export declare const AGENT_TOKEN_CACHE_MS_DEFAULT = 10000;
37
+ /**
38
+ * How long the transport lane may reuse a resolved token (the grant row) before
39
+ * it reads the database again: `agentGrants.tokenCacheMs`, then
40
+ * `AGENT_TOKEN_CACHE_MS`, default 10 s, 0 switches the cache off. Seconds, not
41
+ * minutes, on purpose: a busy grant sends many requests per second, so a few
42
+ * seconds already spare almost every lookup, while a revoke on ANOTHER replica
43
+ * is honoured at most this much later (on the same process it is immediate).
44
+ * An unusable value (not an integer, below 0) is logged once and falls back.
45
+ */
46
+ export declare function loadTokenCacheMs(env?: Record<string, string | undefined>): number;
36
47
  /** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
37
48
  export declare function configuredAuth(): Record<string, unknown>;
38
49
  /**
@@ -3,8 +3,9 @@ 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_GRANT_ADMIN_RATE_LIMIT_DEFAULT = exports.AGENT_GRANTS_DELEGATES = void 0;
6
+ exports.AGENT_TOKEN_CACHE_MS_DEFAULT = exports.AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = exports.AGENT_GRANTS_DELEGATES = void 0;
7
7
  exports.loadGrantAdminRateLimit = loadGrantAdminRateLimit;
8
+ exports.loadTokenCacheMs = loadTokenCacheMs;
8
9
  exports.configuredAuth = configuredAuth;
9
10
  exports.customAuthImpl = customAuthImpl;
10
11
  exports.loadAgentGrantsConfig = loadAgentGrantsConfig;
@@ -30,6 +31,28 @@ function loadGrantAdminRateLimit(env = process.env) {
30
31
  }
31
32
  return n;
32
33
  }
34
+ exports.AGENT_TOKEN_CACHE_MS_DEFAULT = 10_000;
35
+ /**
36
+ * How long the transport lane may reuse a resolved token (the grant row) before
37
+ * it reads the database again: `agentGrants.tokenCacheMs`, then
38
+ * `AGENT_TOKEN_CACHE_MS`, default 10 s, 0 switches the cache off. Seconds, not
39
+ * minutes, on purpose: a busy grant sends many requests per second, so a few
40
+ * seconds already spare almost every lookup, while a revoke on ANOTHER replica
41
+ * is honoured at most this much later (on the same process it is immediate).
42
+ * An unusable value (not an integer, below 0) is logged once and falls back.
43
+ */
44
+ function loadTokenCacheMs(env = process.env) {
45
+ const cfg = envRecord();
46
+ const raw = cfg.tokenCacheMs !== undefined ? cfg.tokenCacheMs : env.AGENT_TOKEN_CACHE_MS;
47
+ if (raw === undefined || raw === null || String(raw).trim() === '')
48
+ return exports.AGENT_TOKEN_CACHE_MS_DEFAULT;
49
+ const n = Number(raw);
50
+ if (!Number.isInteger(n) || n < 0) {
51
+ cds_1.default.log('ODATANO').warn(`AGENT_TOKEN_CACHE_MS "${String(raw)}" is not an integer >= 0; using ${exports.AGENT_TOKEN_CACHE_MS_DEFAULT}`);
52
+ return exports.AGENT_TOKEN_CACHE_MS_DEFAULT;
53
+ }
54
+ return n;
55
+ }
33
56
  function envRecord() {
34
57
  const requires = (cds_1.default.env?.requires ?? {});
35
58
  const core = (requires['odatano-core'] ?? {});
@@ -56,7 +56,7 @@ export declare const AGENT_WALLET_ACTIONS: ReadonlySet<string>;
56
56
  export declare const AGENT_ALWAYS_ALLOWED_EVENTS: ReadonlySet<string>;
57
57
  /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
58
58
  export declare const AGENT_JOB_KINDS: readonly string[];
59
- /** Forget every rate-limit window and re-read the limit from the config (tests). */
59
+ /** Forget every rate-limit window, the token cache and re-read the knobs from the config (tests). */
60
60
  export declare function __resetGrantRateLimiterForTests(): void;
61
61
  export interface AgentGrantRow {
62
62
  ID: string;
@@ -93,11 +93,18 @@ export type TokenResolution = {
93
93
  status: 401 | 410;
94
94
  message: string;
95
95
  };
96
+ /** Test seam: cache lifetime in ms for injected runners too (null = config, injected runners bypass). */
97
+ export declare function __setTokenCacheMsForTests(ms: number | null): void;
98
+ /** Drops the cached resolution of a grant (revoke, rotate, update). */
99
+ export declare function invalidateTokenCache(grantId: string): void;
100
+ /** Entries waiting in the token cache (monitoring, tests). */
101
+ export declare function tokenCacheSize(): number;
96
102
  /**
97
103
  * Authenticate a bearer token: prefix, hash lookup among ACTIVE grants (a
98
104
  * revoked grant is an unknown token, non-leaking), expiry. Detached from any
99
105
  * ambient transaction: the lane runs before the request transaction exists,
100
- * and on SQLite the pool holds one connection.
106
+ * and on SQLite the pool holds one connection. The lookup is cached for a few
107
+ * seconds (see the token cache above).
101
108
  */
102
109
  export declare function resolveAgentToken(token: string, runner?: Runner): Promise<TokenResolution>;
103
110
  /**
@@ -153,9 +160,10 @@ export interface RotatedAgentGrant {
153
160
  }
154
161
  /**
155
162
  * Replace the grant's token; the old one is an unknown token from the next
156
- * request (the lane reads tokenHash per request, so nothing needs invalidating;
157
- * a request in flight with the old token completes). Budget, wallet, allow
158
- * list and expiry survive. Null when the grant does not exist or is revoked.
163
+ * request on this process (its cache entry is dropped here; another replica
164
+ * keeps it for at most AGENT_TOKEN_CACHE_MS; a request in flight with the old
165
+ * token completes). Budget, wallet, allow list and expiry survive. Null when
166
+ * the grant does not exist or is revoked.
159
167
  */
160
168
  export declare function rotateAgentGrantToken(grantId: string, runner?: Runner): Promise<RotatedAgentGrant | null>;
161
169
  /** The editable grant fields, as a client sends them: absent = untouched, explicit null = cleared. */
@@ -36,6 +36,9 @@ exports.hashAgentToken = hashAgentToken;
36
36
  exports.agentPrincipalId = agentPrincipalId;
37
37
  exports.parseGrantList = parseGrantList;
38
38
  exports.agentGrantOf = agentGrantOf;
39
+ exports.__setTokenCacheMsForTests = __setTokenCacheMsForTests;
40
+ exports.invalidateTokenCache = invalidateTokenCache;
41
+ exports.tokenCacheSize = tokenCacheSize;
39
42
  exports.resolveAgentToken = resolveAgentToken;
40
43
  exports.makeAgentUser = makeAgentUser;
41
44
  exports.validateGrantInput = validateGrantInput;
@@ -149,10 +152,14 @@ function grantAdminLimiter() {
149
152
  grantAdminRateLimiter ??= new rate_limiter_1.RateLimiter({ windowMs: 60 * 60 * 1000, maxRequests: (0, agent_grants_config_1.loadGrantAdminRateLimit)() });
150
153
  return grantAdminRateLimiter;
151
154
  }
152
- /** Forget every rate-limit window and re-read the limit from the config (tests). */
155
+ /** Forget every rate-limit window, the token cache and re-read the knobs from the config (tests). */
153
156
  function __resetGrantRateLimiterForTests() {
154
157
  grantAdminRateLimiter = null;
155
158
  lastUsedTouched.clear();
159
+ tokenCache.clear();
160
+ tokenHashOfGrant.clear();
161
+ tokenCacheMs = null;
162
+ tokenCacheOverride = null;
156
163
  }
157
164
  function dbRunner() {
158
165
  return cds_1.default.db;
@@ -193,21 +200,80 @@ function agentGrantOf(req) {
193
200
  const ctx = cds_1.default.context;
194
201
  return ctx?.http?.req?.agentGrant ?? null;
195
202
  }
203
+ const TOKEN_CACHE_MAX = 10_000;
204
+ const tokenCache = new Map();
205
+ const tokenHashOfGrant = new Map();
206
+ let tokenCacheMs = null;
207
+ let tokenCacheOverride = null;
208
+ let tokenCacheGeneration = 0;
209
+ function tokenCacheTtl() {
210
+ if (tokenCacheOverride !== null)
211
+ return tokenCacheOverride;
212
+ tokenCacheMs ??= (0, agent_grants_config_1.loadTokenCacheMs)();
213
+ return tokenCacheMs;
214
+ }
215
+ /** Test seam: cache lifetime in ms for injected runners too (null = config, injected runners bypass). */
216
+ function __setTokenCacheMsForTests(ms) {
217
+ tokenCacheOverride = ms;
218
+ tokenCache.clear();
219
+ tokenHashOfGrant.clear();
220
+ }
221
+ /** Drops the cached resolution of a grant (revoke, rotate, update). */
222
+ function invalidateTokenCache(grantId) {
223
+ tokenCacheGeneration++;
224
+ const hash = tokenHashOfGrant.get(grantId);
225
+ if (hash !== undefined) {
226
+ tokenCache.delete(hash);
227
+ tokenHashOfGrant.delete(grantId);
228
+ }
229
+ }
230
+ /** Entries waiting in the token cache (monitoring, tests). */
231
+ function tokenCacheSize() {
232
+ return tokenCache.size;
233
+ }
234
+ function rememberToken(hash, grant, ttl) {
235
+ if (tokenCache.size >= TOKEN_CACHE_MAX) {
236
+ // Bounded: a flood of distinct tokens must not grow the map without end.
237
+ tokenCache.clear();
238
+ tokenHashOfGrant.clear();
239
+ }
240
+ tokenCache.set(hash, { grant, until: Date.now() + ttl });
241
+ tokenHashOfGrant.set(grant.ID, hash);
242
+ }
196
243
  /**
197
244
  * Authenticate a bearer token: prefix, hash lookup among ACTIVE grants (a
198
245
  * revoked grant is an unknown token, non-leaking), expiry. Detached from any
199
246
  * ambient transaction: the lane runs before the request transaction exists,
200
- * and on SQLite the pool holds one connection.
247
+ * and on SQLite the pool holds one connection. The lookup is cached for a few
248
+ * seconds (see the token cache above).
201
249
  */
202
250
  async function resolveAgentToken(token, runner = dbRunner()) {
203
251
  if (typeof token !== 'string' || !token.startsWith(exports.AGENT_TOKEN_PREFIX)) {
204
252
  return { ok: false, status: 401, message: 'invalid agent token' };
205
253
  }
206
- const grant = (await (0, tx_utils_1.runWithoutAmbientTx)(() => runner.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ tokenHash: hashAgentToken(token), isActive: true }))));
254
+ const hash = hashAgentToken(token);
255
+ const ttl = tokenCacheTtl();
256
+ const cacheable = ttl > 0 && (tokenCacheOverride !== null || runner === dbRunner());
257
+ if (cacheable) {
258
+ const hit = tokenCache.get(hash);
259
+ if (hit && hit.until > Date.now()) {
260
+ if (isExpired(hit.grant))
261
+ return { ok: false, status: 410, message: 'agent grant expired' };
262
+ return { ok: true, grant: hit.grant };
263
+ }
264
+ if (hit)
265
+ tokenCache.delete(hash);
266
+ }
267
+ const generation = tokenCacheGeneration;
268
+ const grant = (await (0, tx_utils_1.runWithoutAmbientTx)(() => runner.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ tokenHash: hash, isActive: true }))));
207
269
  if (!grant)
208
270
  return { ok: false, status: 401, message: 'invalid agent token' };
209
271
  if (isExpired(grant))
210
272
  return { ok: false, status: 410, message: 'agent grant expired' };
273
+ // Not remembered when a revoke / rotate / update ran while the SELECT was in
274
+ // flight: the row read before the UPDATE would outlive the invalidation.
275
+ if (cacheable && generation === tokenCacheGeneration)
276
+ rememberToken(hash, grant, ttl);
211
277
  return { ok: true, grant };
212
278
  }
213
279
  /**
@@ -333,21 +399,24 @@ async function revokeAgentGrantById(grantId, runner = dbRunner()) {
333
399
  .set({ isActive: false, revokedAt: new Date().toISOString() })
334
400
  .where({ ID: grantId, isActive: true }));
335
401
  const revoked = Number(affected) > 0;
402
+ invalidateTokenCache(grantId);
336
403
  if (revoked)
337
404
  logger.info(`agent grant ${grantId} revoked`);
338
405
  return revoked;
339
406
  }
340
407
  /**
341
408
  * Replace the grant's token; the old one is an unknown token from the next
342
- * request (the lane reads tokenHash per request, so nothing needs invalidating;
343
- * a request in flight with the old token completes). Budget, wallet, allow
344
- * list and expiry survive. Null when the grant does not exist or is revoked.
409
+ * request on this process (its cache entry is dropped here; another replica
410
+ * keeps it for at most AGENT_TOKEN_CACHE_MS; a request in flight with the old
411
+ * token completes). Budget, wallet, allow list and expiry survive. Null when
412
+ * the grant does not exist or is revoked.
345
413
  */
346
414
  async function rotateAgentGrantToken(grantId, runner = dbRunner()) {
347
415
  if (!grantId)
348
416
  return null;
349
417
  const token = exports.AGENT_TOKEN_PREFIX + node_crypto_1.default.randomBytes(TOKEN_BYTES).toString('hex');
350
418
  const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set({ tokenHash: hashAgentToken(token) }).where({ ID: grantId, isActive: true }));
419
+ invalidateTokenCache(grantId);
351
420
  if (Number(affected) === 0)
352
421
  return null;
353
422
  logger.info(`agent grant ${grantId} token rotated`);
@@ -405,6 +474,7 @@ async function updateAgentGrant(grantId, input, runner = dbRunner()) {
405
474
  return { ok: true, grantId, updated: [] };
406
475
  // Conditional on isActive: a concurrent revoke wins over the edit.
407
476
  const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set(patch).where({ ID: grantId, isActive: true }));
477
+ invalidateTokenCache(grantId);
408
478
  if (Number(affected) === 0)
409
479
  return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
410
480
  logger.info(`agent grant ${grantId} updated (${updated.join(', ')})`);
@@ -810,7 +880,9 @@ function bufferUsage(key, calls, refunded) {
810
880
  }
811
881
  else
812
882
  usageBuffer.set(k, { ...key, calls, refunded });
813
- if (!usageFlushTimer) {
883
+ // Under a test override the tests flush explicitly: a timer racing them drained
884
+ // the buffer mid-test on a slow run (seen in the full unit suite, 2026-09-23).
885
+ if (!usageFlushTimer && !usageModeOverride) {
814
886
  usageFlushTimer = setTimeout(() => {
815
887
  usageFlushTimer = null;
816
888
  void flushGrantUsage().catch((err) => logger.warn(`usage flush failed: ${String(err?.message ?? err)}`));
@@ -831,6 +903,11 @@ function bufferUsage(key, calls, refunded) {
831
903
  async function flushGrantUsage(runner = dbRunner()) {
832
904
  if (usageBuffer.size === 0)
833
905
  return { flushed: 0, failed: 0 };
906
+ if (!runner) {
907
+ // No database service yet (early boot, tests without cds.db): keep the deltas.
908
+ logger.debug('usage flush skipped: no database service');
909
+ return { flushed: 0, failed: usageBuffer.size };
910
+ }
834
911
  const batch = [...usageBuffer.values()];
835
912
  usageBuffer.clear();
836
913
  const br = { runner, detached: true };
@@ -0,0 +1,30 @@
1
+ export interface IndexSpec {
2
+ /** Index name; lower case, table-prefixed, so it cannot collide across tables. */
3
+ name: string;
4
+ /** Table name as @cap-js creates it (namespace_Entity). */
5
+ table: string;
6
+ /** Column list, comma separated, in the order the lookups use. */
7
+ columns: string;
8
+ /** PostgreSQL spelling when it differs (SQLite knows no NULLS in an index definition). */
9
+ postgres?: string;
10
+ }
11
+ /** Every entry answers a query the service or the crawler actually runs (see the module doc). */
12
+ export declare const DB_INDEXES: readonly IndexSpec[];
13
+ /** The statement for one entry; exported so tests pin the shape. */
14
+ export declare function indexStatement(spec: IndexSpec, kind?: string): string;
15
+ /** Anything that runs a plain SQL string: the primary db service. */
16
+ export type SqlRunner = {
17
+ run: (sql: string) => Promise<unknown>;
18
+ kind?: string;
19
+ };
20
+ /**
21
+ * Creates every index that does not exist yet. Returns the names it ran;
22
+ * a failing statement is logged and skipped (a missing table on a partial
23
+ * deployment, a database without the privilege), the others still run.
24
+ * On HANA nothing runs (see the module doc).
25
+ */
26
+ export declare function ensureDbIndexes(runner?: SqlRunner | undefined): Promise<{
27
+ ensured: string[];
28
+ failed: string[];
29
+ }>;
30
+ //# sourceMappingURL=db-indexes.d.ts.map
@@ -0,0 +1,104 @@
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.DB_INDEXES = void 0;
7
+ exports.indexStatement = indexStatement;
8
+ exports.ensureDbIndexes = ensureDbIndexes;
9
+ /**
10
+ * Secondary indexes the CDS model cannot declare. `cds deploy` creates the
11
+ * primary keys only, and the temporal entities (Assets, Pools, Accounts,
12
+ * Addresses, AddressUTxOs, ...) carry `validFrom` FIRST in their key, so every
13
+ * lookup by unit / poolId / stakeAddress / address scanned the table; Blocks
14
+ * by height (ORDER BY height DESC is the "latest block" read), by slot and by
15
+ * epoch, Transactions by block, TransactionMetadata by tx and AssetHistory by
16
+ * tx (crawler rollback) had no index at all. Measured on the hosted preprod
17
+ * box on 2026-09-23 (930k blocks, 1.4M transactions, 521k metadata rows):
18
+ * latest block 200 ms, GetMetadataByTxHash 1.0 s, GetAssetInfo 78 ms, a
19
+ * block by height 168 ms; with the indexes 0.2 ms each.
20
+ *
21
+ * Created at start with CREATE INDEX IF NOT EXISTS: idempotent, plain SQL
22
+ * that SQLite and PostgreSQL both accept, identifiers unquoted so Postgres
23
+ * folds them exactly like @cap-js/postgres folds the table names. A plain
24
+ * CREATE INDEX locks the table against writes for the build; on a large
25
+ * live PostgreSQL create them once beforehand with CONCURRENTLY (ODATANO
26
+ * ACCESS's scripts/odatano-indexes-on-box.sh does that), then this is a
27
+ * no-op at every boot. A failure is logged, never fatal: the service works
28
+ * without them, only slower.
29
+ *
30
+ * HANA is skipped: its CREATE INDEX knows neither IF NOT EXISTS nor NULLS
31
+ * LAST, and the column store keeps an inverted index per column anyway, so
32
+ * these lookups do not scan there.
33
+ */
34
+ const cds_1 = __importDefault(require("@sap/cds"));
35
+ const logger = cds_1.default.log('DbIndexes');
36
+ /** Every entry answers a query the service or the crawler actually runs (see the module doc). */
37
+ exports.DB_INDEXES = Object.freeze([
38
+ // Blocks: latest (ORDER BY height DESC), byHeight, crawler `height in`, rollback `slot >`, epoch filters
39
+ { name: 'odatano_cardano_blocks_height', table: 'odatano_cardano_Blocks', columns: 'height' },
40
+ // CAP renders `$orderby=height desc` as ORDER BY height DESC NULLS LAST, which the
41
+ // plain (ASC NULLS LAST) index cannot serve backwards (200 ms sort on the box
42
+ // with the plain index in place). This one serves it, and ASC NULLS FIRST
43
+ // backwards; the plain one stays for plain ASC and equality.
44
+ { name: 'odatano_cardano_blocks_height_desc', table: 'odatano_cardano_Blocks', columns: 'height DESC', postgres: 'height DESC NULLS LAST' },
45
+ { name: 'odatano_cardano_blocks_slot', table: 'odatano_cardano_Blocks', columns: 'slot' },
46
+ { name: 'odatano_cardano_blocks_epoch', table: 'odatano_cardano_Blocks', columns: 'epochNumber' },
47
+ // Transactions of a block (rollback `blockHash in`, OData filters by block / height)
48
+ { name: 'odatano_cardano_transactions_block', table: 'odatano_cardano_Transactions', columns: 'blockHash' },
49
+ { name: 'odatano_cardano_transactions_height', table: 'odatano_cardano_Transactions', columns: 'blockHeight' },
50
+ // GetMetadataByTxHash, rollback
51
+ { name: 'odatano_cardano_transactionmetadata_tx', table: 'odatano_cardano_TransactionMetadata', columns: 'tx_hash' },
52
+ // rollback `txHash in` (key is unit, txHash)
53
+ { name: 'odatano_cardano_assethistory_tx', table: 'odatano_cardano_AssetHistory', columns: 'txHash' },
54
+ // temporal entities: the business key behind validFrom
55
+ { name: 'odatano_cardano_assets_unit', table: 'odatano_cardano_Assets', columns: 'unit' },
56
+ { name: 'odatano_cardano_addresses_address', table: 'odatano_cardano_Addresses', columns: 'address' },
57
+ { name: 'odatano_cardano_addressutxos_address', table: 'odatano_cardano_AddressUTxOs', columns: 'address_address' },
58
+ { name: 'odatano_cardano_addressassets_address', table: 'odatano_cardano_AddressAssets', columns: 'address_address' },
59
+ { name: 'odatano_cardano_utxoassets_address', table: 'odatano_cardano_UTxOAssets', columns: 'utxo_address_address' },
60
+ { name: 'odatano_cardano_addresstransactions_tx', table: 'odatano_cardano_AddressTransactions', columns: 'tx_hash' },
61
+ { name: 'odatano_cardano_accounts_stake', table: 'odatano_cardano_Accounts', columns: 'stakeAddress' },
62
+ { name: 'odatano_cardano_pools_poolid', table: 'odatano_cardano_Pools', columns: 'poolId' },
63
+ { name: 'odatano_cardano_dreps_drepid', table: 'odatano_cardano_Dreps', columns: 'drepId' },
64
+ // agent token lane: one lookup by token hash per request
65
+ { name: 'odatano_cardano_cardanoagentgrants_token', table: 'odatano_cardano_CardanoAgentGrants', columns: 'tokenHash' },
66
+ ]);
67
+ /** The statement for one entry; exported so tests pin the shape. */
68
+ function indexStatement(spec, kind = 'sqlite') {
69
+ const columns = kind === 'postgres' && spec.postgres ? spec.postgres : spec.columns;
70
+ return `CREATE INDEX IF NOT EXISTS ${spec.name} ON ${spec.table} (${columns})`;
71
+ }
72
+ /**
73
+ * Creates every index that does not exist yet. Returns the names it ran;
74
+ * a failing statement is logged and skipped (a missing table on a partial
75
+ * deployment, a database without the privilege), the others still run.
76
+ * On HANA nothing runs (see the module doc).
77
+ */
78
+ async function ensureDbIndexes(runner = cds_1.default.db) {
79
+ const ensured = [];
80
+ const failed = [];
81
+ if (!runner) {
82
+ logger.debug('no database service connected, indexes skipped');
83
+ return { ensured, failed };
84
+ }
85
+ const kind = String(runner.kind ?? 'sqlite');
86
+ if (kind === 'hana') {
87
+ logger.info('HANA: secondary indexes not created (column store, no IF NOT EXISTS)');
88
+ return { ensured, failed };
89
+ }
90
+ for (const spec of exports.DB_INDEXES) {
91
+ try {
92
+ await runner.run(indexStatement(spec, kind));
93
+ ensured.push(spec.name);
94
+ }
95
+ catch (err) {
96
+ failed.push(spec.name);
97
+ logger.warn(`index ${spec.name} on ${spec.table} not ensured: ${String(err?.message ?? err)}`);
98
+ }
99
+ }
100
+ if (failed.length === 0)
101
+ logger.info(`${ensured.length} indexes ensured`);
102
+ return { ensured, failed };
103
+ }
104
+ //# sourceMappingURL=db-indexes.js.map
@@ -0,0 +1,14 @@
1
+ interface OrderTerm {
2
+ nulls?: string;
3
+ element?: {
4
+ key?: boolean;
5
+ notNull?: boolean;
6
+ '@cds.valid.from'?: boolean;
7
+ };
8
+ }
9
+ /** Strips the null placement from the rendered terms whose column cannot be NULL. */
10
+ export declare function stripNullsForNotNull(orderBy: OrderTerm[], rendered: string[]): string[];
11
+ /** Wraps the driver's `_orderBy` once; returns false when the driver or the hook is missing. */
12
+ export declare function installPostgresOrderNulls(): boolean;
13
+ export {};
14
+ //# sourceMappingURL=pg-order-nulls.d.ts.map
@@ -0,0 +1,76 @@
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.stripNullsForNotNull = stripNullsForNotNull;
7
+ exports.installPostgresOrderNulls = installPostgresOrderNulls;
8
+ /**
9
+ * ORDER BY on PostgreSQL: no NULLS clause for NOT NULL columns.
10
+ *
11
+ * @cap-js/postgres renders every ordering term with an explicit null placement,
12
+ * `ASC NULLS FIRST` and `DESC NULLS LAST`, to give SQLite's and HANA's null
13
+ * order on Postgres too. A Postgres btree index is `ASC NULLS LAST` (read
14
+ * backwards `DESC NULLS FIRST`), the opposite placement, so the planner
15
+ * cannot use an index for such an ORDER BY and sorts the whole table before
16
+ * the LIMIT. CAP orders every `$top` read by the entity key, so on the hosted
17
+ * box `Blocks?$top=1` took 0.8 to 7.6 s over 2M rows in NIGHTGATE and every
18
+ * `$top` on a large ODATANO table sorted the same way (measured 2026-09-23,
19
+ * `ORDER BY "$b".ID ASC NULLS FIRST LIMIT 1`, parallel seq scan + top-N sort).
20
+ *
21
+ * A key column, a `not null` column and a temporal `@cds.valid.from` column
22
+ * (part of the persisted primary key, NOT NULL, but neither `key` nor
23
+ * `notNull` in the linked model) hold no NULL, so the placement is
24
+ * meaningless there and is dropped; the plain `ASC` / `DESC` then matches the
25
+ * primary key and the secondary indexes. Nullable columns keep the clause (the
26
+ * semantics stay SQLite's); an explicit `nulls` on the term is always kept.
27
+ * Installed once at start on the Postgres renderer class; a driver without the
28
+ * hook (or no Postgres driver at all) leaves everything as it is, with a
29
+ * warning when the deployment runs on Postgres.
30
+ */
31
+ const cds_1 = __importDefault(require("@sap/cds"));
32
+ const logger = cds_1.default.log('PgOrderNulls');
33
+ const INSTALLED = Symbol.for('odatano.pgOrderNulls');
34
+ /** Strips the null placement from the rendered terms whose column cannot be NULL. */
35
+ function stripNullsForNotNull(orderBy, rendered) {
36
+ return rendered.map((sql, i) => {
37
+ const c = orderBy[i];
38
+ if (!c || c.nulls)
39
+ return sql;
40
+ const el = c.element;
41
+ if (el && (el.key === true || el.notNull === true || el['@cds.valid.from'] === true))
42
+ return sql.replace(/ NULLS (FIRST|LAST)$/, '');
43
+ return sql;
44
+ });
45
+ }
46
+ /** Wraps the driver's `_orderBy` once; returns false when the driver or the hook is missing. */
47
+ function installPostgresOrderNulls() {
48
+ let PostgresService;
49
+ try {
50
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
51
+ PostgresService = require('@cap-js/postgres/lib/PostgresService');
52
+ }
53
+ catch (err) {
54
+ // No Postgres driver in this deployment, or a driver that no longer exposes
55
+ // the module: silent unless the database IS Postgres.
56
+ const dbKind = String((cds_1.default.env?.requires?.db)?.kind ?? '');
57
+ if (dbKind === 'postgres')
58
+ logger.warn(`@cap-js/postgres/lib/PostgresService not loadable, ORDER BY keeps the NULLS clause: ${String(err?.message ?? err)}`);
59
+ return false;
60
+ }
61
+ const proto = PostgresService.CQN2SQL?.prototype;
62
+ const orig = proto?._orderBy;
63
+ if (!proto || typeof orig !== 'function') {
64
+ logger.warn('@cap-js/postgres has no _orderBy hook; ORDER BY keeps the NULLS clause (indexes will not serve ordered reads)');
65
+ return false;
66
+ }
67
+ if (proto[INSTALLED])
68
+ return true;
69
+ proto._orderBy = function (orderBy, ...rest) {
70
+ return stripNullsForNotNull(orderBy, orig.call(this, orderBy, ...rest));
71
+ };
72
+ proto[INSTALLED] = true;
73
+ logger.info('ORDER BY on Postgres: NULLS clause dropped for key and NOT NULL columns');
74
+ return true;
75
+ }
76
+ //# sourceMappingURL=pg-order-nulls.js.map