@odatano/core 2.0.0-rc.14 → 2.0.0-rc.16

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,179 +1,179 @@
1
- {
2
- "name": "@odatano/core",
3
- "version": "2.0.0-rc.14",
4
- "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
- "imports": {
6
- "#cds-models/*": "./@cds-models/*/index.js"
7
- },
8
- "main": "src/index.js",
9
- "types": "src/index.d.ts",
10
- "files": [
11
- "cds-plugin.js",
12
- "src/**/*.js",
13
- "src/**/*.d.ts",
14
- "srv/**/*.js",
15
- "srv/**/*.d.ts",
16
- "srv/**/*.cds",
17
- "db/**/*.cds",
18
- "@cds-models/"
19
- ],
20
- "engines": {
21
- "node": ">=22.5"
22
- },
23
- "peerDependencies": {
24
- "@sap/cds": ">=10"
25
- },
26
- "dependencies": {
27
- "@blockfrost/blockfrost-js": "~6.0.0",
28
- "@cap-js/hana": "^3",
29
- "@cardano-ogmios/client": "^6.14.0",
30
- "@harmoniclabs/buildooor": "0.2.9",
31
- "@harmoniclabs/cardano-costmodels-ts": "~1.6.1",
32
- "@harmoniclabs/cardano-ledger-ts": "^0.5.6",
33
- "@harmoniclabs/cbor": "^2.0.1",
34
- "@harmoniclabs/crypto": "^0.3.0",
35
- "@harmoniclabs/uint8array-utils": "^1.0.4",
36
- "@odatano/cap-auth": "^0.1.0",
37
- "@sap/xssec": "^4",
38
- "axios": "^1.18.0",
39
- "bech32": "^2.0.0",
40
- "blake2b": "^2.1.4"
41
- },
42
- "optionalDependencies": {
43
- "pkcs11js": "^2.1.6"
44
- },
45
- "overrides": {
46
- "axios": "^1.18.0",
47
- "esbuild": "0.28.1",
48
- "form-data": "^4.0.6",
49
- "fast-uri": "^3.1.7",
50
- "ws": "7.5.11",
51
- "@sap/approuter": {
52
- "body-parser": "^2.2.3"
53
- }
54
- },
55
- "devDependencies": {
56
- "@cap-js/cds-test": "^0.4.1",
57
- "@cap-js/cds-typer": "^0.40.0",
58
- "@cap-js/cds-types": "^0.18.0",
59
- "@cap-js/postgres": "^3.1.1",
60
- "@cap-js/sqlite": "^3",
61
- "@sap/cds": "^10",
62
- "@sap/cds-dk": "^10",
63
- "@sap/eslint-plugin-cds": "^4.2.4",
64
- "@types/blake2b": "^2.1.3",
65
- "@types/node": "^22.19.7",
66
- "@typescript-eslint/eslint-plugin": "^8.50.1",
67
- "@typescript-eslint/parser": "^8.50.1",
68
- "@vitest/coverage-v8": "^4.1.10",
69
- "dotenv": "^16.3.1",
70
- "eslint": "^9.39.2",
71
- "nock": "^13.5.6",
72
- "ts-node": "^10.9.2",
73
- "tsx": "^4.21.0",
74
- "typescript": "^5.9.3",
75
- "vitest": "^4.1.10"
76
- },
77
- "cds": {
78
- "typer": {
79
- "ieee754compatible": true
80
- },
81
- "build": {
82
- "tasks": [
83
- {
84
- "for": "node-cf",
85
- "src": "srv",
86
- "dest": "../gen/srv"
87
- },
88
- {
89
- "for": "hana",
90
- "src": "db",
91
- "dest": "../gen/db"
92
- }
93
- ]
94
- },
95
- "requires": {
96
- "db": {
97
- "kind": "sqlite",
98
- "credentials": {
99
- "url": "db.sqlite"
100
- },
101
- "client": {
102
- "timeout": 5000
103
- }
104
- },
105
- "[production]": {
106
- "db": {
107
- "kind": "hana",
108
- "pool": {
109
- "acquireTimeoutMillis": 30000,
110
- "min": 0,
111
- "max": 10
112
- }
113
- },
114
- "auth": "xsuaa"
115
- }
116
- }
117
- },
118
- "scripts": {
119
- "clean": "node -e \"const fs=require('fs');fs.globSync('{srv,db,src}/**/*.{js,js.map,d.ts,d.ts.map}').filter(f=>!f.includes('node_modules')).forEach(f=>fs.unlinkSync(f));console.log('Clean complete')\"",
120
- "clean:models": "node -e \"require('fs').rmSync('@cds-models',{recursive:true,force:true});console.log('Removed @cds-models')\"",
121
- "build": "npm run cds:types && tsc",
122
- "build:plugin": "npm run cds:types && tsc -p tsconfig.build.json",
123
- "build:package": "npm run clean && npm run clean:models && npm run build:plugin",
124
- "prepare": "npm run build:package",
125
- "start": "cds-serve",
126
- "cds:watch": "cds watch",
127
- "cds:serve": "cds serve --with-mocks",
128
- "cds:types": "cds-typer \"*\" --outputDirectory @cds-models",
129
- "lint": "eslint .",
130
- "typecheck": "tsc --noEmit",
131
- "db:deploy": "cds deploy",
132
- "pretest": "npm run clean && npm run cds:types && npm run db:deploy",
133
- "test": "vitest run",
134
- "pretest:coverage": "npm run clean && npm run cds:types && npm run db:deploy",
135
- "test:coverage": "vitest run --coverage",
136
- "pretest:ci": "npm run clean && npm run cds:types && npm run db:deploy",
137
- "test:ci": "vitest run --exclude \"**/core-ogmios.test.ts\"",
138
- "pretest:ci:coverage": "npm run clean && npm run cds:types && npm run db:deploy",
139
- "test:ci:coverage": "vitest run --coverage --exclude \"**/core-ogmios.test.ts\"",
140
- "pretest:integration": "npm run clean && npm run cds:types && npm run db:deploy",
141
- "test:integration": "vitest run --project integration",
142
- "test:integration:blockfrost": "vitest run test/integration/core.blockfrost.test.ts",
143
- "test:integration:koios": "vitest run test/integration/core.koios.test.ts",
144
- "test:integration:ogmios": "vitest run test/integration/core-ogmios.test.ts",
145
- "test:integration:both": "npm run test:integration:blockfrost && npm run test:integration:koios",
146
- "pretest:unit": "npm run cds:types",
147
- "test:unit": "vitest run --project unit",
148
- "watch-odatano": "cds watch --open odatano/index.html?sap-ui-xx-viewCache=false --livereload false",
149
- "watch-wallet": "cds watch --open wallet/webapp/index.html",
150
- "release:check": "node scripts/release-check.mjs"
151
- },
152
- "sapux": [
153
- "app/odatano"
154
- ],
155
- "directories": {
156
- "doc": "docs",
157
- "test": "test"
158
- },
159
- "repository": {
160
- "type": "git",
161
- "url": "git+https://github.com/ODATANO/ODATANO.git"
162
- },
163
- "keywords": [
164
- "CAP",
165
- "CDS",
166
- "plugin",
167
- "Cardano",
168
- "blockchain",
169
- "OData",
170
- "SAP"
171
- ],
172
- "author": "Maximilian Weber",
173
- "license": "Apache-2.0",
174
- "type": "commonjs",
175
- "bugs": {
176
- "url": "https://github.com/ODATANO/ODATANO/issues"
177
- },
178
- "homepage": "https://github.com/ODATANO/ODATANO#readme"
179
- }
1
+ {
2
+ "name": "@odatano/core",
3
+ "version": "2.0.0-rc.16",
4
+ "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
+ "imports": {
6
+ "#cds-models/*": "./@cds-models/*/index.js"
7
+ },
8
+ "main": "src/index.js",
9
+ "types": "src/index.d.ts",
10
+ "files": [
11
+ "cds-plugin.js",
12
+ "src/**/*.js",
13
+ "src/**/*.d.ts",
14
+ "srv/**/*.js",
15
+ "srv/**/*.d.ts",
16
+ "srv/**/*.cds",
17
+ "db/**/*.cds",
18
+ "@cds-models/"
19
+ ],
20
+ "engines": {
21
+ "node": ">=22.5"
22
+ },
23
+ "peerDependencies": {
24
+ "@sap/cds": ">=10"
25
+ },
26
+ "dependencies": {
27
+ "@blockfrost/blockfrost-js": "~6.0.0",
28
+ "@cap-js/hana": "^3",
29
+ "@cardano-ogmios/client": "^6.14.0",
30
+ "@harmoniclabs/buildooor": "0.2.9",
31
+ "@harmoniclabs/cardano-costmodels-ts": "~1.6.1",
32
+ "@harmoniclabs/cardano-ledger-ts": "^0.5.6",
33
+ "@harmoniclabs/cbor": "^2.0.1",
34
+ "@harmoniclabs/crypto": "^0.3.0",
35
+ "@harmoniclabs/uint8array-utils": "^1.0.4",
36
+ "@odatano/cap-auth": "^0.1.0",
37
+ "@sap/xssec": "^4",
38
+ "axios": "^1.18.0",
39
+ "bech32": "^2.0.0",
40
+ "blake2b": "^2.1.4"
41
+ },
42
+ "optionalDependencies": {
43
+ "pkcs11js": "^2.1.6"
44
+ },
45
+ "overrides": {
46
+ "axios": "^1.18.0",
47
+ "esbuild": "0.28.1",
48
+ "form-data": "^4.0.6",
49
+ "fast-uri": "^3.1.7",
50
+ "ws": "7.5.11",
51
+ "@sap/approuter": {
52
+ "body-parser": "^2.2.3"
53
+ }
54
+ },
55
+ "devDependencies": {
56
+ "@cap-js/cds-test": "^0.4.1",
57
+ "@cap-js/cds-typer": "^0.40.0",
58
+ "@cap-js/cds-types": "^0.18.0",
59
+ "@cap-js/postgres": "^3.1.1",
60
+ "@cap-js/sqlite": "^3",
61
+ "@sap/cds": "^10",
62
+ "@sap/cds-dk": "^10",
63
+ "@sap/eslint-plugin-cds": "^4.2.4",
64
+ "@types/blake2b": "^2.1.3",
65
+ "@types/node": "^22.19.7",
66
+ "@typescript-eslint/eslint-plugin": "^8.50.1",
67
+ "@typescript-eslint/parser": "^8.50.1",
68
+ "@vitest/coverage-v8": "^4.1.10",
69
+ "dotenv": "^16.3.1",
70
+ "eslint": "^9.39.2",
71
+ "nock": "^13.5.6",
72
+ "ts-node": "^10.9.2",
73
+ "tsx": "^4.21.0",
74
+ "typescript": "^5.9.3",
75
+ "vitest": "^4.1.10"
76
+ },
77
+ "cds": {
78
+ "typer": {
79
+ "ieee754compatible": true
80
+ },
81
+ "build": {
82
+ "tasks": [
83
+ {
84
+ "for": "node-cf",
85
+ "src": "srv",
86
+ "dest": "../gen/srv"
87
+ },
88
+ {
89
+ "for": "hana",
90
+ "src": "db",
91
+ "dest": "../gen/db"
92
+ }
93
+ ]
94
+ },
95
+ "requires": {
96
+ "db": {
97
+ "kind": "sqlite",
98
+ "credentials": {
99
+ "url": "db.sqlite"
100
+ },
101
+ "client": {
102
+ "timeout": 5000
103
+ }
104
+ },
105
+ "[production]": {
106
+ "db": {
107
+ "kind": "hana",
108
+ "pool": {
109
+ "acquireTimeoutMillis": 30000,
110
+ "min": 0,
111
+ "max": 10
112
+ }
113
+ },
114
+ "auth": "xsuaa"
115
+ }
116
+ }
117
+ },
118
+ "scripts": {
119
+ "clean": "node -e \"const fs=require('fs');fs.globSync('{srv,db,src}/**/*.{js,js.map,d.ts,d.ts.map}').filter(f=>!f.includes('node_modules')).forEach(f=>fs.unlinkSync(f));console.log('Clean complete')\"",
120
+ "clean:models": "node -e \"require('fs').rmSync('@cds-models',{recursive:true,force:true});console.log('Removed @cds-models')\"",
121
+ "build": "npm run cds:types && tsc",
122
+ "build:plugin": "npm run cds:types && tsc -p tsconfig.build.json",
123
+ "build:package": "npm run clean && npm run clean:models && npm run build:plugin",
124
+ "prepare": "npm run build:package",
125
+ "start": "cds-serve",
126
+ "cds:watch": "cds watch",
127
+ "cds:serve": "cds serve --with-mocks",
128
+ "cds:types": "cds-typer \"*\" --outputDirectory @cds-models",
129
+ "lint": "eslint .",
130
+ "typecheck": "tsc --noEmit",
131
+ "db:deploy": "cds deploy",
132
+ "pretest": "npm run clean && npm run cds:types && npm run db:deploy",
133
+ "test": "vitest run",
134
+ "pretest:coverage": "npm run clean && npm run cds:types && npm run db:deploy",
135
+ "test:coverage": "vitest run --coverage",
136
+ "pretest:ci": "npm run clean && npm run cds:types && npm run db:deploy",
137
+ "test:ci": "vitest run --exclude \"**/core-ogmios.test.ts\"",
138
+ "pretest:ci:coverage": "npm run clean && npm run cds:types && npm run db:deploy",
139
+ "test:ci:coverage": "vitest run --coverage --exclude \"**/core-ogmios.test.ts\"",
140
+ "pretest:integration": "npm run clean && npm run cds:types && npm run db:deploy",
141
+ "test:integration": "vitest run --project integration",
142
+ "test:integration:blockfrost": "vitest run test/integration/core.blockfrost.test.ts",
143
+ "test:integration:koios": "vitest run test/integration/core.koios.test.ts",
144
+ "test:integration:ogmios": "vitest run test/integration/core-ogmios.test.ts",
145
+ "test:integration:both": "npm run test:integration:blockfrost && npm run test:integration:koios",
146
+ "pretest:unit": "npm run cds:types",
147
+ "test:unit": "vitest run --project unit",
148
+ "watch-odatano": "cds watch --open odatano/index.html?sap-ui-xx-viewCache=false --livereload false",
149
+ "watch-wallet": "cds watch --open wallet/webapp/index.html",
150
+ "release:check": "node scripts/release-check.mjs"
151
+ },
152
+ "sapux": [
153
+ "app/odatano"
154
+ ],
155
+ "directories": {
156
+ "doc": "docs",
157
+ "test": "test"
158
+ },
159
+ "repository": {
160
+ "type": "git",
161
+ "url": "git+https://github.com/ODATANO/ODATANO.git"
162
+ },
163
+ "keywords": [
164
+ "CAP",
165
+ "CDS",
166
+ "plugin",
167
+ "Cardano",
168
+ "blockchain",
169
+ "OData",
170
+ "SAP"
171
+ ],
172
+ "author": "Maximilian Weber",
173
+ "license": "Apache-2.0",
174
+ "type": "commonjs",
175
+ "bugs": {
176
+ "url": "https://github.com/ODATANO/ODATANO/issues"
177
+ },
178
+ "homepage": "https://github.com/ODATANO/ODATANO#readme"
179
+ }
package/srv/server.js CHANGED
@@ -28,6 +28,7 @@ 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");
31
32
  const crawler_1 = require("./blockchain/crawler");
