@odatano/core 2.0.0-rc.15 → 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 +1 -0
- package/package.json +1 -1
- package/srv/server.js +9 -0
- package/srv/utils/agent-grants-config.d.ts +11 -0
- package/srv/utils/agent-grants-config.js +24 -1
- package/srv/utils/agent-grants.d.ts +13 -5
- package/srv/utils/agent-grants.js +84 -7
- package/srv/utils/db-indexes.d.ts +30 -0
- package/srv/utils/db-indexes.js +104 -0
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
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
|
|
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
|
|
157
|
-
* a request in flight with the old
|
|
158
|
-
* list and expiry survive. Null when
|
|
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
|
|
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
|
|
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
|
|
343
|
-
* a request in flight with the old
|
|
344
|
-
* list and expiry survive. Null when
|
|
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
|
-
|
|
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
|