risicare 0.7.0 → 0.8.0
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 +282 -63
- package/dist/frameworks/instructor.cjs +790 -5
- package/dist/frameworks/instructor.cjs.map +1 -1
- package/dist/frameworks/instructor.js +780 -5
- package/dist/frameworks/instructor.js.map +1 -1
- package/dist/frameworks/langchain.cjs +790 -5
- package/dist/frameworks/langchain.cjs.map +1 -1
- package/dist/frameworks/langchain.d.cts +3 -2
- package/dist/frameworks/langchain.d.ts +3 -2
- package/dist/frameworks/langchain.js +780 -5
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/frameworks/langgraph.cjs +790 -5
- package/dist/frameworks/langgraph.cjs.map +1 -1
- package/dist/frameworks/langgraph.js +780 -5
- package/dist/frameworks/langgraph.js.map +1 -1
- package/dist/frameworks/llamaindex.cjs +801 -5
- package/dist/frameworks/llamaindex.cjs.map +1 -1
- package/dist/frameworks/llamaindex.d.cts +3 -2
- package/dist/frameworks/llamaindex.d.ts +3 -2
- package/dist/frameworks/llamaindex.js +791 -5
- package/dist/frameworks/llamaindex.js.map +1 -1
- package/dist/index.cjs +1113 -176
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +234 -42
- package/dist/index.d.ts +234 -42
- package/dist/index.js +1113 -176
- package/dist/index.js.map +1 -1
- package/dist/providers/anthropic/index.cjs +1601 -36
- package/dist/providers/anthropic/index.cjs.map +1 -1
- package/dist/providers/anthropic/index.d.cts +3 -1
- package/dist/providers/anthropic/index.d.ts +3 -1
- package/dist/providers/anthropic/index.js +1591 -36
- package/dist/providers/anthropic/index.js.map +1 -1
- package/dist/providers/bedrock/index.cjs +850 -32
- package/dist/providers/bedrock/index.cjs.map +1 -1
- package/dist/providers/bedrock/index.js +840 -32
- package/dist/providers/bedrock/index.js.map +1 -1
- package/dist/providers/cerebras/index.cjs +1534 -30
- package/dist/providers/cerebras/index.cjs.map +1 -1
- package/dist/providers/cerebras/index.js +1524 -30
- package/dist/providers/cerebras/index.js.map +1 -1
- package/dist/providers/cohere/index.cjs +1557 -102
- package/dist/providers/cohere/index.cjs.map +1 -1
- package/dist/providers/cohere/index.js +1547 -102
- package/dist/providers/cohere/index.js.map +1 -1
- package/dist/providers/google/index.cjs +1562 -60
- package/dist/providers/google/index.cjs.map +1 -1
- package/dist/providers/google/index.js +1552 -60
- package/dist/providers/google/index.js.map +1 -1
- package/dist/providers/groq/index.cjs +1534 -30
- package/dist/providers/groq/index.cjs.map +1 -1
- package/dist/providers/groq/index.js +1524 -30
- package/dist/providers/groq/index.js.map +1 -1
- package/dist/providers/huggingface/index.cjs +1622 -25
- package/dist/providers/huggingface/index.cjs.map +1 -1
- package/dist/providers/huggingface/index.d.cts +0 -9
- package/dist/providers/huggingface/index.d.ts +0 -9
- package/dist/providers/huggingface/index.js +1612 -25
- package/dist/providers/huggingface/index.js.map +1 -1
- package/dist/providers/mistral/index.cjs +1535 -54
- package/dist/providers/mistral/index.cjs.map +1 -1
- package/dist/providers/mistral/index.js +1525 -54
- package/dist/providers/mistral/index.js.map +1 -1
- package/dist/providers/ollama/index.cjs +1559 -93
- package/dist/providers/ollama/index.cjs.map +1 -1
- package/dist/providers/ollama/index.js +1549 -93
- package/dist/providers/ollama/index.js.map +1 -1
- package/dist/providers/openai/index.cjs +1598 -61
- package/dist/providers/openai/index.cjs.map +1 -1
- package/dist/providers/openai/index.d.cts +6 -1
- package/dist/providers/openai/index.d.ts +6 -1
- package/dist/providers/openai/index.js +1588 -61
- package/dist/providers/openai/index.js.map +1 -1
- package/dist/providers/together/index.cjs +1534 -30
- package/dist/providers/together/index.cjs.map +1 -1
- package/dist/providers/together/index.js +1524 -30
- package/dist/providers/together/index.js.map +1 -1
- package/dist/providers/vercel-ai/index.cjs +1288 -17
- package/dist/providers/vercel-ai/index.cjs.map +1 -1
- package/dist/providers/vercel-ai/index.d.cts +0 -6
- package/dist/providers/vercel-ai/index.d.ts +0 -6
- package/dist/providers/vercel-ai/index.js +1278 -17
- package/dist/providers/vercel-ai/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -25,8 +25,80 @@ function debug(msg) {
|
|
|
25
25
|
`);
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
+
function warn(msg) {
|
|
29
|
+
process.stderr.write(`[risicare] WARNING: ${msg}
|
|
30
|
+
`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/utils/text.ts
|
|
34
|
+
function cutCodePoints(text, max) {
|
|
35
|
+
if (text.length <= max) return text;
|
|
36
|
+
let units = 0;
|
|
37
|
+
for (let points = 0; points < max && units < text.length; points++) {
|
|
38
|
+
units += text.codePointAt(units) > 65535 ? 2 : 1;
|
|
39
|
+
}
|
|
40
|
+
return text.slice(0, units);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// src/utils/scrub.ts
|
|
44
|
+
var KEY_MARKER = "[REDACTED-KEY]";
|
|
45
|
+
var CONTROL = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]", "g");
|
|
46
|
+
function escapeRegExp(text) {
|
|
47
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
48
|
+
}
|
|
49
|
+
function percentDecode(text) {
|
|
50
|
+
try {
|
|
51
|
+
return decodeURIComponent(text);
|
|
52
|
+
} catch {
|
|
53
|
+
return text.replace(/%([0-9A-Fa-f]{2})/g, (_m, hex) => String.fromCharCode(parseInt(hex, 16)));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function keyPattern(keys) {
|
|
57
|
+
const values = /* @__PURE__ */ new Set();
|
|
58
|
+
for (const k of [...keys, process.env.RISICARE_API_KEY]) if (k) values.add(k);
|
|
59
|
+
if (values.size === 0) return null;
|
|
60
|
+
const ordered = [...values].sort((a, b) => b.length - a.length);
|
|
61
|
+
return new RegExp(ordered.map(escapeRegExp).join("|"), "gi");
|
|
62
|
+
}
|
|
63
|
+
function scrubText(text, keys, limit = 200) {
|
|
64
|
+
let out;
|
|
65
|
+
try {
|
|
66
|
+
out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);
|
|
67
|
+
} catch {
|
|
68
|
+
out = typeof text;
|
|
69
|
+
}
|
|
70
|
+
const pattern = keyPattern(keys);
|
|
71
|
+
if (pattern !== null) {
|
|
72
|
+
if (out.includes("%")) {
|
|
73
|
+
const decoded = percentDecode(out);
|
|
74
|
+
pattern.lastIndex = 0;
|
|
75
|
+
if (decoded !== out && pattern.test(decoded)) out = decoded;
|
|
76
|
+
}
|
|
77
|
+
pattern.lastIndex = 0;
|
|
78
|
+
out = out.replace(pattern, KEY_MARKER);
|
|
79
|
+
}
|
|
80
|
+
return cutCodePoints(out.replace(CONTROL, " "), limit);
|
|
81
|
+
}
|
|
82
|
+
function safeUrl(url) {
|
|
83
|
+
try {
|
|
84
|
+
const u = new URL(url);
|
|
85
|
+
const path = u.pathname === "/" && !/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*\//i.test(url) ? "" : u.pathname;
|
|
86
|
+
return `${u.protocol}//${u.host}${path}`;
|
|
87
|
+
} catch {
|
|
88
|
+
return url.split("?")[0].split("#")[0].replace(/\/\/[^/@]*@/, "//");
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function hasCredentials(url) {
|
|
92
|
+
try {
|
|
93
|
+
const u = new URL(url);
|
|
94
|
+
return u.username !== "" || u.password !== "";
|
|
95
|
+
} catch {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
28
99
|
|
|
29
100
|
// src/exporters/batch.ts
|
|
101
|
+
var MAX_TIMEOUT_MS = 2 ** 31 - 1;
|
|
30
102
|
var MAX_BATCH_BYTES = 8 * 1024 * 1024;
|
|
31
103
|
var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
|
|
32
104
|
|
|
@@ -103,13 +175,61 @@ var NOOP_SPAN = Object.freeze({
|
|
|
103
175
|
}
|
|
104
176
|
});
|
|
105
177
|
|
|
178
|
+
// src/runtime/config.ts
|
|
179
|
+
function resolveFixRuntimeConfig(config) {
|
|
180
|
+
return {
|
|
181
|
+
apiEndpoint: config.apiEndpoint,
|
|
182
|
+
apiKey: config.apiKey,
|
|
183
|
+
enabled: config.enabled ?? true,
|
|
184
|
+
cacheEnabled: config.cacheEnabled ?? true,
|
|
185
|
+
cacheTtlMs: config.cacheTtlMs ?? 3e5,
|
|
186
|
+
cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
|
|
187
|
+
autoRefresh: config.autoRefresh ?? true,
|
|
188
|
+
refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
|
|
189
|
+
dryRun: config.dryRun ?? false,
|
|
190
|
+
abTestingEnabled: config.abTestingEnabled ?? true,
|
|
191
|
+
timeoutMs: config.timeoutMs ?? 1e3,
|
|
192
|
+
debug: config.debug ?? false
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
function activeFixFromApiResponse(item) {
|
|
196
|
+
return {
|
|
197
|
+
fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
|
|
198
|
+
deploymentId: item.deployment_id ?? item.deploymentId ?? "",
|
|
199
|
+
errorCode: item.error_code ?? item.errorCode ?? "",
|
|
200
|
+
fixType: item.fix_type ?? item.fixType ?? "prompt",
|
|
201
|
+
config: item.config ?? {},
|
|
202
|
+
trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
|
|
203
|
+
version: item.version ?? 1
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
106
207
|
// src/runtime/taxonomy.generated.ts
|
|
208
|
+
var CORE_RULES = [
|
|
209
|
+
{ re: new RegExp("json", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" },
|
|
210
|
+
{ re: new RegExp("encoding", "u"), code: "PERCEPTION.INPUT.ENCODING" },
|
|
211
|
+
{ re: new RegExp("injection", "u"), code: "PERCEPTION.INPUT.INJECTION" },
|
|
212
|
+
{ re: new RegExp("malformed", "u"), code: "PERCEPTION.INPUT.MALFORMED" },
|
|
213
|
+
{ re: new RegExp("hallucin", "u"), code: "REASONING.HALLUCINATION.FACTUAL" },
|
|
214
|
+
{ re: new RegExp("contradict", "u"), code: "REASONING.LOGIC.CONTRADICTION" },
|
|
215
|
+
{ re: new RegExp("timeout", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
|
|
216
|
+
{ re: new RegExp("rate[^\\n]?limit", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
|
|
217
|
+
{ re: new RegExp("permission", "u"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
|
|
218
|
+
{ re: new RegExp("context[^\\n]+overflow", "u"), code: "MEMORY.CONTEXT_WINDOW.EXCEEDED" },
|
|
219
|
+
{ re: new RegExp("state[^\\n]+corrupt", "u"), code: "MEMORY.STATE.CORRUPTED" },
|
|
220
|
+
{ re: new RegExp("pii", "u"), code: "OUTPUT.SAFETY.PII_LEAK" },
|
|
221
|
+
{ re: new RegExp("deadlock", "u"), code: "COORDINATION.WORKFLOW.DEADLOCK" },
|
|
222
|
+
{ re: new RegExp("undeliverable", "u"), code: "COMMUNICATION.DELIVERY.UNDELIVERABLE" },
|
|
223
|
+
{ re: new RegExp("crash", "u"), code: "ORCHESTRATION.LIFECYCLE.CRASHED" },
|
|
224
|
+
{ re: new RegExp("quorum", "u"), code: "CONSENSUS.AGREEMENT.QUORUM_FAILED" },
|
|
225
|
+
{ re: new RegExp("quota[^\\n]+exceed", "u"), code: "RESOURCES.QUOTA.EXCEEDED" }
|
|
226
|
+
];
|
|
107
227
|
var SUPPLEMENTAL_RULES = [
|
|
108
|
-
{ re: new RegExp("timeout|timedout|aborted", "
|
|
109
|
-
{ re: new RegExp("rate
|
|
110
|
-
{ re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "
|
|
111
|
-
{ re: new RegExp("\\
|
|
112
|
-
{ re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "
|
|
228
|
+
{ re: new RegExp("timeout|timedout|aborted", "u"), code: "TOOL.EXECUTION.TIMEOUT" },
|
|
229
|
+
{ re: new RegExp("rate[^\\n]?limit|(?<![\\p{L}\\p{N}_])429(?![\\p{L}\\p{N}_])|too many requests", "u"), code: "TOOL.EXECUTION.RATE_LIMITED" },
|
|
230
|
+
{ re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "u"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
|
|
231
|
+
{ re: new RegExp("(?<![\\p{L}\\p{N}_])auth|unauthorized|forbidden|permission|(?<![\\p{L}\\p{N}_])401(?![\\p{L}\\p{N}_])|(?<![\\p{L}\\p{N}_])403(?![\\p{L}\\p{N}_])", "u"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
|
|
232
|
+
{ re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" }
|
|
113
233
|
];
|
|
114
234
|
|
|
115
235
|
// src/context/storage.ts
|
|
@@ -120,10 +240,695 @@ function getContext() {
|
|
|
120
240
|
return storage().getStore() ?? {};
|
|
121
241
|
}
|
|
122
242
|
|
|
243
|
+
// src/version.ts
|
|
244
|
+
var SDK_VERSION = "0.8.0";
|
|
245
|
+
|
|
246
|
+
// src/exporters/http.ts
|
|
247
|
+
var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
|
|
248
|
+
var RETRY_AFTER_CEILING_MS = 1e4;
|
|
249
|
+
var REFUSAL_BACKOFF_BASE_MS = 1e3;
|
|
250
|
+
var REFUSAL_NO_HINT = -1;
|
|
251
|
+
var MISROUTE_WARN_WINDOW_MS = 3e5;
|
|
252
|
+
var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
|
|
253
|
+
var FAILURE_WARN_WINDOW_MS = 3e5;
|
|
254
|
+
var HttpExporter = class {
|
|
255
|
+
name = "http";
|
|
256
|
+
_endpoint;
|
|
257
|
+
_apiKey;
|
|
258
|
+
_projectId;
|
|
259
|
+
_environment;
|
|
260
|
+
_timeoutMs;
|
|
261
|
+
_maxRetries;
|
|
262
|
+
_compress;
|
|
263
|
+
// Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
|
|
264
|
+
// a "30-second prod restart" scenario: with default 1s batch flush a
|
|
265
|
+
// 5-failure threshold opens the circuit ~5s into an outage and the 60s
|
|
266
|
+
// cooldown gives the gateway time to come back before the half-open
|
|
267
|
+
// probe fires. Lower numbers (was 3@30s) tripped on transient blips.
|
|
268
|
+
_consecutiveFailures = 0;
|
|
269
|
+
_lastMisrouteWarnAt = -Infinity;
|
|
270
|
+
_lastFailureWarnAt = -Infinity;
|
|
271
|
+
/**
|
|
272
|
+
* The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
|
|
273
|
+
* 'unknown'). `null` after a success. A new kind in the same outage writes one more
|
|
274
|
+
* WARNING, also inside the window.
|
|
275
|
+
*/
|
|
276
|
+
_failureKind = null;
|
|
277
|
+
/** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
|
|
278
|
+
_safeEndpoint;
|
|
279
|
+
/** The endpoint holds userinfo. `fetch` refuses such a URL. */
|
|
280
|
+
_endpointHasCredentials;
|
|
281
|
+
/** The calls in progress, by their batch, so that `abort(spans)` stops the right one. */
|
|
282
|
+
_calls = /* @__PURE__ */ new Map();
|
|
283
|
+
/** The ack of each finished call, by its batch. Read once by `takeAck(spans)`. */
|
|
284
|
+
_acks = /* @__PURE__ */ new WeakMap();
|
|
285
|
+
/** The spans of each finished call that could not be serialized, by its batch. */
|
|
286
|
+
_unserializable = /* @__PURE__ */ new WeakMap();
|
|
287
|
+
_circuitOpenUntil = 0;
|
|
288
|
+
_circuitBreakerThreshold = 5;
|
|
289
|
+
_circuitBreakerCooldownMs = 6e4;
|
|
290
|
+
constructor(options) {
|
|
291
|
+
this._endpoint = options.endpoint.replace(/\/+$/, "");
|
|
292
|
+
this._apiKey = options.apiKey;
|
|
293
|
+
this._projectId = options.projectId;
|
|
294
|
+
this._environment = options.environment;
|
|
295
|
+
this._timeoutMs = options.timeoutMs ?? 5e3;
|
|
296
|
+
this._maxRetries = options.maxRetries ?? 3;
|
|
297
|
+
this._compress = options.compress ?? false;
|
|
298
|
+
this._safeEndpoint = safeUrl(this._endpoint);
|
|
299
|
+
this._endpointHasCredentials = hasCredentials(this._endpoint);
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Network or error text for a log line: the endpoint as `safeUrl` gives it, and no
|
|
303
|
+
* form of the API key (`utils/scrub.ts`).
|
|
304
|
+
*/
|
|
305
|
+
_scrub(text, limit = 200) {
|
|
306
|
+
let out;
|
|
307
|
+
try {
|
|
308
|
+
out = text instanceof Error ? `${text.name}: ${text.message}` : String(text);
|
|
309
|
+
} catch {
|
|
310
|
+
out = typeof text;
|
|
311
|
+
}
|
|
312
|
+
if (this._safeEndpoint !== this._endpoint) out = out.split(this._endpoint).join(this._safeEndpoint);
|
|
313
|
+
return scrubText(out, [this._apiKey], limit);
|
|
314
|
+
}
|
|
315
|
+
/** Hide the key from `util.inspect` and `console.log` of the exporter. */
|
|
316
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
317
|
+
return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
|
|
318
|
+
}
|
|
319
|
+
/** The most requests that one `export()` call sends (`maxRetries`). */
|
|
320
|
+
get attemptsPerExport() {
|
|
321
|
+
return this._maxRetries;
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Returns the counts of the ack that the `export()` call for `spans` received, and clears
|
|
325
|
+
* them. The answer is kept per batch, not on the instance: two processors that share this
|
|
326
|
+
* exporter cannot read each other's ack across an `await`.
|
|
327
|
+
*/
|
|
328
|
+
takeAck(spans) {
|
|
329
|
+
const ack = this._acks.get(spans) ?? null;
|
|
330
|
+
this._acks.delete(spans);
|
|
331
|
+
return ack;
|
|
332
|
+
}
|
|
333
|
+
/** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
|
|
334
|
+
takeUnserializable(spans) {
|
|
335
|
+
const bad = this._unserializable.get(spans) ?? [];
|
|
336
|
+
this._unserializable.delete(spans);
|
|
337
|
+
return bad;
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
|
|
341
|
+
* request, its retries and its backoff sleep. The batch processor calls it when
|
|
342
|
+
* `shutdown()` abandons the batch, so that the call does not keep the process alive. The
|
|
343
|
+
* cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
|
|
344
|
+
* logs no WARNING.
|
|
345
|
+
*/
|
|
346
|
+
abort(spans) {
|
|
347
|
+
if (spans !== void 0) this._calls.get(spans)?.cancel.abort();
|
|
348
|
+
else for (const call of this._calls.values()) call.cancel.abort();
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Send one batch. The limits are the request timeout and `maxRetries`.
|
|
352
|
+
*
|
|
353
|
+
* ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
|
|
354
|
+
* cuts a request that is already sent. A short flush budget that cut the request made a
|
|
355
|
+
* healthy, slow server look like a failure: the span used a retry, the breaker moved, and
|
|
356
|
+
* the server stored the same spans again. Only `abort()` stops the call, and only
|
|
357
|
+
* `shutdown()` calls it.
|
|
358
|
+
*/
|
|
359
|
+
async export(spans) {
|
|
360
|
+
if (spans.length === 0) return "success" /* SUCCESS */;
|
|
361
|
+
const call = {
|
|
362
|
+
cancel: new AbortController(),
|
|
363
|
+
refusalAfterMs: null,
|
|
364
|
+
misroute: null,
|
|
365
|
+
noRetry: false,
|
|
366
|
+
status: null,
|
|
367
|
+
error: null
|
|
368
|
+
};
|
|
369
|
+
this._calls.set(spans, call);
|
|
370
|
+
try {
|
|
371
|
+
return await this._export(spans, call);
|
|
372
|
+
} finally {
|
|
373
|
+
this._calls.delete(spans);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
async _export(spans, call) {
|
|
377
|
+
const cancelled = call.cancel.signal;
|
|
378
|
+
const parts = [];
|
|
379
|
+
const bad = [];
|
|
380
|
+
let errorClass = "";
|
|
381
|
+
for (const span of spans) {
|
|
382
|
+
try {
|
|
383
|
+
parts.push(JSON.stringify(span.toPayload()));
|
|
384
|
+
} catch (e) {
|
|
385
|
+
bad.push(span);
|
|
386
|
+
errorClass ||= e instanceof Error ? e.name : typeof e;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
if (bad.length > 0) {
|
|
390
|
+
this._unserializable.set(spans, bad);
|
|
391
|
+
warn(
|
|
392
|
+
`Risicare: ${bad.length} of ${spans.length} span(s) in this batch could not be serialized (${errorClass}), for example an attribute with a BigInt or a circular reference. They are not sent and are counted as dropped (reason=unacknowledged).`
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
if (parts.length === 0) return "success" /* SUCCESS */;
|
|
396
|
+
const payload = `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
|
|
397
|
+
const now = Date.now();
|
|
398
|
+
let isHalfOpen = false;
|
|
399
|
+
if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
|
|
400
|
+
if (now < this._circuitOpenUntil) {
|
|
401
|
+
return "failure" /* FAILURE */;
|
|
402
|
+
}
|
|
403
|
+
isHalfOpen = true;
|
|
404
|
+
}
|
|
405
|
+
const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
|
|
406
|
+
let attempts = 0;
|
|
407
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
408
|
+
call.refusalAfterMs = null;
|
|
409
|
+
call.misroute = null;
|
|
410
|
+
call.noRetry = false;
|
|
411
|
+
call.status = null;
|
|
412
|
+
call.error = null;
|
|
413
|
+
attempts++;
|
|
414
|
+
const result = await this._sendRequest(payload, parts.length, call, spans);
|
|
415
|
+
if (cancelled.aborted) {
|
|
416
|
+
this._acks.delete(spans);
|
|
417
|
+
return "failure" /* FAILURE */;
|
|
418
|
+
}
|
|
419
|
+
if (result === "success" /* SUCCESS */) {
|
|
420
|
+
this._consecutiveFailures = 0;
|
|
421
|
+
this._failureKind = null;
|
|
422
|
+
return result;
|
|
423
|
+
}
|
|
424
|
+
if (call.misroute !== null || call.noRetry) break;
|
|
425
|
+
if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;
|
|
426
|
+
if (attempt < maxAttempts - 1) {
|
|
427
|
+
const refusal = call.refusalAfterMs;
|
|
428
|
+
const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
|
|
429
|
+
await sleep(delay, cancelled);
|
|
430
|
+
if (cancelled.aborted) return "failure" /* FAILURE */;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (call.refusalAfterMs !== null) {
|
|
434
|
+
warn(
|
|
435
|
+
`Risicare: the ingest endpoint refused this batch for capacity (HTTP 429/503) after ${attempts} attempt(s). This is a healthy server shedding load, not an outage. This export of the batch failed; the circuit breaker does not count it. Reduce batch size or export rate if it persists.`
|
|
436
|
+
);
|
|
437
|
+
return "failure" /* FAILURE */;
|
|
438
|
+
}
|
|
439
|
+
const misroute = call.misroute;
|
|
440
|
+
if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
|
|
441
|
+
this._lastMisrouteWarnAt = Date.now();
|
|
442
|
+
warn(
|
|
443
|
+
`Risicare: spans are NOT reaching ${this._safeEndpoint}. It answered POST /v1/spans with ${misroute}. That is not the Risicare ingest gateway, so the endpoint is probably wrong (for example the dashboard URL instead of the ingest gateway URL). The SDK does not follow redirects, and this batch is counted as NOT delivered. Set endpoint or RISICARE_ENDPOINT to the ingest gateway URL.`
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
this._consecutiveFailures++;
|
|
447
|
+
if (misroute === null && !call.noRetry) {
|
|
448
|
+
const status = call.status;
|
|
449
|
+
const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
|
|
450
|
+
let write = false;
|
|
451
|
+
if (this._consecutiveFailures === 1 || this._failureKind === null) {
|
|
452
|
+
if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
|
|
453
|
+
this._lastFailureWarnAt = Date.now();
|
|
454
|
+
write = true;
|
|
455
|
+
}
|
|
456
|
+
this._failureKind = kind;
|
|
457
|
+
} else if (kind !== this._failureKind) {
|
|
458
|
+
this._failureKind = kind;
|
|
459
|
+
write = true;
|
|
460
|
+
}
|
|
461
|
+
if (write) this._warnOutage(kind, status, call.error);
|
|
462
|
+
}
|
|
463
|
+
if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
|
|
464
|
+
this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
|
|
465
|
+
warn(
|
|
466
|
+
`HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
return "failure" /* FAILURE */;
|
|
470
|
+
}
|
|
471
|
+
/** The outage WARNING for one kind of failure. */
|
|
472
|
+
_warnOutage(kind, status, error) {
|
|
473
|
+
const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
|
|
474
|
+
const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
|
|
475
|
+
if (kind === "auth") {
|
|
476
|
+
warn(
|
|
477
|
+
`${where}: it answered HTTP ${status}. The endpoint refused the API key. Check the apiKey (or RISICARE_API_KEY) and the project it belongs to. ${tail}`
|
|
478
|
+
);
|
|
479
|
+
} else if (kind === "http") {
|
|
480
|
+
warn(
|
|
481
|
+
`${where}: it answered HTTP ${status}. The server did not take the batch. Check the endpoint and the server. ${tail} Set debug: true to see each attempt.`
|
|
482
|
+
);
|
|
483
|
+
} else if (kind === "none" && this._endpointHasCredentials) {
|
|
484
|
+
warn(
|
|
485
|
+
`${where}: no answer (${error}). The endpoint URL holds credentials (a user name or a password before the host), and fetch does not send a request to such a URL. Remove the credentials from the endpoint URL. ${tail}`
|
|
486
|
+
);
|
|
487
|
+
} else if (kind === "none") {
|
|
488
|
+
warn(
|
|
489
|
+
`${where}: no answer (${error}). The endpoint cannot be reached, or it did not answer in time. Check the endpoint and the network. ${tail} Set debug: true to see each attempt.`
|
|
490
|
+
);
|
|
491
|
+
} else {
|
|
492
|
+
warn(
|
|
493
|
+
`${where}: the export failed. Common causes: an invalid apiKey or an unreachable endpoint. ${tail} Set debug: true to see each attempt.`
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
/** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
|
|
498
|
+
_noteMisroute(call, answer) {
|
|
499
|
+
call.misroute = this._scrub(answer, 300);
|
|
500
|
+
debug(`Ingest misroute: ${call.misroute}`);
|
|
501
|
+
return "failure" /* FAILURE */;
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
|
|
505
|
+
*
|
|
506
|
+
* `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
|
|
507
|
+
* HTTP-date); anything else falls back to our own backoff rather than guessing at a date
|
|
508
|
+
* parse.
|
|
509
|
+
*/
|
|
510
|
+
_noteRefusal(call, status, retryAfterRaw) {
|
|
511
|
+
if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
|
|
512
|
+
let delay = REFUSAL_NO_HINT;
|
|
513
|
+
if (retryAfterRaw) {
|
|
514
|
+
const secs = Number(retryAfterRaw);
|
|
515
|
+
if (Number.isFinite(secs) && secs >= 0) {
|
|
516
|
+
delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
call.refusalAfterMs = delay;
|
|
520
|
+
debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
|
|
521
|
+
return true;
|
|
522
|
+
}
|
|
523
|
+
async _sendRequest(body, spansSent, call, spans) {
|
|
524
|
+
const cancelled = call.cancel.signal;
|
|
525
|
+
const timeoutMs = this._timeoutMs;
|
|
526
|
+
const url = `${this._endpoint}/v1/spans`;
|
|
527
|
+
const headers = {
|
|
528
|
+
"Content-Type": "application/json",
|
|
529
|
+
"User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
|
|
530
|
+
// F-SDKVER-001 parity. Python's ingest exporter has always sent
|
|
531
|
+
// `X-Risicare-SDK-Version`; JS sent only a User-Agent, so the two SDKs
|
|
532
|
+
// disagreed about how a client identifies itself. A parser-free header is
|
|
533
|
+
// strictly easier for the gateway to consume than picking a version out of
|
|
534
|
+
// a UA string.
|
|
535
|
+
"X-Risicare-SDK-Version": SDK_VERSION
|
|
536
|
+
};
|
|
537
|
+
if (this._apiKey) {
|
|
538
|
+
headers["Authorization"] = `Bearer ${this._apiKey}`;
|
|
539
|
+
}
|
|
540
|
+
let payload = body;
|
|
541
|
+
if (this._compress && payload.length > 1024) {
|
|
542
|
+
try {
|
|
543
|
+
const { gzipSync } = await import("zlib");
|
|
544
|
+
payload = gzipSync(Buffer.from(payload));
|
|
545
|
+
headers["Content-Encoding"] = "gzip";
|
|
546
|
+
} catch (e) {
|
|
547
|
+
debug(`Gzip compression failed, sending uncompressed: ${this._scrub(e)}`);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
const controller = new AbortController();
|
|
551
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
552
|
+
const onCancel = () => controller.abort();
|
|
553
|
+
cancelled.addEventListener("abort", onCancel, { once: true });
|
|
554
|
+
if (cancelled.aborted) controller.abort();
|
|
555
|
+
try {
|
|
556
|
+
const response = await fetch(url, {
|
|
557
|
+
method: "POST",
|
|
558
|
+
headers,
|
|
559
|
+
body: payload,
|
|
560
|
+
signal: controller.signal,
|
|
561
|
+
// Never follow: a redirect is a misroute (see MISROUTE_WARN_WINDOW_MS). Node returns
|
|
562
|
+
// the 3xx itself; a browser-like runtime returns type 'opaqueredirect' with status 0.
|
|
563
|
+
redirect: "manual"
|
|
564
|
+
});
|
|
565
|
+
call.status = response.status;
|
|
566
|
+
const redirected = response.type === "opaqueredirect";
|
|
567
|
+
if (redirected || response.status >= 300 && response.status < 400) {
|
|
568
|
+
const location = response.headers?.get?.("Location");
|
|
569
|
+
const target = location ? this._scrub(location, 1e3) : "no Location header";
|
|
570
|
+
return this._noteMisroute(call, `HTTP ${response.status || "3xx"}, a redirect to ${target}`);
|
|
571
|
+
}
|
|
572
|
+
if (response.status >= 200 && response.status < 300) {
|
|
573
|
+
const ack = await checkAck(response, spansSent, (t) => this._scrub(t, 1e3));
|
|
574
|
+
if (ack === null) {
|
|
575
|
+
if (controller.signal.aborted) {
|
|
576
|
+
call.status = null;
|
|
577
|
+
call.error = `timeout after ${timeoutMs} ms`;
|
|
578
|
+
debug(`HTTP export timeout: the ack body did not arrive within ${timeoutMs} ms`);
|
|
579
|
+
return "timeout" /* TIMEOUT */;
|
|
580
|
+
}
|
|
581
|
+
return this._noteMisroute(
|
|
582
|
+
call,
|
|
583
|
+
`HTTP ${response.status} and a body that is not a Risicare ack (content-type: ${response.headers?.get?.("Content-Type") || "none"})`
|
|
584
|
+
);
|
|
585
|
+
}
|
|
586
|
+
if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
|
|
587
|
+
if (ack.final) call.noRetry = true;
|
|
588
|
+
return ack.result;
|
|
589
|
+
} else if (response.status === 408 || response.status === 504) {
|
|
590
|
+
debug(`HTTP export timeout: ${response.status}`);
|
|
591
|
+
return "timeout" /* TIMEOUT */;
|
|
592
|
+
}
|
|
593
|
+
this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
|
|
594
|
+
debug(`HTTP export failed: ${response.status}`);
|
|
595
|
+
return "failure" /* FAILURE */;
|
|
596
|
+
} catch (e) {
|
|
597
|
+
const cause = e instanceof Error ? e.cause : void 0;
|
|
598
|
+
call.error = controller.signal.aborted ? `timeout after ${timeoutMs} ms` : typeof cause?.code === "string" ? cause.code : e instanceof Error ? e.name : "Error";
|
|
599
|
+
debug(`HTTP export error: ${this._scrub(e)}`);
|
|
600
|
+
return "failure" /* FAILURE */;
|
|
601
|
+
} finally {
|
|
602
|
+
clearTimeout(timeoutId);
|
|
603
|
+
cancelled.removeEventListener("abort", onCancel);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
shutdown() {
|
|
607
|
+
}
|
|
608
|
+
};
|
|
609
|
+
function sleep(ms, signal) {
|
|
610
|
+
return new Promise((resolve) => {
|
|
611
|
+
if (signal?.aborted) return resolve();
|
|
612
|
+
const done = () => {
|
|
613
|
+
clearTimeout(timer);
|
|
614
|
+
signal?.removeEventListener("abort", done);
|
|
615
|
+
resolve();
|
|
616
|
+
};
|
|
617
|
+
const timer = setTimeout(done, ms);
|
|
618
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
function asCount(v) {
|
|
622
|
+
return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
|
|
623
|
+
}
|
|
624
|
+
var MAX_ACK_REASONS = 3;
|
|
625
|
+
var MAX_ACK_REASON_CHARS = 200;
|
|
626
|
+
function oneLine(text) {
|
|
627
|
+
return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ");
|
|
628
|
+
}
|
|
629
|
+
function ackReasons(body) {
|
|
630
|
+
const reasons = [];
|
|
631
|
+
const errors = body.errors;
|
|
632
|
+
if (Array.isArray(errors)) {
|
|
633
|
+
for (const entry of errors) {
|
|
634
|
+
const text = entry?.error;
|
|
635
|
+
if (typeof text !== "string" || text.length === 0) continue;
|
|
636
|
+
const cut = oneLine(text).slice(0, MAX_ACK_REASON_CHARS);
|
|
637
|
+
if (!reasons.includes(cut)) reasons.push(cut);
|
|
638
|
+
if (reasons.length === MAX_ACK_REASONS) break;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
if (reasons.length === 0) {
|
|
642
|
+
const message = typeof body.errorMessage === "string" && body.errorMessage || typeof body.error_message === "string" && body.error_message || "";
|
|
643
|
+
if (message) reasons.push(oneLine(message).slice(0, MAX_ACK_REASON_CHARS));
|
|
644
|
+
}
|
|
645
|
+
return reasons.length === 0 ? "No reason was returned." : `Reasons: ${reasons.join("; ")}`;
|
|
646
|
+
}
|
|
647
|
+
async function checkAck(response, spansSent, scrub) {
|
|
648
|
+
let payload;
|
|
649
|
+
try {
|
|
650
|
+
payload = await response.json();
|
|
651
|
+
} catch {
|
|
652
|
+
return null;
|
|
653
|
+
}
|
|
654
|
+
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
|
|
655
|
+
return null;
|
|
656
|
+
}
|
|
657
|
+
const body = payload;
|
|
658
|
+
const accepted = asCount(body.accepted);
|
|
659
|
+
const rejected = asCount(body.rejected);
|
|
660
|
+
if (accepted === void 0 || rejected === void 0) return null;
|
|
661
|
+
const counts = { accepted, rejected };
|
|
662
|
+
if (accepted === 0 && rejected === 0 && spansSent > 0) {
|
|
663
|
+
warn(
|
|
664
|
+
`Risicare: the backend acknowledged 0 of ${spansSent} span(s): its ack counts no span as accepted or rejected. This batch is counted as NOT delivered.`
|
|
665
|
+
);
|
|
666
|
+
return { result: "failure" /* FAILURE */, counts, final: true };
|
|
667
|
+
}
|
|
668
|
+
if (rejected === 0) return { result: "success" /* SUCCESS */, counts, final: false };
|
|
669
|
+
const total = accepted + rejected;
|
|
670
|
+
if (accepted === 0) {
|
|
671
|
+
warn(
|
|
672
|
+
`Risicare: the backend accepted 0 of ${total} span(s) and rejected ${rejected} \u2014 this batch was NOT stored. Rejected spans are permanently lost and are NOT retried. ${scrub(ackReasons(body))}`
|
|
673
|
+
);
|
|
674
|
+
return { result: "success" /* SUCCESS */, counts, final: false };
|
|
675
|
+
}
|
|
676
|
+
warn(
|
|
677
|
+
`Risicare: the backend rejected ${rejected} of ${total} span(s); the remaining ${accepted} were stored. Those ${rejected} are permanently lost and are NOT retried. ${scrub(ackReasons(body))}`
|
|
678
|
+
);
|
|
679
|
+
return { result: "success" /* SUCCESS */, counts, final: false };
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// src/utils/read-safely.ts
|
|
683
|
+
var logged = /* @__PURE__ */ new Set();
|
|
684
|
+
var LOGGED_MAX = 1e3;
|
|
685
|
+
function className(error) {
|
|
686
|
+
if (error !== null && typeof error === "object") {
|
|
687
|
+
const name = error.constructor?.name;
|
|
688
|
+
if (typeof name === "string" && name) return name;
|
|
689
|
+
}
|
|
690
|
+
return typeof error;
|
|
691
|
+
}
|
|
692
|
+
function responseReadFailed(provider, site, error, span) {
|
|
693
|
+
try {
|
|
694
|
+
const cls = className(error);
|
|
695
|
+
span?.setAttribute("risicare.observer_error", cls);
|
|
696
|
+
if (!getDebug()) return;
|
|
697
|
+
const key = `${provider}\0${site}\0${cls}`;
|
|
698
|
+
if (logged.has(key) || logged.size >= LOGGED_MAX) return;
|
|
699
|
+
logged.add(key);
|
|
700
|
+
debug(`could not read the ${provider} response in ${site} (${cls}); the span keeps fewer facts`);
|
|
701
|
+
} catch {
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
function readResponseSafely(provider, site, span, read) {
|
|
705
|
+
try {
|
|
706
|
+
read();
|
|
707
|
+
} catch (error) {
|
|
708
|
+
responseReadFailed(provider, site, error, span);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
123
712
|
// src/runtime/applier.ts
|
|
124
713
|
import { createHash } from "crypto";
|
|
125
714
|
|
|
715
|
+
// src/runtime/loader.ts
|
|
716
|
+
var FixLoader = class _FixLoader {
|
|
717
|
+
_config;
|
|
718
|
+
_cache;
|
|
719
|
+
_refreshTimer = null;
|
|
720
|
+
_lastLoadTime = null;
|
|
721
|
+
_consecutiveFailures = 0;
|
|
722
|
+
_circuitOpenUntil = 0;
|
|
723
|
+
_onLoadCallbacks = [];
|
|
724
|
+
// The HTTP status of the last load that got a non-2xx answer; null otherwise.
|
|
725
|
+
_lastStatus = null;
|
|
726
|
+
// Circuit breaker settings
|
|
727
|
+
static CIRCUIT_BREAKER_THRESHOLD = 3;
|
|
728
|
+
static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
|
|
729
|
+
constructor(config, cache) {
|
|
730
|
+
this._config = resolveFixRuntimeConfig(config);
|
|
731
|
+
this._cache = cache;
|
|
732
|
+
}
|
|
733
|
+
/** Error text for a log line: one line, the api endpoint as `safeUrl` gives it, no key. */
|
|
734
|
+
_scrub(error) {
|
|
735
|
+
let out;
|
|
736
|
+
try {
|
|
737
|
+
out = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
738
|
+
} catch {
|
|
739
|
+
out = typeof error;
|
|
740
|
+
}
|
|
741
|
+
const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
|
|
742
|
+
if (endpoint && safeUrl(endpoint) !== endpoint) out = out.split(endpoint).join(safeUrl(endpoint));
|
|
743
|
+
return scrubText(out, [this._config.apiKey]);
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* The WARNING for a failed first load: the request URL with no userinfo, no
|
|
747
|
+
* query and no key, the HTTP status or the error class, and that tracing is
|
|
748
|
+
* not affected. Never the error text: it can echo the URL with its query.
|
|
749
|
+
*/
|
|
750
|
+
_firstLoadWarning(error) {
|
|
751
|
+
let cause;
|
|
752
|
+
if (this._lastStatus !== null) {
|
|
753
|
+
cause = `HTTP ${this._lastStatus}`;
|
|
754
|
+
} else {
|
|
755
|
+
cause = error instanceof Error ? error.name : typeof error;
|
|
756
|
+
const code = error?.cause?.code;
|
|
757
|
+
if (typeof code === "string" && /^[A-Z][A-Z0-9_]*$/.test(code)) cause += ` (${code})`;
|
|
758
|
+
}
|
|
759
|
+
const endpoint = (this._config.apiEndpoint ?? "").replace(/\/+$/, "");
|
|
760
|
+
return scrubText(
|
|
761
|
+
`The first load of the fixes from ${safeUrl(endpoint)}/v1/fixes/active failed (${cause}). No fix is applied until a later load succeeds. Tracing is not affected.`,
|
|
762
|
+
[this._config.apiKey],
|
|
763
|
+
500
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
/** Hide the key from `util.inspect` and `console.log` of the loader. */
|
|
767
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
768
|
+
return "FixLoader {}";
|
|
769
|
+
}
|
|
770
|
+
/** Timestamp of last successful load. */
|
|
771
|
+
get lastLoadTime() {
|
|
772
|
+
return this._lastLoadTime;
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Start the loader: perform initial load and start background refresh.
|
|
776
|
+
*
|
|
777
|
+
* Never throws — failures are logged and the runtime degrades gracefully.
|
|
778
|
+
*/
|
|
779
|
+
start() {
|
|
780
|
+
try {
|
|
781
|
+
if (!this._config.enabled) {
|
|
782
|
+
debug("Fix runtime disabled, skipping loader start");
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
if (!this._config.apiKey) {
|
|
786
|
+
warn("No API key configured, fixes will not be loaded");
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
this.loadSync().catch((e) => {
|
|
790
|
+
warn(this._firstLoadWarning(e));
|
|
791
|
+
});
|
|
792
|
+
if (this._config.autoRefresh) {
|
|
793
|
+
this._startRefreshInterval();
|
|
794
|
+
}
|
|
795
|
+
} catch (e) {
|
|
796
|
+
debug(`FixLoader.start error: ${this._scrub(e)}`);
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
/** Stop the loader: clear the refresh interval. */
|
|
800
|
+
stop() {
|
|
801
|
+
try {
|
|
802
|
+
if (this._refreshTimer !== null) {
|
|
803
|
+
clearInterval(this._refreshTimer);
|
|
804
|
+
this._refreshTimer = null;
|
|
805
|
+
}
|
|
806
|
+
} catch (e) {
|
|
807
|
+
debug(`FixLoader.stop error: ${this._scrub(e)}`);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* Register a callback invoked after each successful load.
|
|
812
|
+
*/
|
|
813
|
+
onLoad(callback) {
|
|
814
|
+
this._onLoadCallbacks.push(callback);
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Load fixes from the API.
|
|
818
|
+
*
|
|
819
|
+
* Name kept as "loadSync" for parity with the Python SDK, but this
|
|
820
|
+
* returns a Promise in JS (there's no synchronous fetch in Node.js).
|
|
821
|
+
*/
|
|
822
|
+
async loadSync() {
|
|
823
|
+
if (!this._config.apiKey) {
|
|
824
|
+
return [];
|
|
825
|
+
}
|
|
826
|
+
const now = Date.now();
|
|
827
|
+
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && now < this._circuitOpenUntil) {
|
|
828
|
+
debug("Fix loader circuit breaker open \u2014 skipping load");
|
|
829
|
+
return this._cache.getAll();
|
|
830
|
+
}
|
|
831
|
+
this._lastStatus = null;
|
|
832
|
+
try {
|
|
833
|
+
const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
|
|
834
|
+
const url = `${endpoint}/v1/fixes/active`;
|
|
835
|
+
const controller = new AbortController();
|
|
836
|
+
const timeoutId = setTimeout(
|
|
837
|
+
() => controller.abort(),
|
|
838
|
+
this._config.timeoutMs
|
|
839
|
+
);
|
|
840
|
+
const response = await fetch(url, {
|
|
841
|
+
method: "GET",
|
|
842
|
+
headers: {
|
|
843
|
+
"Authorization": `Bearer ${this._config.apiKey}`,
|
|
844
|
+
"Content-Type": "application/json",
|
|
845
|
+
"X-Risicare-SDK-Version": SDK_VERSION
|
|
846
|
+
},
|
|
847
|
+
signal: controller.signal
|
|
848
|
+
});
|
|
849
|
+
clearTimeout(timeoutId);
|
|
850
|
+
if (!response.ok) {
|
|
851
|
+
this._lastStatus = response.status;
|
|
852
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
853
|
+
}
|
|
854
|
+
const data = await response.json();
|
|
855
|
+
const fixes = this._parseResponse(data);
|
|
856
|
+
this._onLoadSuccess(fixes);
|
|
857
|
+
return fixes;
|
|
858
|
+
} catch (e) {
|
|
859
|
+
this._onLoadFailure(e);
|
|
860
|
+
throw e;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
/** Get currently cached fixes without hitting the API. */
|
|
864
|
+
getCached() {
|
|
865
|
+
return this._cache.getAll();
|
|
866
|
+
}
|
|
867
|
+
// ─── Private ────────────────────────────────────────────────────────────
|
|
868
|
+
_parseResponse(data) {
|
|
869
|
+
const fixes = [];
|
|
870
|
+
const items = data.fixes ?? data.data ?? [];
|
|
871
|
+
if (!Array.isArray(items)) return fixes;
|
|
872
|
+
for (const item of items) {
|
|
873
|
+
try {
|
|
874
|
+
if (item && typeof item === "object") {
|
|
875
|
+
fixes.push(activeFixFromApiResponse(item));
|
|
876
|
+
}
|
|
877
|
+
} catch (e) {
|
|
878
|
+
debug(`Failed to parse fix item: ${this._scrub(e)}`);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
return fixes;
|
|
882
|
+
}
|
|
883
|
+
_onLoadSuccess(fixes) {
|
|
884
|
+
this._lastLoadTime = Date.now();
|
|
885
|
+
this._consecutiveFailures = 0;
|
|
886
|
+
this._cache.setAll(fixes);
|
|
887
|
+
for (const callback of this._onLoadCallbacks) {
|
|
888
|
+
try {
|
|
889
|
+
callback(fixes);
|
|
890
|
+
} catch (e) {
|
|
891
|
+
debug(`Load callback error: ${this._scrub(e)}`);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
debug(`Loaded ${fixes.length} active fixes`);
|
|
895
|
+
}
|
|
896
|
+
_onLoadFailure(error) {
|
|
897
|
+
this._consecutiveFailures++;
|
|
898
|
+
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD) {
|
|
899
|
+
this._circuitOpenUntil = Date.now() + _FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS;
|
|
900
|
+
warn(
|
|
901
|
+
`Fix loader circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${_FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS / 1e3}s`
|
|
902
|
+
);
|
|
903
|
+
} else {
|
|
904
|
+
debug(
|
|
905
|
+
`Fix load failed (attempt ${this._consecutiveFailures}): ${this._scrub(error)}`
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
_startRefreshInterval() {
|
|
910
|
+
const tick = () => {
|
|
911
|
+
this.loadSync().catch((e) => {
|
|
912
|
+
debug(`Background fix refresh failed: ${this._scrub(e)}`);
|
|
913
|
+
});
|
|
914
|
+
};
|
|
915
|
+
this._refreshTimer = setInterval(
|
|
916
|
+
() => {
|
|
917
|
+
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && Date.now() < this._circuitOpenUntil) {
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
tick();
|
|
921
|
+
},
|
|
922
|
+
this._config.refreshIntervalMs
|
|
923
|
+
);
|
|
924
|
+
this._refreshTimer.unref();
|
|
925
|
+
debug("Started fix refresh interval");
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
|
|
126
929
|
// src/client.ts
|
|
930
|
+
var SCORE_MAX_WAITING = 1e3;
|
|
931
|
+
var SCORE_CAP_REASON = `not sent: ${SCORE_MAX_WAITING} scores wait for a free slot`;
|
|
127
932
|
function requireTracer() {
|
|
128
933
|
const tracer = getTracer();
|
|
129
934
|
if (!tracer) {
|
|
@@ -181,6 +986,23 @@ function calculateCost(model, promptTokens, completionTokens) {
|
|
|
181
986
|
return inputCost + outputCost;
|
|
182
987
|
}
|
|
183
988
|
|
|
989
|
+
// src/utils/token-usage.ts
|
|
990
|
+
function tokenCount(value) {
|
|
991
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
992
|
+
}
|
|
993
|
+
function recordTokenUsage(span, counts, model) {
|
|
994
|
+
const promptTokens = tokenCount(counts.prompt);
|
|
995
|
+
const completionTokens = tokenCount(counts.completion);
|
|
996
|
+
const bothKnown = promptTokens !== void 0 && completionTokens !== void 0;
|
|
997
|
+
const totalTokens = tokenCount(counts.total) ?? (bothKnown ? promptTokens + completionTokens : void 0);
|
|
998
|
+
const costUsd = model && bothKnown ? calculateCost(model, promptTokens, completionTokens) : void 0;
|
|
999
|
+
span.setLlmFields({ promptTokens, completionTokens, totalTokens, costUsd });
|
|
1000
|
+
if (promptTokens !== void 0) span.setAttribute("gen_ai.usage.prompt_tokens", promptTokens);
|
|
1001
|
+
if (completionTokens !== void 0) span.setAttribute("gen_ai.usage.completion_tokens", completionTokens);
|
|
1002
|
+
if (totalTokens !== void 0) span.setAttribute("gen_ai.usage.total_tokens", totalTokens);
|
|
1003
|
+
if (costUsd !== void 0) span.setAttribute("llm.cost.total_usd", costUsd);
|
|
1004
|
+
}
|
|
1005
|
+
|
|
184
1006
|
// src/utils/assert-client.ts
|
|
185
1007
|
function assertClient(patcherName, client) {
|
|
186
1008
|
if (client === null || client === void 0) {
|
|
@@ -242,16 +1064,7 @@ function enrichFromConverseResponse(span, response) {
|
|
|
242
1064
|
const responseModel = response.modelId;
|
|
243
1065
|
if (responseModel) span.setAttribute("gen_ai.response.model", responseModel);
|
|
244
1066
|
if (usage) {
|
|
245
|
-
|
|
246
|
-
const completionTokens = usage.outputTokens ?? 0;
|
|
247
|
-
const totalTokens = usage.totalTokens ?? promptTokens + completionTokens;
|
|
248
|
-
const model = span.llmModel;
|
|
249
|
-
const cost = model ? calculateCost(model, promptTokens, completionTokens) : void 0;
|
|
250
|
-
span.setLlmFields({ promptTokens, completionTokens, totalTokens, costUsd: cost });
|
|
251
|
-
span.setAttribute("gen_ai.usage.prompt_tokens", promptTokens);
|
|
252
|
-
span.setAttribute("gen_ai.usage.completion_tokens", completionTokens);
|
|
253
|
-
span.setAttribute("gen_ai.usage.total_tokens", totalTokens);
|
|
254
|
-
if (cost !== void 0) span.setAttribute("llm.cost.total_usd", cost);
|
|
1067
|
+
recordTokenUsage(span, { prompt: usage.inputTokens, completion: usage.outputTokens, total: usage.totalTokens }, span.llmModel);
|
|
255
1068
|
}
|
|
256
1069
|
const stopReason = response.stopReason;
|
|
257
1070
|
if (stopReason) {
|
|
@@ -261,7 +1074,8 @@ function enrichFromConverseResponse(span, response) {
|
|
|
261
1074
|
if (metrics?.latencyMs != null) {
|
|
262
1075
|
span.setAttribute("bedrock.latency_ms", metrics.latencyMs);
|
|
263
1076
|
}
|
|
264
|
-
} catch {
|
|
1077
|
+
} catch (error) {
|
|
1078
|
+
responseReadFailed("bedrock", "enrichFromConverseResponse", error, span);
|
|
265
1079
|
}
|
|
266
1080
|
}
|
|
267
1081
|
function enrichFromInvokeModelResponse(span, response) {
|
|
@@ -283,22 +1097,14 @@ function enrichFromInvokeModelResponse(span, response) {
|
|
|
283
1097
|
if (stopReason) span.setAttribute("gen_ai.response.finish_reasons", [stopReason]);
|
|
284
1098
|
const usage = parsed.usage;
|
|
285
1099
|
if (usage) {
|
|
286
|
-
|
|
287
|
-
const completionTokens = usage.output_tokens ?? usage.outputTokens ?? 0;
|
|
288
|
-
const totalTokens = promptTokens + completionTokens;
|
|
289
|
-
const model = span.llmModel;
|
|
290
|
-
const cost = model ? calculateCost(model, promptTokens, completionTokens) : void 0;
|
|
291
|
-
span.setLlmFields({ promptTokens, completionTokens, totalTokens, costUsd: cost });
|
|
292
|
-
span.setAttribute("gen_ai.usage.prompt_tokens", promptTokens);
|
|
293
|
-
span.setAttribute("gen_ai.usage.completion_tokens", completionTokens);
|
|
294
|
-
span.setAttribute("gen_ai.usage.total_tokens", totalTokens);
|
|
295
|
-
if (cost !== void 0) span.setAttribute("llm.cost.total_usd", cost);
|
|
1100
|
+
recordTokenUsage(span, { prompt: usage.input_tokens ?? usage.inputTokens, completion: usage.output_tokens ?? usage.outputTokens }, span.llmModel);
|
|
296
1101
|
}
|
|
297
1102
|
const results = parsed.results;
|
|
298
1103
|
if (results?.[0]?.tokenCount != null) {
|
|
299
1104
|
span.setAttribute("bedrock.output_token_count", results[0].tokenCount);
|
|
300
1105
|
}
|
|
301
|
-
} catch {
|
|
1106
|
+
} catch (error) {
|
|
1107
|
+
responseReadFailed("bedrock", "enrichFromInvokeModelResponse", error, span);
|
|
302
1108
|
}
|
|
303
1109
|
}
|
|
304
1110
|
function getCommandName(command) {
|
|
@@ -352,11 +1158,13 @@ function createSendProxy(originalSend) {
|
|
|
352
1158
|
if (result && typeof result.then === "function") {
|
|
353
1159
|
return result.then((response) => {
|
|
354
1160
|
if (!response) return response;
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
1161
|
+
readResponseSafely("bedrock", "send", span, () => {
|
|
1162
|
+
if (commandName === "ConverseCommand") {
|
|
1163
|
+
enrichFromConverseResponse(span, response);
|
|
1164
|
+
} else if (commandName === "InvokeModelCommand") {
|
|
1165
|
+
enrichFromInvokeModelResponse(span, response);
|
|
1166
|
+
}
|
|
1167
|
+
});
|
|
360
1168
|
return response;
|
|
361
1169
|
});
|
|
362
1170
|
}
|