32
33
  const wallet_worker_1 = require("./blockchain/wallet-worker");
33
34
  const agent_grants_config_1 = require("./utils/agent-grants-config");
@@ -180,6 +181,14 @@ async function initializeFromConfig(config, protocolParams, hsmConfig) {
180
181
  return;
181
182
  }
182
183
  hsmConfigInstance = hsmConfig;
184
+ // The secondary indexes the model cannot declare (srv/utils/db-indexes.ts):
185
+ // idempotent, never fatal, before anything reads.
186
+ try {
187
+ await (0, db_indexes_1.ensureDbIndexes)();
188
+ }
189
+ catch (err) {
190
+ logger.warn('secondary indexes not ensured (non-fatal):', err);
191
+ }
183
192
  try {
184
193
  appContext = await initializeAppContext(config, protocolParams, hsmConfig);
185
194
  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. */
@@ -229,10 +237,17 @@ export interface AgentGrantUsage {
229
237
  jobsUsedToday: number;
230
238
  maxJobsPerDay: number | null;
231
239
  }
232
- /** The grant's admitted calls in `window`, grouped by service and action (one SUM per group). */
240
+ /**
241
+ * The grant's admitted calls in `window`, grouped by service and action (one
242
+ * SUM per group). `runner` is the request's transaction (the read); deferred
243
+ * counters (Postgres / HANA) are flushed first on `flushRunner`, the detached
244
+ * primary db service: written inside the request transaction they would hold
245
+ * the rows' locks until the GET commits and vanish with its rollback, while a
246
+ * separate autocommit is visible to the following SELECT under read committed.
247
+ */
233
248
  export declare function getGrantUsage(grant: AgentGrantRow, window: Extract<UsageWindow, {
234
249
  ok: true;
235
- }>, runner?: Runner): Promise<AgentGrantUsage>;
250
+ }>, runner?: Runner, flushRunner?: Runner): Promise<AgentGrantUsage>;
236
251
  export interface AgentGrantStatus {
237
252
  grantId: string;
238
253
  agentLabel: string | null;
@@ -299,16 +314,38 @@ export declare function consumeDailyBudget(br: BudgetRunner | Runner, grant: Age
299
314
  * the new day's counter: the unit was spent yesterday, yesterday keeps it.
300
315
  */
301
316
  export declare function refundDailyBudget(br: BudgetRunner | Runner, grant: AgentGrantRow, window: string): Promise<void>;
317
+ type UsageMode = 'sync' | 'deferred';
318
+ /** Test seam: force a mode (null = derive from cds.db.kind). */
319
+ export declare function __setGrantUsageModeForTests(mode: UsageMode | null): void;
320
+ /** Test seam: forget buffered deltas and the pending timer. */
321
+ export declare function __resetGrantUsageBufferForTests(): void;
322
+ /** How many keys wait for the next flush (monitoring, tests). */
323
+ export declare function pendingGrantUsageKeys(): number;
324
+ /**
325
+ * Writes the buffered deltas: `calls + n, refunded + m` per key, an INSERT when
326
+ * the row does not exist yet, one more UPDATE when a racing writer created it.
327
+ * A delta whose write fails goes back into the buffer for the next flush.
328
+ * `runner` defaults to the primary db service (tests pass their fake).
329
+ */
330
+ export declare function flushGrantUsage(runner?: Runner): Promise<{
331
+ flushed: number;
332
+ failed: number;
333
+ }>;
302
334
  /**
303
- * One admitted call: `calls + 1` on (grant, UTC day, service, action). A
304
- * conditional UPDATE first (the common path), an INSERT when the row does not
305
- * exist yet, one more UPDATE when a racing request inserted it first. Runs on
306
- * the hook's BudgetRunner and is AWAITED like every other write of the hook
307
- * (see touchLastUsed), but never fails the request: usage is accounting, not
308
- * admission. Returns the day the call was counted on (the refund names it).
335
+ * One admitted call: `calls + 1` on (grant, UTC day, service, action).
336
+ * Deferred mode (Postgres / HANA, detached runner): the delta goes into the
337
+ * buffer, nothing is written here. Sync mode: a conditional UPDATE first (the
338
+ * common path), an INSERT when the row does not exist yet, one more UPDATE
339
+ * when a racing request inserted it first, AWAITED like every other write of
340
+ * the hook (see touchLastUsed). Never fails the request: usage is accounting,
341
+ * not admission. Returns the day the call was counted on (the refund names it).
309
342
  */
310
343
  export declare function recordGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, now?: Date): Promise<string>;
311
- /** `refunded + 1` on the row the call was counted on: a refused request admitted nothing. */
344
+ /**
345
+ * `refunded + 1` on the row the call was counted on: a refused request admitted
346
+ * nothing. Deferred mode: into the buffer, on the same key the call went to,
347
+ * whether or not that call has been flushed yet (the flush adds deltas).
348
+ */
312
349
  export declare function refundGrantUsage(br: BudgetRunner | Runner, grant: AgentGrantRow, service: string, action: string, day: string): Promise<void>;
313
350
  export {};
314
351
  //# sourceMappingURL=agent-grants.d.ts.map
@@ -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;
@@ -52,6 +55,10 @@ exports.budgetRunnerFor = budgetRunnerFor;
52
55
  exports.enforceAgentGrant = enforceAgentGrant;
53
56
  exports.consumeDailyBudget = consumeDailyBudget;
54
57
  exports.refundDailyBudget = refundDailyBudget;
58
+ exports.__setGrantUsageModeForTests = __setGrantUsageModeForTests;
59
+ exports.__resetGrantUsageBufferForTests = __resetGrantUsageBufferForTests;
60
+ exports.pendingGrantUsageKeys = pendingGrantUsageKeys;
61
+ exports.flushGrantUsage = flushGrantUsage;
55
62
  exports.recordGrantUsage = recordGrantUsage;
56
63
  exports.refundGrantUsage = refundGrantUsage;
57
64
  const cds_1 = __importDefault(require("@sap/cds"));
@@ -145,10 +152,14 @@ function grantAdminLimiter() {
145
152
  grantAdminRateLimiter ??= new rate_limiter_1.RateLimiter({ windowMs: 60 * 60 * 1000, maxRequests: (0, agent_grants_config_1.loadGrantAdminRateLimit)() });
146
153
  return grantAdminRateLimiter;
147
154
  }
148
- /** 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). */
149
156
  function __resetGrantRateLimiterForTests() {
150
157
  grantAdminRateLimiter = null;
151
158
  lastUsedTouched.clear();
159
+ tokenCache.clear();
160
+ tokenHashOfGrant.clear();
161
+ tokenCacheMs = null;
162
+ tokenCacheOverride = null;
152
163
  }
153
164
  function dbRunner() {
154
165
  return cds_1.default.db;
@@ -189,21 +200,80 @@ function agentGrantOf(req) {
189
200
  const ctx = cds_1.default.context;
190
201
  return ctx?.http?.req?.agentGrant ?? null;
191
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
+ }
192
243
  /**
193
244
  * Authenticate a bearer token: prefix, hash lookup among ACTIVE grants (a
194
245
  * revoked grant is an unknown token, non-leaking), expiry. Detached from any
195
246
  * ambient transaction: the lane runs before the request transaction exists,
196
- * 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).
197
249
  */
198
250
  async function resolveAgentToken(token, runner = dbRunner()) {
199
251
  if (typeof token !== 'string' || !token.startsWith(exports.AGENT_TOKEN_PREFIX)) {
200
252
  return { ok: false, status: 401, message: 'invalid agent token' };
201
253
  }
202
- 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 }))));
203
269
  if (!grant)
