@odatano/core 1.9.2 → 1.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "1.9.2",
3
+ "version": "1.9.3",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -120,10 +120,10 @@
120
120
  "typecheck": "tsc --noEmit",
121
121
  "db:deploy": "cds deploy",
122
122
  "pretest": "npm run cds:types && npm run db:deploy",
123
- "test": "jest --runInBand",
124
- "test:coverage": "jest --runInBand --coverage",
125
- "test:ci": "jest --runInBand --testPathIgnorePatterns=core-ogmios.test.ts",
126
- "test:ci:coverage": "jest --runInBand --coverage --testPathIgnorePatterns=core-ogmios.test.ts",
123
+ "test": "jest --runInBand --forceExit",
124
+ "test:coverage": "jest --runInBand --coverage --forceExit",
125
+ "test:ci": "jest --runInBand --testPathIgnorePatterns=core-ogmios.test.ts --forceExit",
126
+ "test:ci:coverage": "jest --runInBand --coverage --testPathIgnorePatterns=core-ogmios.test.ts --forceExit",
127
127
  "test:integration": "npm test -- --testPathPattern=integration",
128
128
  "test:integration:blockfrost": "npm test -- --testPathPattern=core.blockfrost.test.ts",
129
129
  "test:integration:koios": "npm test -- --testPathPattern=core.koios.test.ts",
