risicare 0.4.2 → 0.5.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 +30 -0
- package/dist/frameworks/instructor.cjs +26 -19
- package/dist/frameworks/instructor.cjs.map +1 -1
- package/dist/frameworks/instructor.js +26 -19
- package/dist/frameworks/instructor.js.map +1 -1
- package/dist/frameworks/langchain.cjs +32 -25
- package/dist/frameworks/langchain.cjs.map +1 -1
- package/dist/frameworks/langchain.js +32 -25
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/frameworks/langgraph.cjs +32 -25
- package/dist/frameworks/langgraph.cjs.map +1 -1
- package/dist/frameworks/langgraph.js +32 -25
- package/dist/frameworks/langgraph.js.map +1 -1
- package/dist/frameworks/llamaindex.cjs +21 -14
- package/dist/frameworks/llamaindex.cjs.map +1 -1
- package/dist/frameworks/llamaindex.js +21 -14
- package/dist/frameworks/llamaindex.js.map +1 -1
- package/dist/index.cjs +675 -239
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +200 -46
- package/dist/index.d.ts +200 -46
- package/dist/index.js +670 -235
- package/dist/index.js.map +1 -1
- package/dist/providers/anthropic/index.cjs +32 -25
- package/dist/providers/anthropic/index.cjs.map +1 -1
- package/dist/providers/anthropic/index.js +32 -25
- package/dist/providers/anthropic/index.js.map +1 -1
- package/dist/providers/bedrock/index.cjs +32 -25
- package/dist/providers/bedrock/index.cjs.map +1 -1
- package/dist/providers/bedrock/index.js +32 -25
- package/dist/providers/bedrock/index.js.map +1 -1
- package/dist/providers/cerebras/index.cjs +32 -25
- package/dist/providers/cerebras/index.cjs.map +1 -1
- package/dist/providers/cerebras/index.js +32 -25
- package/dist/providers/cerebras/index.js.map +1 -1
- package/dist/providers/cohere/index.cjs +32 -25
- package/dist/providers/cohere/index.cjs.map +1 -1
- package/dist/providers/cohere/index.js +32 -25
- package/dist/providers/cohere/index.js.map +1 -1
- package/dist/providers/google/index.cjs +32 -25
- package/dist/providers/google/index.cjs.map +1 -1
- package/dist/providers/google/index.js +32 -25
- package/dist/providers/google/index.js.map +1 -1
- package/dist/providers/groq/index.cjs +32 -25
- package/dist/providers/groq/index.cjs.map +1 -1
- package/dist/providers/groq/index.js +32 -25
- package/dist/providers/groq/index.js.map +1 -1
- package/dist/providers/huggingface/index.cjs +32 -25
- package/dist/providers/huggingface/index.cjs.map +1 -1
- package/dist/providers/huggingface/index.js +32 -25
- package/dist/providers/huggingface/index.js.map +1 -1
- package/dist/providers/mistral/index.cjs +32 -25
- package/dist/providers/mistral/index.cjs.map +1 -1
- package/dist/providers/mistral/index.js +32 -25
- package/dist/providers/mistral/index.js.map +1 -1
- package/dist/providers/ollama/index.cjs +32 -25
- package/dist/providers/ollama/index.cjs.map +1 -1
- package/dist/providers/ollama/index.js +32 -25
- package/dist/providers/ollama/index.js.map +1 -1
- package/dist/providers/openai/index.cjs +32 -25
- package/dist/providers/openai/index.cjs.map +1 -1
- package/dist/providers/openai/index.js +32 -25
- package/dist/providers/openai/index.js.map +1 -1
- package/dist/providers/together/index.cjs +32 -25
- package/dist/providers/together/index.cjs.map +1 -1
- package/dist/providers/together/index.js +32 -25
- package/dist/providers/together/index.js.map +1 -1
- package/dist/providers/vercel-ai/index.cjs +26 -19
- package/dist/providers/vercel-ai/index.cjs.map +1 -1
- package/dist/providers/vercel-ai/index.js +26 -19
- package/dist/providers/vercel-ai/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,6 +5,547 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
5
5
|
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
6
6
|
});
|
|
7
7
|
|
|
8
|
+
// src/client.ts
|
|
9
|
+
import { createHash as createHash2 } from "crypto";
|
|
10
|
+
|
|
11
|
+
// src/globals.ts
|
|
12
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
13
|
+
var G = globalThis;
|
|
14
|
+
var PREFIX = "__risicare_";
|
|
15
|
+
function getClient() {
|
|
16
|
+
return G[PREFIX + "client"];
|
|
17
|
+
}
|
|
18
|
+
function setClient(client) {
|
|
19
|
+
G[PREFIX + "client"] = client;
|
|
20
|
+
}
|
|
21
|
+
function getTracer() {
|
|
22
|
+
return G[PREFIX + "tracer"];
|
|
23
|
+
}
|
|
24
|
+
function setTracer(tracer) {
|
|
25
|
+
G[PREFIX + "tracer"] = tracer;
|
|
26
|
+
}
|
|
27
|
+
function getContextStorage() {
|
|
28
|
+
if (!G[PREFIX + "ctx"]) {
|
|
29
|
+
G[PREFIX + "ctx"] = new AsyncLocalStorage();
|
|
30
|
+
}
|
|
31
|
+
return G[PREFIX + "ctx"];
|
|
32
|
+
}
|
|
33
|
+
function getRegistry() {
|
|
34
|
+
if (!G[PREFIX + "registry"]) {
|
|
35
|
+
G[PREFIX + "registry"] = /* @__PURE__ */ new Map();
|
|
36
|
+
}
|
|
37
|
+
return G[PREFIX + "registry"];
|
|
38
|
+
}
|
|
39
|
+
function getOpCount() {
|
|
40
|
+
return G[PREFIX + "opcount"] ?? 0;
|
|
41
|
+
}
|
|
42
|
+
function setOpCount(n) {
|
|
43
|
+
G[PREFIX + "opcount"] = n;
|
|
44
|
+
}
|
|
45
|
+
function getDebug() {
|
|
46
|
+
return G[PREFIX + "debug"] ?? false;
|
|
47
|
+
}
|
|
48
|
+
function setDebugFlag(enabled) {
|
|
49
|
+
G[PREFIX + "debug"] = enabled;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/utils/log.ts
|
|
53
|
+
function setDebug(enabled) {
|
|
54
|
+
setDebugFlag(enabled);
|
|
55
|
+
}
|
|
56
|
+
function debug(msg) {
|
|
57
|
+
if (getDebug()) {
|
|
58
|
+
process.stderr.write(`[risicare] ${msg}
|
|
59
|
+
`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function warn(msg) {
|
|
63
|
+
process.stderr.write(`[risicare] WARNING: ${msg}
|
|
64
|
+
`);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// src/masking.ts
|
|
68
|
+
var MASK_ERROR_MARKER = "<risicare:mask-error>";
|
|
69
|
+
var MASK_BUDGET_MS_PER_SPAN = 1;
|
|
70
|
+
var MASK_WARN_WINDOW_MS = 3e5;
|
|
71
|
+
var SCORE_COMMENT_KEY = "score.comment";
|
|
72
|
+
function maskText(mask, key, value, onError) {
|
|
73
|
+
return maskString(mask, key, value, onError);
|
|
74
|
+
}
|
|
75
|
+
function maskOne(mask, key, value, onError) {
|
|
76
|
+
try {
|
|
77
|
+
return mask(key, value);
|
|
78
|
+
} catch (e) {
|
|
79
|
+
onError?.(key, e);
|
|
80
|
+
return MASK_ERROR_MARKER;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function maskString(mask, key, value, onError) {
|
|
84
|
+
const masked = maskOne(mask, key, value, onError);
|
|
85
|
+
if (typeof masked === "string") return masked;
|
|
86
|
+
try {
|
|
87
|
+
return String(masked);
|
|
88
|
+
} catch (e) {
|
|
89
|
+
onError?.(key, e);
|
|
90
|
+
return MASK_ERROR_MARKER;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function maskAttributes(mask, prefix, attrs, onError) {
|
|
94
|
+
for (const k of Object.keys(attrs)) {
|
|
95
|
+
attrs[k] = maskOne(mask, prefix + k, attrs[k], onError);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function isMasked(span) {
|
|
99
|
+
return span._risicareMasked === true;
|
|
100
|
+
}
|
|
101
|
+
function markMasked(span) {
|
|
102
|
+
try {
|
|
103
|
+
span._risicareMasked = true;
|
|
104
|
+
} catch {
|
|
105
|
+
debug("Could not mark span as masked; a re-queue may re-mask it");
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function applyMask(span, mask, onError) {
|
|
109
|
+
if (isMasked(span)) return;
|
|
110
|
+
if (span.attributes && typeof span.attributes === "object") {
|
|
111
|
+
maskAttributes(mask, "", span.attributes, onError);
|
|
112
|
+
}
|
|
113
|
+
if (span.statusMessage !== void 0) {
|
|
114
|
+
span.statusMessage = maskString(mask, "statusMessage", span.statusMessage, onError);
|
|
115
|
+
}
|
|
116
|
+
if (Array.isArray(span.events)) {
|
|
117
|
+
span.events.forEach((event, i) => {
|
|
118
|
+
if (event?.attributes && typeof event.attributes === "object") {
|
|
119
|
+
maskAttributes(mask, `events.${i}.attributes.`, event.attributes, onError);
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
if (Array.isArray(span.links)) {
|
|
124
|
+
span.links.forEach((link, i) => {
|
|
125
|
+
if (link?.attributes && typeof link.attributes === "object") {
|
|
126
|
+
maskAttributes(mask, `links.${i}.attributes.`, link.attributes, onError);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
markMasked(span);
|
|
131
|
+
}
|
|
132
|
+
function applyMaskBatch(spans, mask, onError) {
|
|
133
|
+
let errors = 0;
|
|
134
|
+
let firstKey;
|
|
135
|
+
let firstError;
|
|
136
|
+
const report = (key, error) => {
|
|
137
|
+
errors++;
|
|
138
|
+
if (firstKey === void 0) {
|
|
139
|
+
firstKey = key;
|
|
140
|
+
firstError = error;
|
|
141
|
+
}
|
|
142
|
+
onError?.(key, error);
|
|
143
|
+
};
|
|
144
|
+
const started = Date.now();
|
|
145
|
+
for (const span of spans) {
|
|
146
|
+
applyMask(span, mask, report);
|
|
147
|
+
}
|
|
148
|
+
const elapsedMs = Date.now() - started;
|
|
149
|
+
if (errors > 0 && firstKey !== void 0) {
|
|
150
|
+
debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${String(firstError)}`);
|
|
151
|
+
}
|
|
152
|
+
return { errors, elapsedMs };
|
|
153
|
+
}
|
|
154
|
+
function warnMaskErrors(batchErrors, totalErrors) {
|
|
155
|
+
warn(
|
|
156
|
+
`the mask callback threw on ${batchErrors} field(s) in this batch (${totalErrors} since start). Those fields were replaced with "${MASK_ERROR_MARKER}" and the spans were exported intact \u2014 no span was dropped. Fix the callback; until then those fields carry no data.`
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
function warnMaskSlow(spanCount, elapsedMs) {
|
|
160
|
+
warn(
|
|
161
|
+
`masking ${spanCount} span(s) took ${elapsedMs} ms (budget ${MASK_BUDGET_MS_PER_SPAN * spanCount} ms, ${MASK_BUDGET_MS_PER_SPAN} ms/span). Node is single-threaded: this time is taken from your event loop, so it delays your application as well as the export drain, and a queue that cannot drain drops spans (reason=queue_full). Keep the callback CPU-only: no I/O, no network, no unbounded retries.`
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// src/exporters/batch.ts
|
|
166
|
+
var SHUTDOWN_RESERVE_MS = 100;
|
|
167
|
+
var SHUTDOWN_BUDGET_MS = 5e3;
|
|
168
|
+
var REFUSAL_WARN_WINDOW_MS = 3e5;
|
|
169
|
+
var DEFAULT_BATCH_SIZE = 500;
|
|
170
|
+
var MAX_ATTRIBUTE_PAIRS_PER_BATCH = 24e3;
|
|
171
|
+
var MAX_BATCH_BYTES = 8 * 1024 * 1024;
|
|
172
|
+
var SPAN_ENVELOPE_BYTES = 512;
|
|
173
|
+
var CHILD_ENVELOPE_BYTES = 128;
|
|
174
|
+
var SCALAR_BYTES = 24;
|
|
175
|
+
var LITERAL_BYTES = 5;
|
|
176
|
+
var EST_MAX_DEPTH = 4;
|
|
177
|
+
var EST_OPAQUE_VALUE_BYTES = 4096;
|
|
178
|
+
var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
|
|
179
|
+
function estStringBytes(s) {
|
|
180
|
+
return 2 + utf8ByteLength(s);
|
|
181
|
+
}
|
|
182
|
+
function estValueBytes(v, depth = 0) {
|
|
183
|
+
if (typeof v === "string") return estStringBytes(v);
|
|
184
|
+
if (v === null || v === void 0 || typeof v === "boolean") return LITERAL_BYTES;
|
|
185
|
+
if (typeof v === "number" || typeof v === "bigint") return SCALAR_BYTES;
|
|
186
|
+
if (Array.isArray(v) && depth < EST_MAX_DEPTH) {
|
|
187
|
+
let total = 2 + Math.max(0, v.length - 1);
|
|
188
|
+
for (const item of v) total += estValueBytes(item, depth + 1);
|
|
189
|
+
return total;
|
|
190
|
+
}
|
|
191
|
+
if (typeof v === "object" && depth < EST_MAX_DEPTH && Object.getPrototypeOf(v) === Object.prototype) {
|
|
192
|
+
let total = 2;
|
|
193
|
+
for (const [k, val] of Object.entries(v)) {
|
|
194
|
+
total += estStringBytes(k) + 2 + estValueBytes(val, depth + 1);
|
|
195
|
+
}
|
|
196
|
+
return total;
|
|
197
|
+
}
|
|
198
|
+
return EST_OPAQUE_VALUE_BYTES;
|
|
199
|
+
}
|
|
200
|
+
function estMappingBytes(m) {
|
|
201
|
+
let total = 0;
|
|
202
|
+
for (const [k, v] of Object.entries(m)) total += estStringBytes(k) + 2 + estValueBytes(v);
|
|
203
|
+
return total;
|
|
204
|
+
}
|
|
205
|
+
function spanBytesEstimate(span) {
|
|
206
|
+
try {
|
|
207
|
+
const s = span;
|
|
208
|
+
let total = SPAN_ENVELOPE_BYTES;
|
|
209
|
+
for (const field of ["name", "statusMessage"]) {
|
|
210
|
+
if (typeof s[field] === "string") total += estStringBytes(s[field]);
|
|
211
|
+
}
|
|
212
|
+
const attrs = s.attributes;
|
|
213
|
+
if (attrs != null && typeof attrs === "object" && !Array.isArray(attrs)) {
|
|
214
|
+
total += estMappingBytes(attrs);
|
|
215
|
+
}
|
|
216
|
+
for (const key of ["events", "links"]) {
|
|
217
|
+
const coll = s[key];
|
|
218
|
+
if (!Array.isArray(coll)) continue;
|
|
219
|
+
for (const child of coll) {
|
|
220
|
+
total += CHILD_ENVELOPE_BYTES;
|
|
221
|
+
const ca = child?.attributes;
|
|
222
|
+
if (ca != null && typeof ca === "object" && !Array.isArray(ca)) {
|
|
223
|
+
total += estMappingBytes(ca);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return total;
|
|
228
|
+
} catch {
|
|
229
|
+
return SPAN_ENVELOPE_BYTES;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
function spanAttrCount(span) {
|
|
233
|
+
const attrs = span.attributes;
|
|
234
|
+
if (attrs == null) return 0;
|
|
235
|
+
if (attrs instanceof Map) return attrs.size;
|
|
236
|
+
if (typeof attrs === "object") return Object.keys(attrs).length;
|
|
237
|
+
return 0;
|
|
238
|
+
}
|
|
239
|
+
var BatchSpanProcessor = class _BatchSpanProcessor {
|
|
240
|
+
_exporters;
|
|
241
|
+
_batchSize;
|
|
242
|
+
_batchTimeoutMs;
|
|
243
|
+
_maxQueueSize;
|
|
244
|
+
_debug;
|
|
245
|
+
_queue = [];
|
|
246
|
+
_timer = null;
|
|
247
|
+
_started = false;
|
|
248
|
+
_flushing = false;
|
|
249
|
+
_beforeExitHandler = null;
|
|
250
|
+
// Retry tracking for failed batches (Audit #5)
|
|
251
|
+
_retryCounts = /* @__PURE__ */ new Map();
|
|
252
|
+
static MAX_RETRIES = 3;
|
|
253
|
+
_lastRefusalWarnAt = Number.NEGATIVE_INFINITY;
|
|
254
|
+
// ── Masking (see `../masking.ts`) ──────────────────────────────────────────
|
|
255
|
+
_mask;
|
|
256
|
+
_lastMaskWarnAt = Number.NEGATIVE_INFINITY;
|
|
257
|
+
_lastSlowMaskWarnAt = Number.NEGATIVE_INFINITY;
|
|
258
|
+
// Metrics
|
|
259
|
+
/** DEPRECATED flat total. Retained as the exact SUM of
|
|
260
|
+
* `droppedSpansByReason` so existing readers keep working (RULING §5
|
|
261
|
+
* back-compat — the same deprecate-and-alias shape this codebase used for
|
|
262
|
+
* `complete`->`settled` and `spans_flushed_total`). Prefer the labelled
|
|
263
|
+
* record: one integer cannot tell an under-provisioned queue from a dead
|
|
264
|
+
* gateway from a redeploy. */
|
|
265
|
+
droppedSpans = 0;
|
|
266
|
+
droppedSpansByReason = {
|
|
267
|
+
queue_full: 0,
|
|
268
|
+
transport_refused: 0,
|
|
269
|
+
shutdown_residue: 0
|
|
270
|
+
};
|
|
271
|
+
exportedSpans = 0;
|
|
272
|
+
/** Export ATTEMPTS, not a span count. */
|
|
273
|
+
failedExports = 0;
|
|
274
|
+
/**
|
|
275
|
+
* Fields whose mask callback threw and were replaced with
|
|
276
|
+
* `MASK_ERROR_MARKER`. A FIELD count, not a span count — one span can
|
|
277
|
+
* contribute several. Non-zero means those fields carry a marker instead of
|
|
278
|
+
* data: a customer-code bug, not a transport one.
|
|
279
|
+
*/
|
|
280
|
+
maskErrors = 0;
|
|
281
|
+
constructor(options) {
|
|
282
|
+
this._exporters = [...options.exporters];
|
|
283
|
+
const requestedBatchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
284
|
+
const clampedBatchSize = Math.max(1, Math.min(requestedBatchSize, 1e4));
|
|
285
|
+
if (clampedBatchSize !== requestedBatchSize) {
|
|
286
|
+
warn(
|
|
287
|
+
`batchSize=${requestedBatchSize} is outside the allowed range [1, 10000]; clamping to ${clampedBatchSize}`
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
this._batchSize = clampedBatchSize;
|
|
291
|
+
this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
|
|
292
|
+
this._maxQueueSize = options.maxQueueSize ?? 1e4;
|
|
293
|
+
this._debug = options.debug ?? false;
|
|
294
|
+
this._mask = options.mask;
|
|
295
|
+
}
|
|
296
|
+
start() {
|
|
297
|
+
if (this._started) return;
|
|
298
|
+
this._started = true;
|
|
299
|
+
this._timer = setInterval(() => {
|
|
300
|
+
void this._exportBatch();
|
|
301
|
+
}, this._batchTimeoutMs);
|
|
302
|
+
this._timer.unref();
|
|
303
|
+
this._beforeExitHandler = () => {
|
|
304
|
+
void this.shutdown();
|
|
305
|
+
};
|
|
306
|
+
process.once("beforeExit", this._beforeExitHandler);
|
|
307
|
+
}
|
|
308
|
+
/** Record `count` discarded spans under `reason`.
|
|
309
|
+
*
|
|
310
|
+
* `droppedSpans` is maintained as the exact sum of the labelled counters
|
|
311
|
+
* (RULING §5 back-compat), so the locked pins — which read the flat
|
|
312
|
+
* integer — stay meaningful. */
|
|
313
|
+
_recordDropped(reason, count = 1) {
|
|
314
|
+
this.droppedSpans += count;
|
|
315
|
+
this.droppedSpansByReason[reason] += count;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Run the customer mask over a batch, in place. Never throws.
|
|
319
|
+
*
|
|
320
|
+
* Failure semantics are ruled in `../masking.ts`: a field whose mask throws
|
|
321
|
+
* becomes `MASK_ERROR_MARKER` and the span is kept. The counter is per FIELD;
|
|
322
|
+
* both warnings are rate-limited to one per window so a mask that throws on
|
|
323
|
+
* every span cannot flood the customer's logs — the same shape as the
|
|
324
|
+
* transport-refusal warning above.
|
|
325
|
+
*/
|
|
326
|
+
_applyMask(batch) {
|
|
327
|
+
const mask = this._mask;
|
|
328
|
+
if (mask === void 0) return;
|
|
329
|
+
const { errors, elapsedMs } = applyMaskBatch(batch, mask);
|
|
330
|
+
const now = Date.now();
|
|
331
|
+
if (errors > 0) {
|
|
332
|
+
this.maskErrors += errors;
|
|
333
|
+
if (now - this._lastMaskWarnAt > MASK_WARN_WINDOW_MS) {
|
|
334
|
+
this._lastMaskWarnAt = now;
|
|
335
|
+
warnMaskErrors(errors, this.maskErrors);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (elapsedMs > MASK_BUDGET_MS_PER_SPAN * batch.length && now - this._lastSlowMaskWarnAt > MASK_WARN_WINDOW_MS) {
|
|
339
|
+
this._lastSlowMaskWarnAt = now;
|
|
340
|
+
warnMaskSlow(batch.length, elapsedMs);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Drain what we hold, or name what we could not (F-SDKDRAIN-001).
|
|
345
|
+
*
|
|
346
|
+
* Per RULING §4 (option E, hard-bounded) the drain loops until ONE of: the
|
|
347
|
+
* queue is empty; the deadline expires; or a full round completes with no
|
|
348
|
+
* exporter returning SUCCESS.
|
|
349
|
+
*
|
|
350
|
+
* ⚠ The `_flushing` handling is load-bearing, and `SDKDRAIN_JS_004` exists
|
|
351
|
+
* to catch its absence. `_exportBatch()` returns immediately when an export
|
|
352
|
+
* is already in flight (`:171`), so a loop that merely calls it again makes
|
|
353
|
+
* NO progress and abandons the queue exactly as before — measured at 900 of
|
|
354
|
+
* 1,000. We await a tick instead, the shape `flush()` already models.
|
|
355
|
+
*
|
|
356
|
+
* Anything still queued when the loop stops is COUNTED as `shutdown_residue`
|
|
357
|
+
* and announced with a WARNING. The warning is the primary signal, not the
|
|
358
|
+
* counter: a counter incremented inside `shutdown()` is written to memory
|
|
359
|
+
* about to be freed and has no reader (RULING §2 / §8.2).
|
|
360
|
+
*/
|
|
361
|
+
async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
|
|
362
|
+
if (!this._started) return;
|
|
363
|
+
this._started = false;
|
|
364
|
+
if (this._timer) {
|
|
365
|
+
clearInterval(this._timer);
|
|
366
|
+
this._timer = null;
|
|
367
|
+
}
|
|
368
|
+
if (this._beforeExitHandler) {
|
|
369
|
+
process.removeListener("beforeExit", this._beforeExitHandler);
|
|
370
|
+
this._beforeExitHandler = null;
|
|
371
|
+
}
|
|
372
|
+
const reserveMs = Math.min(SHUTDOWN_RESERVE_MS, timeoutMs / 2);
|
|
373
|
+
const drainDeadline = Date.now() + Math.max(0, timeoutMs - reserveMs);
|
|
374
|
+
while (this._queue.length > 0 || this._flushing) {
|
|
375
|
+
if (Date.now() >= drainDeadline) break;
|
|
376
|
+
const outcome = await this._exportBatch();
|
|
377
|
+
if (outcome === 3 /* Busy */) {
|
|
378
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
if (outcome !== 1 /* Delivered */) {
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
const residue = this._queue.length;
|
|
386
|
+
if (residue > 0) {
|
|
387
|
+
this._queue.length = 0;
|
|
388
|
+
this._recordDropped("shutdown_residue", residue);
|
|
389
|
+
warn(
|
|
390
|
+
`shutdown() gave up with ${residue} span(s) still queued (reason=shutdown_residue) \u2014 they were NOT delivered. The ${timeoutMs} ms shutdown budget expired or the transport stopped accepting. Raise the shutdown timeout, or your container's termination grace period, to lose less.`
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
for (const exporter of this._exporters) {
|
|
394
|
+
try {
|
|
395
|
+
await exporter.shutdown();
|
|
396
|
+
} catch (e) {
|
|
397
|
+
debug(`Error shutting down ${exporter.name}: ${e}`);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
this._retryCounts.clear();
|
|
401
|
+
debug(
|
|
402
|
+
`BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
onSpanEnd(span) {
|
|
406
|
+
if (!this._started) return;
|
|
407
|
+
if (this._queue.length >= this._maxQueueSize) {
|
|
408
|
+
this._recordDropped("queue_full");
|
|
409
|
+
if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
|
|
410
|
+
warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
|
|
411
|
+
}
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
this._queue.push(span);
|
|
415
|
+
if (this._queue.length >= this._batchSize) {
|
|
416
|
+
void this._exportBatch();
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Flush pending spans.
|
|
421
|
+
*
|
|
422
|
+
* @returns `true` only if everything queued at entry was DELIVERED.
|
|
423
|
+
*
|
|
424
|
+
* RULING §6. This used to answer a different question — "is the queue
|
|
425
|
+
* empty?" — and those two diverge in exactly one case: when spans left the
|
|
426
|
+
* queue WITHOUT reaching the transport. That case is the entire finding. A
|
|
427
|
+
* customer who calls `flush()` before exit and gets `true` has done
|
|
428
|
+
* everything right; silence lets them discover the problem, a false
|
|
429
|
+
* affirmative forecloses it.
|
|
430
|
+
*
|
|
431
|
+
* Returns `false` when (a) the deadline expires with spans still queued,
|
|
432
|
+
* (b) any span was discarded during the window — breaker refusal or retry
|
|
433
|
+
* exhaustion — or (c) it is called after `shutdown()` and the shutdown
|
|
434
|
+
* residue was non-zero.
|
|
435
|
+
*
|
|
436
|
+
* ⚠ (b) reads the flat total, so a concurrent `queue_full` drop of a span
|
|
437
|
+
* that arrived DURING the window also answers `false`. That is the
|
|
438
|
+
* conservative direction on purpose: a false negative costs a caller one
|
|
439
|
+
* more flush, a false positive is the defect being fixed.
|
|
440
|
+
*/
|
|
441
|
+
async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
|
|
442
|
+
if (!this._started) {
|
|
443
|
+
return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;
|
|
444
|
+
}
|
|
445
|
+
const start = Date.now();
|
|
446
|
+
const discardedAtEntry = this.droppedSpans;
|
|
447
|
+
while (this._queue.length > 0 || this._flushing) {
|
|
448
|
+
if (!this._flushing && this._queue.length > 0) {
|
|
449
|
+
await this._exportBatch();
|
|
450
|
+
} else {
|
|
451
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
452
|
+
}
|
|
453
|
+
if (Date.now() - start > timeoutMs) return false;
|
|
454
|
+
}
|
|
455
|
+
return this.droppedSpans === discardedAtEntry;
|
|
456
|
+
}
|
|
457
|
+
getMetrics() {
|
|
458
|
+
return {
|
|
459
|
+
exportedSpans: this.exportedSpans,
|
|
460
|
+
droppedSpans: this.droppedSpans,
|
|
461
|
+
droppedSpansByReason: { ...this.droppedSpansByReason },
|
|
462
|
+
failedExports: this.failedExports,
|
|
463
|
+
maskErrors: this.maskErrors,
|
|
464
|
+
queueSize: this._queue.length,
|
|
465
|
+
queueCapacity: this._maxQueueSize,
|
|
466
|
+
queueUtilization: this._queue.length / this._maxQueueSize
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
async _exportBatch() {
|
|
470
|
+
if (this._flushing) return 3 /* Busy */;
|
|
471
|
+
if (this._queue.length === 0) return 0 /* Empty */;
|
|
472
|
+
this._flushing = true;
|
|
473
|
+
try {
|
|
474
|
+
let take = 0;
|
|
475
|
+
let pairs = 0;
|
|
476
|
+
let nbytes = 0;
|
|
477
|
+
const limit = Math.min(this._batchSize, this._queue.length);
|
|
478
|
+
while (take < limit) {
|
|
479
|
+
const head = this._queue[take];
|
|
480
|
+
const spanPairs = spanAttrCount(head);
|
|
481
|
+
const spanBytes = spanBytesEstimate(head);
|
|
482
|
+
if (take > 0 && (pairs + spanPairs > MAX_ATTRIBUTE_PAIRS_PER_BATCH || nbytes + spanBytes > MAX_BATCH_BYTES)) {
|
|
483
|
+
break;
|
|
484
|
+
}
|
|
485
|
+
pairs += spanPairs;
|
|
486
|
+
nbytes += spanBytes;
|
|
487
|
+
take++;
|
|
488
|
+
}
|
|
489
|
+
const batch = this._queue.splice(0, take);
|
|
490
|
+
if (batch.length === 0) return 0 /* Empty */;
|
|
491
|
+
if (this._mask !== void 0) {
|
|
492
|
+
this._applyMask(batch);
|
|
493
|
+
}
|
|
494
|
+
debug(`Exporting batch of ${batch.length} spans`);
|
|
495
|
+
let batchExported = false;
|
|
496
|
+
for (const exporter of this._exporters) {
|
|
497
|
+
try {
|
|
498
|
+
const result = await exporter.export(batch);
|
|
499
|
+
if (result === "success" /* SUCCESS */) {
|
|
500
|
+
if (!batchExported) {
|
|
501
|
+
this.exportedSpans += batch.length;
|
|
502
|
+
batchExported = true;
|
|
503
|
+
for (const span of batch) {
|
|
504
|
+
this._retryCounts.delete(span.spanId);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
} else {
|
|
508
|
+
this.failedExports++;
|
|
509
|
+
}
|
|
510
|
+
} catch (e) {
|
|
511
|
+
this.failedExports++;
|
|
512
|
+
debug(`Export to ${exporter.name} failed: ${e}`);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
if (!batchExported) {
|
|
516
|
+
let dropped = 0;
|
|
517
|
+
const retryable = batch.filter((span) => {
|
|
518
|
+
const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
|
|
519
|
+
if (count > _BatchSpanProcessor.MAX_RETRIES) {
|
|
520
|
+
this._retryCounts.delete(span.spanId);
|
|
521
|
+
this._recordDropped("transport_refused");
|
|
522
|
+
dropped++;
|
|
523
|
+
return false;
|
|
524
|
+
}
|
|
525
|
+
this._retryCounts.set(span.spanId, count);
|
|
526
|
+
return true;
|
|
527
|
+
});
|
|
528
|
+
if (retryable.length > 0) {
|
|
529
|
+
this._queue.unshift(...retryable);
|
|
530
|
+
debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);
|
|
531
|
+
}
|
|
532
|
+
if (dropped > 0) {
|
|
533
|
+
const now = Date.now();
|
|
534
|
+
if (now - this._lastRefusalWarnAt > REFUSAL_WARN_WINDOW_MS) {
|
|
535
|
+
this._lastRefusalWarnAt = now;
|
|
536
|
+
warn(
|
|
537
|
+
`${dropped} span(s) DISCARDED (reason=transport_refused) after ${_BatchSpanProcessor.MAX_RETRIES} failed export attempts each \u2014 the endpoint is not accepting spans and the retry budget is spent. ${this.droppedSpansByReason.transport_refused} span(s) discarded this way so far in this process. This data is gone; check the apiKey and the endpoint.`
|
|
538
|
+
);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
return batchExported ? 1 /* Delivered */ : 2 /* Failed */;
|
|
543
|
+
} finally {
|
|
544
|
+
this._flushing = false;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
};
|
|
548
|
+
|
|
8
549
|
// src/config.ts
|
|
9
550
|
var DEFAULT_ENDPOINT = "https://app.risicare.ai";
|
|
10
551
|
function resolveConfig(config) {
|
|
@@ -24,11 +565,11 @@ function resolveConfig(config) {
|
|
|
24
565
|
const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
|
|
25
566
|
const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
|
|
26
567
|
const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
|
|
27
|
-
const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE,
|
|
568
|
+
const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE, DEFAULT_BATCH_SIZE);
|
|
28
569
|
const batchTimeoutMsRaw = config?.batchTimeoutMs ?? parseNumericEnv(env.RISICARE_BATCH_TIMEOUT_MS, 1e3);
|
|
29
570
|
const maxQueueSizeRaw = config?.maxQueueSize ?? parseNumericEnv(env.RISICARE_MAX_QUEUE_SIZE, 1e4);
|
|
30
571
|
const sampleRate = validateSampleRate(sampleRateRaw);
|
|
31
|
-
const batchSize = validatePositiveInt("batchSize", batchSizeRaw,
|
|
572
|
+
const batchSize = validatePositiveInt("batchSize", batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 1e4);
|
|
32
573
|
const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
|
|
33
574
|
const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
|
|
34
575
|
let enabled;
|
|
@@ -54,7 +595,9 @@ function resolveConfig(config) {
|
|
|
54
595
|
maxQueueSize,
|
|
55
596
|
debug: debug2,
|
|
56
597
|
compress,
|
|
57
|
-
metadata: config?.metadata ?? {}
|
|
598
|
+
metadata: config?.metadata ?? {},
|
|
599
|
+
// No env fallback — see the field's note on RisicareConfig.
|
|
600
|
+
mask: config?.mask
|
|
58
601
|
};
|
|
59
602
|
}
|
|
60
603
|
function parseBool(value, defaultValue) {
|
|
@@ -465,47 +1008,6 @@ function shouldSample(traceId, sampleRate) {
|
|
|
465
1008
|
return hash / 4294967295 < sampleRate;
|
|
466
1009
|
}
|
|
467
1010
|
|
|
468
|
-
// src/globals.ts
|
|
469
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
470
|
-
var G = globalThis;
|
|
471
|
-
var PREFIX = "__risicare_";
|
|
472
|
-
function getClient() {
|
|
473
|
-
return G[PREFIX + "client"];
|
|
474
|
-
}
|
|
475
|
-
function setClient(client) {
|
|
476
|
-
G[PREFIX + "client"] = client;
|
|
477
|
-
}
|
|
478
|
-
function getTracer() {
|
|
479
|
-
return G[PREFIX + "tracer"];
|
|
480
|
-
}
|
|
481
|
-
function setTracer(tracer) {
|
|
482
|
-
G[PREFIX + "tracer"] = tracer;
|
|
483
|
-
}
|
|
484
|
-
function getContextStorage() {
|
|
485
|
-
if (!G[PREFIX + "ctx"]) {
|
|
486
|
-
G[PREFIX + "ctx"] = new AsyncLocalStorage();
|
|
487
|
-
}
|
|
488
|
-
return G[PREFIX + "ctx"];
|
|
489
|
-
}
|
|
490
|
-
function getRegistry() {
|
|
491
|
-
if (!G[PREFIX + "registry"]) {
|
|
492
|
-
G[PREFIX + "registry"] = /* @__PURE__ */ new Map();
|
|
493
|
-
}
|
|
494
|
-
return G[PREFIX + "registry"];
|
|
495
|
-
}
|
|
496
|
-
function getOpCount() {
|
|
497
|
-
return G[PREFIX + "opcount"] ?? 0;
|
|
498
|
-
}
|
|
499
|
-
function setOpCount(n) {
|
|
500
|
-
G[PREFIX + "opcount"] = n;
|
|
501
|
-
}
|
|
502
|
-
function getDebug() {
|
|
503
|
-
return G[PREFIX + "debug"] ?? false;
|
|
504
|
-
}
|
|
505
|
-
function setDebugFlag(enabled) {
|
|
506
|
-
G[PREFIX + "debug"] = enabled;
|
|
507
|
-
}
|
|
508
|
-
|
|
509
1011
|
// src/context/storage.ts
|
|
510
1012
|
function storage() {
|
|
511
1013
|
return getContextStorage();
|
|
@@ -704,180 +1206,8 @@ var Tracer = class {
|
|
|
704
1206
|
}
|
|
705
1207
|
};
|
|
706
1208
|
|
|
707
|
-
// src/utils/log.ts
|
|
708
|
-
function setDebug(enabled) {
|
|
709
|
-
setDebugFlag(enabled);
|
|
710
|
-
}
|
|
711
|
-
function debug(msg) {
|
|
712
|
-
if (getDebug()) {
|
|
713
|
-
process.stderr.write(`[risicare] ${msg}
|
|
714
|
-
`);
|
|
715
|
-
}
|
|
716
|
-
}
|
|
717
|
-
function warn(msg) {
|
|
718
|
-
process.stderr.write(`[risicare] WARNING: ${msg}
|
|
719
|
-
`);
|
|
720
|
-
}
|
|
721
|
-
|
|
722
|
-
// src/exporters/batch.ts
|
|
723
|
-
var BatchSpanProcessor = class _BatchSpanProcessor {
|
|
724
|
-
_exporters;
|
|
725
|
-
_batchSize;
|
|
726
|
-
_batchTimeoutMs;
|
|
727
|
-
_maxQueueSize;
|
|
728
|
-
_debug;
|
|
729
|
-
_queue = [];
|
|
730
|
-
_timer = null;
|
|
731
|
-
_started = false;
|
|
732
|
-
_flushing = false;
|
|
733
|
-
_beforeExitHandler = null;
|
|
734
|
-
// Retry tracking for failed batches (Audit #5)
|
|
735
|
-
_retryCounts = /* @__PURE__ */ new Map();
|
|
736
|
-
static MAX_RETRIES = 3;
|
|
737
|
-
// Metrics
|
|
738
|
-
droppedSpans = 0;
|
|
739
|
-
exportedSpans = 0;
|
|
740
|
-
failedExports = 0;
|
|
741
|
-
constructor(options) {
|
|
742
|
-
this._exporters = [...options.exporters];
|
|
743
|
-
const requestedBatchSize = options.batchSize ?? 100;
|
|
744
|
-
const clampedBatchSize = Math.max(1, Math.min(requestedBatchSize, 1e4));
|
|
745
|
-
if (clampedBatchSize !== requestedBatchSize) {
|
|
746
|
-
warn(
|
|
747
|
-
`batchSize=${requestedBatchSize} is outside the allowed range [1, 10000]; clamping to ${clampedBatchSize}`
|
|
748
|
-
);
|
|
749
|
-
}
|
|
750
|
-
this._batchSize = clampedBatchSize;
|
|
751
|
-
this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
|
|
752
|
-
this._maxQueueSize = options.maxQueueSize ?? 1e4;
|
|
753
|
-
this._debug = options.debug ?? false;
|
|
754
|
-
}
|
|
755
|
-
start() {
|
|
756
|
-
if (this._started) return;
|
|
757
|
-
this._started = true;
|
|
758
|
-
this._timer = setInterval(() => {
|
|
759
|
-
void this._exportBatch();
|
|
760
|
-
}, this._batchTimeoutMs);
|
|
761
|
-
this._timer.unref();
|
|
762
|
-
this._beforeExitHandler = () => {
|
|
763
|
-
void this.shutdown();
|
|
764
|
-
};
|
|
765
|
-
process.once("beforeExit", this._beforeExitHandler);
|
|
766
|
-
}
|
|
767
|
-
async shutdown(timeoutMs = 5e3) {
|
|
768
|
-
if (!this._started) return;
|
|
769
|
-
this._started = false;
|
|
770
|
-
if (this._timer) {
|
|
771
|
-
clearInterval(this._timer);
|
|
772
|
-
this._timer = null;
|
|
773
|
-
}
|
|
774
|
-
if (this._beforeExitHandler) {
|
|
775
|
-
process.removeListener("beforeExit", this._beforeExitHandler);
|
|
776
|
-
this._beforeExitHandler = null;
|
|
777
|
-
}
|
|
778
|
-
const flushPromise = this._exportBatch();
|
|
779
|
-
const timeoutPromise = new Promise((resolve) => setTimeout(resolve, timeoutMs));
|
|
780
|
-
await Promise.race([flushPromise, timeoutPromise]);
|
|
781
|
-
for (const exporter of this._exporters) {
|
|
782
|
-
try {
|
|
783
|
-
await exporter.shutdown();
|
|
784
|
-
} catch (e) {
|
|
785
|
-
debug(`Error shutting down ${exporter.name}: ${e}`);
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
this._retryCounts.clear();
|
|
789
|
-
debug(
|
|
790
|
-
`BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`
|
|
791
|
-
);
|
|
792
|
-
}
|
|
793
|
-
onSpanEnd(span) {
|
|
794
|
-
if (!this._started) return;
|
|
795
|
-
if (this._queue.length >= this._maxQueueSize) {
|
|
796
|
-
this.droppedSpans++;
|
|
797
|
-
if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
|
|
798
|
-
warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
|
|
799
|
-
}
|
|
800
|
-
return;
|
|
801
|
-
}
|
|
802
|
-
this._queue.push(span);
|
|
803
|
-
if (this._queue.length >= this._batchSize) {
|
|
804
|
-
void this._exportBatch();
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
async flush(timeoutMs = 5e3) {
|
|
808
|
-
if (!this._started) return true;
|
|
809
|
-
const start = Date.now();
|
|
810
|
-
while (this._queue.length > 0 || this._flushing) {
|
|
811
|
-
if (!this._flushing && this._queue.length > 0) {
|
|
812
|
-
await this._exportBatch();
|
|
813
|
-
} else {
|
|
814
|
-
await new Promise((r) => setTimeout(r, 1));
|
|
815
|
-
}
|
|
816
|
-
if (Date.now() - start > timeoutMs) return false;
|
|
817
|
-
}
|
|
818
|
-
return true;
|
|
819
|
-
}
|
|
820
|
-
getMetrics() {
|
|
821
|
-
return {
|
|
822
|
-
exportedSpans: this.exportedSpans,
|
|
823
|
-
droppedSpans: this.droppedSpans,
|
|
824
|
-
failedExports: this.failedExports,
|
|
825
|
-
queueSize: this._queue.length,
|
|
826
|
-
queueCapacity: this._maxQueueSize,
|
|
827
|
-
queueUtilization: this._queue.length / this._maxQueueSize
|
|
828
|
-
};
|
|
829
|
-
}
|
|
830
|
-
async _exportBatch() {
|
|
831
|
-
if (this._flushing || this._queue.length === 0) return;
|
|
832
|
-
this._flushing = true;
|
|
833
|
-
try {
|
|
834
|
-
const batch = this._queue.splice(0, this._batchSize);
|
|
835
|
-
if (batch.length === 0) return;
|
|
836
|
-
debug(`Exporting batch of ${batch.length} spans`);
|
|
837
|
-
let batchExported = false;
|
|
838
|
-
for (const exporter of this._exporters) {
|
|
839
|
-
try {
|
|
840
|
-
const result = await exporter.export(batch);
|
|
841
|
-
if (result === "success" /* SUCCESS */) {
|
|
842
|
-
if (!batchExported) {
|
|
843
|
-
this.exportedSpans += batch.length;
|
|
844
|
-
batchExported = true;
|
|
845
|
-
for (const span of batch) {
|
|
846
|
-
this._retryCounts.delete(span.spanId);
|
|
847
|
-
}
|
|
848
|
-
}
|
|
849
|
-
} else {
|
|
850
|
-
this.failedExports++;
|
|
851
|
-
}
|
|
852
|
-
} catch (e) {
|
|
853
|
-
this.failedExports++;
|
|
854
|
-
debug(`Export to ${exporter.name} failed: ${e}`);
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
if (!batchExported) {
|
|
858
|
-
const retryable = batch.filter((span) => {
|
|
859
|
-
const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
|
|
860
|
-
if (count > _BatchSpanProcessor.MAX_RETRIES) {
|
|
861
|
-
this._retryCounts.delete(span.spanId);
|
|
862
|
-
this.droppedSpans++;
|
|
863
|
-
return false;
|
|
864
|
-
}
|
|
865
|
-
this._retryCounts.set(span.spanId, count);
|
|
866
|
-
return true;
|
|
867
|
-
});
|
|
868
|
-
if (retryable.length > 0) {
|
|
869
|
-
this._queue.unshift(...retryable);
|
|
870
|
-
debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);
|
|
871
|
-
}
|
|
872
|
-
}
|
|
873
|
-
} finally {
|
|
874
|
-
this._flushing = false;
|
|
875
|
-
}
|
|
876
|
-
}
|
|
877
|
-
};
|
|
878
|
-
|
|
879
1209
|
// src/version.ts
|
|
880
|
-
var SDK_VERSION = "0.
|
|
1210
|
+
var SDK_VERSION = "0.5.0";
|
|
881
1211
|
|
|
882
1212
|
// src/exporters/http.ts
|
|
883
1213
|
var HttpExporter = class {
|
|
@@ -2301,10 +2631,20 @@ function shutdownFixRuntime() {
|
|
|
2301
2631
|
}
|
|
2302
2632
|
|
|
2303
2633
|
// src/client.ts
|
|
2634
|
+
var TERMINATING_SIGNALS = [
|
|
2635
|
+
["SIGTERM", 15],
|
|
2636
|
+
["SIGINT", 2]
|
|
2637
|
+
];
|
|
2638
|
+
var BACKSTOP_MARGIN_MS = 500;
|
|
2639
|
+
var _finalMetrics;
|
|
2304
2640
|
var RisicareClient = class {
|
|
2305
2641
|
config;
|
|
2306
2642
|
processor;
|
|
2307
2643
|
tracer;
|
|
2644
|
+
/** RULING §5. The signal path does NOT clear the global client, so without
|
|
2645
|
+
* this flag `getMetrics()` would keep reporting `"running"` over a processor
|
|
2646
|
+
* that has already been torn down. */
|
|
2647
|
+
isShutdown = false;
|
|
2308
2648
|
_shutdownPromise;
|
|
2309
2649
|
_shutdownHandlers = [];
|
|
2310
2650
|
constructor(config) {
|
|
@@ -2324,14 +2664,27 @@ var RisicareClient = class {
|
|
|
2324
2664
|
compress: this.config.compress
|
|
2325
2665
|
});
|
|
2326
2666
|
} else {
|
|
2327
|
-
exporter =
|
|
2667
|
+
exporter = void 0;
|
|
2668
|
+
if (this.config.enabled) {
|
|
2669
|
+
try {
|
|
2670
|
+
console.warn(
|
|
2671
|
+
`[risicare] tracing is enabled but NO API key is configured \u2014 spans are created and then DROPPED, not sent to ${this.config.endpoint}. Pass apiKey to init() (or set the RISICARE_API_KEY env var). Span data is NOT written to the console: it would be unredacted. Pass debug:true if you want console output for local development.`
|
|
2672
|
+
);
|
|
2673
|
+
} catch {
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2328
2676
|
}
|
|
2329
2677
|
this.processor = new BatchSpanProcessor({
|
|
2330
|
-
exporters: [exporter],
|
|
2678
|
+
exporters: exporter ? [exporter] : [],
|
|
2331
2679
|
batchSize: this.config.batchSize,
|
|
2332
2680
|
batchTimeoutMs: this.config.batchTimeoutMs,
|
|
2333
2681
|
maxQueueSize: this.config.maxQueueSize,
|
|
2334
|
-
debug: this.config.debug
|
|
2682
|
+
debug: this.config.debug,
|
|
2683
|
+
// The processor is the ONE choke point every exporter is behind. Masking
|
|
2684
|
+
// anywhere downstream (in the HTTP exporter, say) would leave a hole for
|
|
2685
|
+
// any other exporter; masking upstream would put customer code on the
|
|
2686
|
+
// span-end call path.
|
|
2687
|
+
mask: this.config.mask
|
|
2335
2688
|
});
|
|
2336
2689
|
this.tracer = new Tracer({
|
|
2337
2690
|
onSpanEnd: (span) => this.processor.onSpanEnd(span),
|
|
@@ -2385,21 +2738,82 @@ var RisicareClient = class {
|
|
|
2385
2738
|
}
|
|
2386
2739
|
this._shutdownHandlers = [];
|
|
2387
2740
|
await this.processor.shutdown();
|
|
2741
|
+
this.isShutdown = true;
|
|
2742
|
+
_finalMetrics = this.processor.getMetrics();
|
|
2388
2743
|
}
|
|
2744
|
+
/**
|
|
2745
|
+
* Flush pending spans.
|
|
2746
|
+
*
|
|
2747
|
+
* @returns `true` only if everything queued at entry was DELIVERED.
|
|
2748
|
+
*
|
|
2749
|
+
* RULING §6: this used to discard the processor's boolean and return
|
|
2750
|
+
* `Promise<void>`, which resolves without throwing and reads to a caller
|
|
2751
|
+
* exactly like success. A discarded answer is not meaningfully better than a
|
|
2752
|
+
* false one — both leave the customer unable to tell *drained* from
|
|
2753
|
+
* *discarded*.
|
|
2754
|
+
*/
|
|
2389
2755
|
async flush() {
|
|
2390
|
-
|
|
2756
|
+
return this.processor.flush();
|
|
2391
2757
|
}
|
|
2758
|
+
/**
|
|
2759
|
+
* SDK-RELEASE-RULING.md §3 — who decides whether the process dies.
|
|
2760
|
+
*
|
|
2761
|
+
* The contract, and it is the same one the Python SDK now satisfies:
|
|
2762
|
+
*
|
|
2763
|
+
* the SDK's signal handler never CHANGES whether the signal
|
|
2764
|
+
* terminates the process.
|
|
2765
|
+
*
|
|
2766
|
+
* Registering ANY listener for SIGTERM/SIGINT displaces Node's default
|
|
2767
|
+
* terminate. Before this, the SDK registered one unconditionally, and on the
|
|
2768
|
+
* success path `clearTimeout` removed the 5 s `process.exit(1)` backstop —
|
|
2769
|
+
* so a JS app with a live event loop drained, cleared its own only exit, and
|
|
2770
|
+
* **ran forever**. The orchestrator waited out the whole grace period and
|
|
2771
|
+
* SIGKILLed, which exits **137** and reads as OOM-killed in every dashboard.
|
|
2772
|
+
* Measured >25 s alive on both 0.5.0 and a clean-rebuilt 0.4.2, so this is
|
|
2773
|
+
* PRE-EXISTING (`F-SDKJSEXIT-001`), not a regression of the data-loss fix.
|
|
2774
|
+
*
|
|
2775
|
+
* The rule splits on one question — did the signal already have an owner?
|
|
2776
|
+
*
|
|
2777
|
+
* * **No prior listener.** Node's default was termination and OUR
|
|
2778
|
+
* registration displaced it. We owe the process that death.
|
|
2779
|
+
* * **A prior listener exists.** The application took ownership before the
|
|
2780
|
+
* SDK loaded. We drain and RETURN; termination was never ours to decide,
|
|
2781
|
+
* and forcing it would cut off the app's own graceful shutdown.
|
|
2782
|
+
*
|
|
2783
|
+
* ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and
|
|
2784
|
+
* carries no termination the SDK could displace — the loop has already
|
|
2785
|
+
* drained and the process is leaving on its own.
|
|
2786
|
+
*/
|
|
2392
2787
|
_registerShutdownHooks() {
|
|
2393
|
-
const
|
|
2394
|
-
const timeout = setTimeout(() => process.exit(1), 5e3);
|
|
2395
|
-
timeout.unref();
|
|
2788
|
+
const onBeforeExit = () => {
|
|
2396
2789
|
this.shutdown().catch(() => {
|
|
2397
|
-
})
|
|
2790
|
+
});
|
|
2398
2791
|
};
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2792
|
+
process.once("beforeExit", onBeforeExit);
|
|
2793
|
+
this._shutdownHandlers.push({ signal: "beforeExit", handler: onBeforeExit });
|
|
2794
|
+
for (const [signal, signum] of TERMINATING_SIGNALS) {
|
|
2795
|
+
const weDisplacedDefault = process.listenerCount(signal) === 0;
|
|
2796
|
+
const handler = () => {
|
|
2797
|
+
const backstop = setTimeout(
|
|
2798
|
+
() => process.exit(128 + signum),
|
|
2799
|
+
SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
|
|
2800
|
+
);
|
|
2801
|
+
backstop.unref();
|
|
2802
|
+
this.shutdown().catch(() => {
|
|
2803
|
+
}).finally(() => {
|
|
2804
|
+
clearTimeout(backstop);
|
|
2805
|
+
if (!weDisplacedDefault) return;
|
|
2806
|
+
try {
|
|
2807
|
+
process.kill(process.pid, signal);
|
|
2808
|
+
} catch {
|
|
2809
|
+
process.exit(128 + signum);
|
|
2810
|
+
}
|
|
2811
|
+
const failsafe = setTimeout(() => process.exit(128 + signum), 100);
|
|
2812
|
+
failsafe.unref();
|
|
2813
|
+
});
|
|
2814
|
+
};
|
|
2815
|
+
process.once(signal, handler);
|
|
2816
|
+
this._shutdownHandlers.push({ signal, handler });
|
|
2403
2817
|
}
|
|
2404
2818
|
}
|
|
2405
2819
|
};
|
|
@@ -2436,6 +2850,7 @@ function init(config) {
|
|
|
2436
2850
|
}
|
|
2437
2851
|
return;
|
|
2438
2852
|
}
|
|
2853
|
+
_finalMetrics = void 0;
|
|
2439
2854
|
const client = new RisicareClient(config);
|
|
2440
2855
|
setClient(client);
|
|
2441
2856
|
setTracer(client.tracer);
|
|
@@ -2453,8 +2868,8 @@ async function shutdown() {
|
|
|
2453
2868
|
}
|
|
2454
2869
|
async function flush() {
|
|
2455
2870
|
const client = getClient();
|
|
2456
|
-
if (!client) return;
|
|
2457
|
-
|
|
2871
|
+
if (!client) return true;
|
|
2872
|
+
return client.flush();
|
|
2458
2873
|
}
|
|
2459
2874
|
function enable() {
|
|
2460
2875
|
const client = getClient();
|
|
@@ -2477,13 +2892,29 @@ function getTraceContent() {
|
|
|
2477
2892
|
}
|
|
2478
2893
|
function getMetrics() {
|
|
2479
2894
|
const client = getClient();
|
|
2480
|
-
|
|
2895
|
+
if (client && !client.isShutdown) {
|
|
2896
|
+
return { ...client.processor.getMetrics(), sdkState: "running" };
|
|
2897
|
+
}
|
|
2898
|
+
if (_finalMetrics) {
|
|
2899
|
+
return {
|
|
2900
|
+
..._finalMetrics,
|
|
2901
|
+
droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },
|
|
2902
|
+
sdkState: "shutdown"
|
|
2903
|
+
};
|
|
2904
|
+
}
|
|
2905
|
+
return {
|
|
2481
2906
|
exportedSpans: 0,
|
|
2482
2907
|
droppedSpans: 0,
|
|
2908
|
+
droppedSpansByReason: {
|
|
2909
|
+
queue_full: 0,
|
|
2910
|
+
transport_refused: 0,
|
|
2911
|
+
shutdown_residue: 0
|
|
2912
|
+
},
|
|
2483
2913
|
failedExports: 0,
|
|
2484
2914
|
queueSize: 0,
|
|
2485
2915
|
queueCapacity: 0,
|
|
2486
|
-
queueUtilization: 0
|
|
2916
|
+
queueUtilization: 0,
|
|
2917
|
+
sdkState: "uninitialised"
|
|
2487
2918
|
};
|
|
2488
2919
|
}
|
|
2489
2920
|
var _ERROR_DEDUP_TTL_MS = 5 * 60 * 1e3;
|
|
@@ -2491,7 +2922,6 @@ var _ERROR_DEDUP_MAX = 1e3;
|
|
|
2491
2922
|
var _recentErrors = /* @__PURE__ */ new Map();
|
|
2492
2923
|
function _errorFingerprint(err) {
|
|
2493
2924
|
const raw = `${err.constructor?.name ?? "Error"}:${String(err.message ?? "").slice(0, 200)}`;
|
|
2494
|
-
const { createHash: createHash2 } = __require("crypto");
|
|
2495
2925
|
return createHash2("sha256").update(raw).digest("hex").slice(0, 16);
|
|
2496
2926
|
}
|
|
2497
2927
|
function _isDuplicateError(fingerprint) {
|
|
@@ -2550,13 +2980,17 @@ function score(traceId, name, value, options) {
|
|
|
2550
2980
|
if (!client?.enabled || !client.config.apiKey) return;
|
|
2551
2981
|
const endpoint = client.config.endpoint.replace(/\/$/, "");
|
|
2552
2982
|
const url = `${endpoint}/api/v1/scores`;
|
|
2983
|
+
let comment = options?.comment;
|
|
2984
|
+
if (comment !== void 0 && client.config.mask) {
|
|
2985
|
+
comment = maskText(client.config.mask, SCORE_COMMENT_KEY, comment);
|
|
2986
|
+
}
|
|
2553
2987
|
const body = JSON.stringify({
|
|
2554
2988
|
trace_id: traceId,
|
|
2555
2989
|
name,
|
|
2556
2990
|
score: value,
|
|
2557
2991
|
source: "sdk",
|
|
2558
2992
|
...options?.spanId && { span_id: options.spanId },
|
|
2559
|
-
...
|
|
2993
|
+
...comment && { comment }
|
|
2560
2994
|
});
|
|
2561
2995
|
fetch(url, {
|
|
2562
2996
|
method: "POST",
|
|
@@ -3699,6 +4133,7 @@ export {
|
|
|
3699
4133
|
AgentRole,
|
|
3700
4134
|
DEFAULT_TIMESTAMP_TOLERANCE_S,
|
|
3701
4135
|
GuardRejectedError,
|
|
4136
|
+
MASK_ERROR_MARKER,
|
|
3702
4137
|
MessageType,
|
|
3703
4138
|
RisicareCallbackHandler,
|
|
3704
4139
|
RisicareLlamaIndexHandler,
|