204
270
  return { ok: false, status: 401, message: 'invalid agent token' };
205
271
  if (isExpired(grant))
206
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);
207
277
  return { ok: true, grant };
208
278
  }
209
279
  /**
@@ -329,21 +399,24 @@ async function revokeAgentGrantById(grantId, runner = dbRunner()) {
329
399
  .set({ isActive: false, revokedAt: new Date().toISOString() })
330
400
  .where({ ID: grantId, isActive: true }));
331
401
  const revoked = Number(affected) > 0;
402
+ invalidateTokenCache(grantId);
332
403
  if (revoked)
333
404
  logger.info(`agent grant ${grantId} revoked`);
334
405
  return revoked;
335
406
  }
336
407
  /**
337
408
  * Replace the grant's token; the old one is an unknown token from the next
338
- * request (the lane reads tokenHash per request, so nothing needs invalidating;
339
- * a request in flight with the old token completes). Budget, wallet, allow
340
- * 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.
341
413
  */
342
414
  async function rotateAgentGrantToken(grantId, runner = dbRunner()) {
343
415
  if (!grantId)
344
416
  return null;
345
417
  const token = exports.AGENT_TOKEN_PREFIX + node_crypto_1.default.randomBytes(TOKEN_BYTES).toString('hex');
346
418
  const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set({ tokenHash: hashAgentToken(token) }).where({ ID: grantId, isActive: true }));