@@ -24,6 +24,16 @@ export declare class KoiosBackend implements CardanoBackend {
24
24
  * epoch lookups, so we retry with increasing delays (500 → 1000 → 2000 ms).
25
25
  */
26
26
  private fetchWithRetryOnEmpty;
27
+ /**
28
+ * Koios runs several load-balanced grest instances and they are occasionally
29
+ * version-skewed: some return HTTP 400 with Postgres error 42804 ("structure
30
+ * of query does not match function result type", e.g. `out_sum_lovelace`
31
+ * word128 vs numeric on /epoch_info) while healthy instances serve the
32
+ * IDENTICAL request fine. The same request therefore flips 200/400 between
33
+ * calls. Retrying a few times lands on a healthy instance. Scoped strictly to
34
+ * the 42804 type-skew error so genuine 400s (bad params) still fail fast.
35
+ */
36
+ private getWithRetryOn42804;
27
37
  /**
28
38
  * Get Transaction Data for specified transaction hash
29
39
  * @param hash transaction hash (hex)
@@ -116,6 +116,35 @@ class KoiosBackend {
116
116
  }
117
117
  return [];
118
118
  }
119
+ /**
120
+ * Koios runs several load-balanced grest instances and they are occasionally
121
+ * version-skewed: some return HTTP 400 with Postgres error 42804 ("structure
122
+ * of query does not match function result type", e.g. `out_sum_lovelace`
123
+ * word128 vs numeric on /epoch_info) while healthy instances serve the
124
+ * IDENTICAL request fine. The same request therefore flips 200/400 between
125
+ * calls. Retrying a few times lands on a healthy instance. Scoped strictly to
126
+ * the 42804 type-skew error so genuine 400s (bad params) still fail fast.
127
+ */
128
+ async getWithRetryOn42804(url, config, label) {
129
+ const maxRetries = 8;
130
+ const baseDelayMs = 300;
131
+ for (let attempt = 0;; attempt++) {
132
+ try {
133
+ return await this.api.get(url, config);
134
+ }
135
+ catch (err) {
136
+ const e = err;
137
+ const isSkew = e?.response?.status === 400 &&
138
+ (e.response.data?.code === '42804' ||
139
+ /structure of query does not match function result type/i.test(e.response.data?.message ?? ''));
140
+ if (!isSkew || attempt >= maxRetries)
141
+ throw err;
142
+ const delay = baseDelayMs * (attempt + 1);
143
+ logger.warn(`${label}: Koios transient 42804 (grest version skew), retry ${attempt + 1}/${maxRetries} after ${delay}ms...`);
144
+ await new Promise(r => setTimeout(r, delay));
145
+ }
146
+ }
147
+ }
119
148
  /**
120
149
  * Get Transaction Data for specified transaction hash
121
150
  * @param hash transaction hash (hex)
@@ -174,7 +203,7 @@ class KoiosBackend {
174
203
  */
175
204
  async getEpoch(epochNumber) {
176
205
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
177
- const results = await this.fetchWithRetryOnEmpty(() => this.api.get('/epoch_info', { params: { _epoch_no: epochNumber } }), `getEpoch(${epochNumber})`);
206
+ const results = await this.fetchWithRetryOnEmpty(() => this.getWithRetryOn42804('/epoch_info', { params: { _epoch_no: epochNumber } }, `getEpoch(${epochNumber})`), `getEpoch(${epochNumber})`);
178
207
  if (!results || results.length === 0) {
179
208
  throw new errors_1.NotFoundError('Epoch', this.name);
180
209
  }
@@ -38,8 +38,36 @@ export declare class OgmiosBackend implements EvaluatingBackend {
38
38
  * Constructor
39
39
  */
40
40
  constructor(network: Network, timeoutMs: number, ogmiosUrl: string);
41
+ /**
42
+ * Force fresh (non-keep-alive) HTTP connections for the Ogmios `/health` probe.
43
+ *
44
+ * createInteractionContext() opens the WebSocket, but FIRST probes
45
+ * `GET http://<ogmios>/health` via the library's `cross-fetch` → node-fetch v2
46
+ * → Node-core `http`. Since Node 19, `http.globalAgent` defaults to
47
+ * keepAlive:true, so node-fetch reuses pooled sockets. Against Ogmios' Warp
48
+ * server on Node 22/24 a reused socket the server has already half-closed
49
+ * yields "Invalid response body … Premature close" the instant the body is
50
+ * read — deterministically (Node 20's older http client tolerated it; `curl`
51
+ * does too, so the /health response itself is well-formed and the node is
52
+ * healthy). The lib pins cross-fetch even in 7.0 and exposes no way to inject
53
+ * an agent into that internal fetch, so we neutralise keep-alive process-wide
54
+ * for `http://`. Blast radius is tiny: the only `http://` consumer is the local
55
+ * Ogmios probe — Blockfrost/Koios run over `https` with their own axios agents
56
+ * and are unaffected. Runs once, lazily, only when Ogmios is actually used.
57
+ */
58
+ private static keepAliveDisabled;
59
+ private static disableHttpKeepAlive;
41
60
  /** Validate Ogmios URL scheme and reject dangerous protocols */
42
61
  private static validateOgmiosUrl;
62
+ /**
63
+ * Bound an init step in time. A hung WebSocket connect/handshake (e.g. the
64
+ * node is alive but too busy catching up to answer) would otherwise block
65
+ * forever — there is no built-in connect timeout — hanging the whole
66
+ * app-context bootstrap (seen as a 6h CI job timeout). On timeout we reject
67
+ * with a message containing "timeout" so the orchestrator's transient-error
68
+ * retry picks it up instead of dying.
69
+ */
70
+ private withInitTimeout;
43
71
  /**
44
72
  * Initialize the Ogmios backend connection
45
73
  */
@@ -7,6 +7,7 @@ exports.OgmiosBackend = void 0;
7
7
  exports.resolveOgmiosTip = resolveOgmiosTip;
8
8
  exports.resolveOgmiosHeight = resolveOgmiosHeight;
9
9
  const cds_1 = __importDefault(require("@sap/cds"));
10
+ const node_http_1 = __importDefault(require("node:http"));
10
11
  const client_1 = require("@cardano-ogmios/client");
11
12
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
12
13
  const errors_1 = require("../../utils/errors");
@@ -115,6 +116,30 @@ class OgmiosBackend {
115
116
  this.timeoutMs = timeoutMs;
116
117
  this.ogmiosUrl = ogmiosUrl;
117
118
  }
119
+ /**
120
+ * Force fresh (non-keep-alive) HTTP connections for the Ogmios `/health` probe.
121
+ *
122
+ * createInteractionContext() opens the WebSocket, but FIRST probes
123
+ * `GET http://<ogmios>/health` via the library's `cross-fetch` → node-fetch v2
124
+ * → Node-core `http`. Since Node 19, `http.globalAgent` defaults to
125
+ * keepAlive:true, so node-fetch reuses pooled sockets. Against Ogmios' Warp
126
+ * server on Node 22/24 a reused socket the server has already half-closed
127
+ * yields "Invalid response body … Premature close" the instant the body is
128
+ * read — deterministically (Node 20's older http client tolerated it; `curl`
129
+ * does too, so the /health response itself is well-formed and the node is
130
+ * healthy). The lib pins cross-fetch even in 7.0 and exposes no way to inject
131
+ * an agent into that internal fetch, so we neutralise keep-alive process-wide
132
+ * for `http://`. Blast radius is tiny: the only `http://` consumer is the local
133
+ * Ogmios probe — Blockfrost/Koios run over `https` with their own axios agents
134
+ * and are unaffected. Runs once, lazily, only when Ogmios is actually used.
135
+ */
136
+ static keepAliveDisabled = false;
137
+ static disableHttpKeepAlive() {
138
+ if (OgmiosBackend.keepAliveDisabled)
139
+ return;
140
+ node_http_1.default.globalAgent = new node_http_1.default.Agent({ keepAlive: false });
141
+ OgmiosBackend.keepAliveDisabled = true;
142
+ }
118
143
  /** Validate Ogmios URL scheme and reject dangerous protocols */
119
144
  static validateOgmiosUrl(rawUrl) {
120
145
  const url = new URL(rawUrl);
@@ -133,10 +158,31 @@ class OgmiosBackend {
133
158
  throw new errors_1.BackendInitError('ogmios', new Error('Ogmios URL must not point to a link-local or metadata address'));
134
159
  }
135
160
  }
161
+ /**
162
+ * Bound an init step in time. A hung WebSocket connect/handshake (e.g. the
163
+ * node is alive but too busy catching up to answer) would otherwise block
164
+ * forever — there is no built-in connect timeout — hanging the whole
165
+ * app-context bootstrap (seen as a 6h CI job timeout). On timeout we reject
166
+ * with a message containing "timeout" so the orchestrator's transient-error
167
+ * retry picks it up instead of dying.
168
+ */
169
+ withInitTimeout(p, label) {
170
+ // Keep this SHORT: the orchestrator retries init a few times within the
171
+ // integration suite's 20s cds.test() hook, so each attempt must be brief.
172
+ // Still bounds a genuinely hung connect in production.
173
+ const ms = Math.min(this.timeoutMs, 4000);
174
+ let timer;
175
+ const timeout = new Promise((_, reject) => {
176
+ timer = setTimeout(() => reject(new Error(`Ogmios init timeout after ${ms}ms (${label})`)), ms);
177
+ timer.unref?.();
178
+ });
179
+ return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
180
+ }
136
181
  /**
137
182
  * Initialize the Ogmios backend connection
138
183
  */
139
184
  async init() {
185
+ OgmiosBackend.disableHttpKeepAlive();
140
186
  OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
141
187
  const url = new URL(this.ogmiosUrl);
142
188
  const connection = {
@@ -144,7 +190,7 @@ class OgmiosBackend {
144
190
  port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80),
145
191
  tls: url.protocol === 'wss:'
146
192
  };
147
- const context = await (0, client_1.createInteractionContext)(
193
+ const context = await this.withInitTimeout((0, client_1.createInteractionContext)(
148
194
  /* c8 ignore next */
149
195
  (err) => logger.error(`[OgmiosBackend] Interaction context error: ${err.message}`), () => {
150
196
  // Socket closed: clear the clients so the next request reconnects via
@@ -155,10 +201,10 @@ class OgmiosBackend {
155
201
  logger.warn('[OgmiosBackend] WebSocket closed — will reconnect on next request');
156
202
  this.stateQueryClient = null;
157
203
  this.txSubmissionClient = null;
158
- }, { connection });
204
+ }, { connection }), 'createInteractionContext');
159
205
  try {
160
- this.stateQueryClient = await (0, client_1.createLedgerStateQueryClient)(context);
161
- this.txSubmissionClient = await (0, client_1.createTransactionSubmissionClient)(context);
206
+ this.stateQueryClient = await this.withInitTimeout((0, client_1.createLedgerStateQueryClient)(context), 'ledgerStateQueryClient');
207
+ this.txSubmissionClient = await this.withInitTimeout((0, client_1.createTransactionSubmissionClient)(context), 'txSubmissionClient');
162
208
  }
163
209
  catch (err) {
164
210
  // don't leak the WebSocket when client creation fails mid-init
@@ -57,6 +57,22 @@ export declare class CardanoClient {
57
57
  * @returns {Promise<void>}
58
58
  */
59
59
  private ensureInitialized;
60
+ /**
61
+ * Transient (retryable) init failures: a backend momentarily unreachable at
62
+ * startup — e.g. Ogmios's /health response cut short while the node processes
63
+ * a freshly-arrived block ("Premature close"), or the socket still coming up
64
+ * (ECONNREFUSED). Config/validation errors are NOT transient.
65
+ */
66
+ private static isTransientInitError;
67
+ /**
68
+ * Init a backend, retrying brief transient failures. Deliberately SMALL: the
69
+ * integration suites bootstrap under a 20s cds.test() hook, so total retry
70
+ * time must stay well under it (≤3 attempts × 4s init-timeout + 1s backoff
71
+ * ≈ 14s worst case; in practice "Premature close" returns sub-second). With
72
+ * the node at tip these failures are momentary block-processing blips, so a
73
+ * couple of quick retries ride over them; a sustained outage still fails fast.
74
+ */
75
+ private initBackendWithRetry;
60
76
  /**
61
77
  * Initialize all backends from configuration.
62
78
  * Backends that fail to initialize are KEPT (previously removed permanently)
@@ -117,6 +117,43 @@ class CardanoClient {
117
117
  });
118
118
  await this.initPromise;
119
119
  }
120
+ /**
121
+ * Transient (retryable) init failures: a backend momentarily unreachable at
122
+ * startup — e.g. Ogmios's /health response cut short while the node processes
123
+ * a freshly-arrived block ("Premature close"), or the socket still coming up
124
+ * (ECONNREFUSED). Config/validation errors are NOT transient.
125
+ */
126
+ static isTransientInitError(err) {
127
+ const e = err;
128
+ const code = e?.code ?? e?.cause?.code ?? '';
129
+ const msg = `${e?.message ?? ''} ${e?.cause?.message ?? ''}`.toLowerCase();
130
+ if (['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EPIPE', 'EAI_AGAIN', 'ENOTFOUND', 'UND_ERR_SOCKET'].includes(code))
131
+ return true;
132
+ return /premature close|socket hang up|econnreset|econnrefused|etimedout|timeout|fetch failed|terminated|other side closed/.test(msg);
133
+ }
134
+ /**
135
+ * Init a backend, retrying brief transient failures. Deliberately SMALL: the
136
+ * integration suites bootstrap under a 20s cds.test() hook, so total retry
137
+ * time must stay well under it (≤3 attempts × 4s init-timeout + 1s backoff
138
+ * ≈ 14s worst case; in practice "Premature close" returns sub-second). With
139
+ * the node at tip these failures are momentary block-processing blips, so a
140
+ * couple of quick retries ride over them; a sustained outage still fails fast.
141
+ */
142
+ async initBackendWithRetry(backend) {
143
+ const maxAttempts = 3;
144
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
145
+ try {
146
+ await backend.init();
147
+ return;
148
+ }
149
+ catch (err) {
150
+ if (attempt >= maxAttempts || !CardanoClient.isTransientInitError(err))
151
+ throw err;
152
+ logger.warn(`Init of ${backend.name} failed (attempt ${attempt}/${maxAttempts}) — transient, retrying in 1s`, err);
153
+ await new Promise(r => setTimeout(r, 1000));
154
+ }
155
+ }
156
+ }
120
157
  /**
121
158
  * Initialize all backends from configuration.
122
159
  * Backends that fail to initialize are KEPT (previously removed permanently)
@@ -131,7 +168,7 @@ class CardanoClient {
131
168
  if (this.liveBackend) {
132
169
  try {
133
170
  logger.debug(`Initializing live backend: ${this.liveBackend.name}`);
134
- await this.liveBackend.init();
171
+ await this.initBackendWithRetry(this.liveBackend);
135
172
  this.uninitializedBackends.delete(this.liveBackend);
136
173
  logger.debug(`Live backend initialized: ${this.liveBackend.name}`);
137
174
  }
@@ -145,7 +182,7 @@ class CardanoClient {
145
182
  for (const backend of this.historicalBackends) {
146
183
  try {
147
184
  logger.debug(`Initializing historical backend: ${backend.name}`);
148
- await backend.init();
185
+ await this.initBackendWithRetry(backend);
149
186
  this.uninitializedBackends.delete(backend);
150
187
  logger.debug(`Historical backend initialized: ${backend.name}`);
151
188
  }