419
+ invalidateTokenCache(grantId);
347
420
  if (Number(affected) === 0)
348
421
  return null;
349
422
  logger.info(`agent grant ${grantId} token rotated`);
@@ -401,6 +474,7 @@ async function updateAgentGrant(grantId, input, runner = dbRunner()) {
401
474
  return { ok: true, grantId, updated: [] };
402
475
  // Conditional on isActive: a concurrent revoke wins over the edit.
403
476
  const affected = await runner.run(UPDATE.entity(exports.GRANTS_ENTITY).set(patch).where({ ID: grantId, isActive: true }));
477
+ invalidateTokenCache(grantId);
404
478
  if (Number(affected) === 0)
405
479
  return { ok: false, status: 409, code: 'GRANT_REVOKED', message: 'Grant is revoked' };
406
480
  logger.info(`agent grant ${grantId} updated (${updated.join(', ')})`);
@@ -440,8 +514,17 @@ function resolveUsageWindow(since, until, now = new Date()) {
440
514
  const untilIso = new Date(toMs).toISOString();
441
515
  return { ok: true, since: sinceIso, until: untilIso, sinceDay: sinceIso.slice(0, 10), untilDay: untilIso.slice(0, 10) };
442
516
  }
443
- /** The grant's admitted calls in `window`, grouped by service and action (one SUM per group). */
444
- async function getGrantUsage(grant, window, runner = dbRunner()) {
517
+ /**
518
+ * The grant's admitted calls in `window`, grouped by service and action (one
519
+ * SUM per group). `runner` is the request's transaction (the read); deferred
520
+ * counters (Postgres / HANA) are flushed first on `flushRunner`, the detached
521
+ * primary db service: written inside the request transaction they would hold
522
+ * the rows' locks until the GET commits and vanish with its rollback, while a
523
+ * separate autocommit is visible to the following SELECT under read committed.
524
+ */
525
+ async function getGrantUsage(grant, window, runner = dbRunner(), flushRunner = dbRunner()) {
526
+ if (pendingGrantUsageKeys() > 0)
527
+ await flushGrantUsage(flushRunner);
445
528
  const rows = ((await runner.run(SELECT.from(exports.GRANT_USAGE_ENTITY)
446
529
  .columns('service', 'action', { func: 'sum', args: [{ ref: ['calls'] }], as: 'calls' }, { func: 'sum', args: [{ ref: ['refunded'] }], as: 'refunded' })
447
530
  .where({ grant_ID: grant.ID, day: { '>=': window.sinceDay } })
@@ -612,7 +695,7 @@ function registerAgentGrantHandlers(srv) {
612
695
  const grant = (await tx.run(SELECT.one.from(exports.GRANTS_ENTITY).where({ ID: data.grantId })));
613
696
  if (!grant)
614
697
  return req.reject(404, 'Grant not found', 'grantId');
615
- return getGrantUsage(grant, window, tx);
698
+ return getGrantUsage(grant, window, tx, dbRunner());
616
699
  });
617
700
  }
618
701
  // ---------------------------------------------------------------------------
@@ -760,18 +843,118 @@ async function refundDailyBudget(br, grant, window) {
760
843
  .set({ jobsUsedToday: { '-=': 1 } })
761
844
  .where({ ID: grant.ID, budgetWindow: window, jobsUsedToday: { '>': 0 } }));
762
845
  }
846
+ const USAGE_FLUSH_INTERVAL_MS = 1000;
847
+ const usageBuffer = new Map();
848
+ let usageFlushTimer = null;
849
+ let usageModeOverride = null;
850
+ let usageShutdownHooked = false;
851
+ /** Deferred on the databases whose writers do not block readers; sync everywhere else (SQLite, tests). */
852
+ function usageMode() {
853
+ if (usageModeOverride)
854
+ return usageModeOverride;
855
+ const kind = String(cds_1.default.db?.kind ?? '');
856
+ return kind === 'postgres' || kind === 'hana' ? 'deferred' : 'sync';
857
+ }
858
+ /** Test seam: force a mode (null = derive from cds.db.kind). */
859
+ function __setGrantUsageModeForTests(mode) {
860
+ usageModeOverride = mode;
861
+ }
862
+ /** Test seam: forget buffered deltas and the pending timer. */
863
+ function __resetGrantUsageBufferForTests() {
864
+ usageBuffer.clear();
865
+ if (usageFlushTimer) {
866
+ clearTimeout(usageFlushTimer);
867
+ usageFlushTimer = null;
868
+ }
869
+ }
870
+ /** How many keys wait for the next flush (monitoring, tests). */
871
+ function pendingGrantUsageKeys() {
872
+ return usageBuffer.size;
873
+ }
874
+ function bufferUsage(key, calls, refunded) {
875
+ const k = `${key.grant_ID}|${key.day}|${key.service}|${key.action}`;
876
+ const d = usageBuffer.get(k);
877
+ if (d) {
878
+ d.calls += calls;
879
+ d.refunded += refunded;
880
+ }
881
+ else
882
+ usageBuffer.set(k, { ...key, calls, refunded });
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) {
886
+ usageFlushTimer = setTimeout(() => {
887
+ usageFlushTimer = null;
888
+ void flushGrantUsage().catch((err) => logger.warn(`usage flush failed: ${String(err?.message ?? err)}`));
889
+ }, USAGE_FLUSH_INTERVAL_MS);
890
+ usageFlushTimer.unref?.();
891
+ }
892
+ if (!usageShutdownHooked) {
893
+ usageShutdownHooked = true;
894
+ cds_1.default.on('shutdown', () => flushGrantUsage().catch(() => undefined));
895
+ }
896
+ }
897
+ /**
898
+ * Writes the buffered deltas: `calls + n, refunded + m` per key, an INSERT when
899
+ * the row does not exist yet, one more UPDATE when a racing writer created it.
900
+ * A delta whose write fails goes back into the buffer for the next flush.
901
+ * `runner` defaults to the primary db service (tests pass their fake).
902
+ */
903
+ async function flushGrantUsage(runner = dbRunner()) {
904
+ if (usageBuffer.size === 0)
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
+ }
911
+ const batch = [...usageBuffer.values()];
912
+ usageBuffer.clear();
913
+ const br = { runner, detached: true };
914
+ let flushed = 0;
915
+ let failed = 0;
916
+ for (const d of batch) {
917
+ const key = { grant_ID: d.grant_ID, day: d.day, service: d.service, action: d.action };
918
+ const bump = () => runStmt(br, UPDATE.entity(exports.GRANT_USAGE_ENTITY).set({ calls: { '+=': d.calls }, refunded: { '+=': d.refunded } }).where(key));
919
+ try {
920
+ if (Number(await bump()) === 0) {
921
+ try {
922
+ await runStmt(br, INSERT.into(exports.GRANT_USAGE_ENTITY).entries({ ...key, calls: d.calls, refunded: d.refunded }));
923
+ }
924
+ catch (insertErr) {
925
+ // Lost the insert race: the row exists now. Anything else (the row is
926
+ // still missing) is the INSERT's own failure: keep the delta.
927
+ if (Number(await bump()) === 0)
928
+ throw insertErr;
929
+ }
930
+ }
931
+ flushed++;
932
+ }
933
+ catch (err) {
934
+ failed++;
935
+ bufferUsage(key, d.calls, d.refunded); // retried on the next flush
936
+ logger.warn(`usage flush for grant ${d.grant_ID} (${d.service}.${d.action}) failed, kept for retry: ${String(err?.message ?? err)}`);
937
+ }
938
+ }
939
+ return { flushed, failed };
940
+ }
763
941
  /**
764
- * One admitted call: `calls + 1` on (grant, UTC day, service, action). A
765
- * conditional UPDATE first (the common path), an INSERT when the row does not
766
- * exist yet, one more UPDATE when a racing request inserted it first. Runs on
767
- * the hook's BudgetRunner and is AWAITED like every other write of the hook
768
- * (see touchLastUsed), but never fails the request: usage is accounting, not
769
- * admission. Returns the day the call was counted on (the refund names it).
942
+ * One admitted call: `calls + 1` on (grant, UTC day, service, action).
943
+ * Deferred mode (Postgres / HANA, detached runner): the delta goes into the
944
+ * buffer, nothing is written here. Sync mode: a conditional UPDATE first (the
945
+ * common path), an INSERT when the row does not exist yet, one more UPDATE
946
+ * when a racing request inserted it first, AWAITED like every other write of
947
+ * the hook (see touchLastUsed). Never fails the request: usage is accounting,
948
+ * not admission. Returns the day the call was counted on (the refund names it).
770
949
  */
771
950
  async function recordGrantUsage(br, grant, service, action, now = new Date()) {
772
951
  const runner = 'runner' in br ? br : { runner: br, detached: true };
773
952
  const day = utcDay(now);
774
953
  const key = { grant_ID: grant.ID, day, service, action };
954
+ if (runner.detached && usageMode() === 'deferred') {
955
+ bufferUsage(key, 1, 0);
956
+ return day;
957
+ }
775
958
  const bump = () => runStmt(runner, UPDATE.entity(exports.GRANT_USAGE_ENTITY).set({ calls: { '+=': 1 } }).where(key));
776
959
  try {
777
960
  if (Number(await bump()) > 0)
@@ -788,12 +971,21 @@ async function recordGrantUsage(br, grant, service, action, now = new Date()) {
788
971
  }
789
972
  return day;
790
973
  }
791
- /** `refunded + 1` on the row the call was counted on: a refused request admitted nothing. */
974
+ /**
975
+ * `refunded + 1` on the row the call was counted on: a refused request admitted
976
+ * nothing. Deferred mode: into the buffer, on the same key the call went to,
977
+ * whether or not that call has been flushed yet (the flush adds deltas).
978
+ */
792
979
  async function refundGrantUsage(br, grant, service, action, day) {
793
980
  const runner = 'runner' in br ? br : { runner: br, detached: true };
981
+ const key = { grant_ID: grant.ID, day, service, action };
982
+ if (runner.detached && usageMode() === 'deferred') {
983
+ bufferUsage(key, 0, 1);
984
+ return;
985
+ }
794
986
  await runStmt(runner, UPDATE.entity(exports.GRANT_USAGE_ENTITY)
795
987
  .set({ refunded: { '+=': 1 } })
796
- .where({ grant_ID: grant.ID, day, service, action }));
988
+ .where(key));
797
989
  }
798
990
  /**
799
991
  * lastUsedAt, at most once a minute per grant. AWAITED, like the budget
@@ -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