risicare 0.9.2 → 0.11.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/CHANGELOG.md +254 -0
- package/README.md +194 -58
- package/dist/frameworks/instructor.cjs +383 -117
- package/dist/frameworks/instructor.cjs.map +1 -1
- package/dist/frameworks/instructor.js +383 -117
- package/dist/frameworks/instructor.js.map +1 -1
- package/dist/frameworks/langchain.cjs +396 -130
- package/dist/frameworks/langchain.cjs.map +1 -1
- package/dist/frameworks/langchain.js +396 -130
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/frameworks/langgraph.cjs +396 -130
- package/dist/frameworks/langgraph.cjs.map +1 -1
- package/dist/frameworks/langgraph.js +396 -130
- package/dist/frameworks/langgraph.js.map +1 -1
- package/dist/frameworks/llamaindex.cjs +396 -130
- package/dist/frameworks/llamaindex.cjs.map +1 -1
- package/dist/frameworks/llamaindex.js +396 -130
- package/dist/frameworks/llamaindex.js.map +1 -1
- package/dist/index.cjs +1136 -240
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +151 -26
- package/dist/index.d.ts +151 -26
- package/dist/index.js +1132 -240
- package/dist/index.js.map +1 -1
- package/dist/providers/anthropic/index.cjs +467 -137
- package/dist/providers/anthropic/index.cjs.map +1 -1
- package/dist/providers/anthropic/index.js +467 -137
- package/dist/providers/anthropic/index.js.map +1 -1
- package/dist/providers/bedrock/index.cjs +409 -128
- package/dist/providers/bedrock/index.cjs.map +1 -1
- package/dist/providers/bedrock/index.js +409 -128
- package/dist/providers/bedrock/index.js.map +1 -1
- package/dist/providers/cerebras/index.cjs +414 -133
- package/dist/providers/cerebras/index.cjs.map +1 -1
- package/dist/providers/cerebras/index.js +414 -133
- package/dist/providers/cerebras/index.js.map +1 -1
- package/dist/providers/cohere/index.cjs +414 -133
- package/dist/providers/cohere/index.cjs.map +1 -1
- package/dist/providers/cohere/index.js +414 -133
- package/dist/providers/cohere/index.js.map +1 -1
- package/dist/providers/google/index.cjs +414 -133
- package/dist/providers/google/index.cjs.map +1 -1
- package/dist/providers/google/index.js +414 -133
- package/dist/providers/google/index.js.map +1 -1
- package/dist/providers/groq/index.cjs +414 -133
- package/dist/providers/groq/index.cjs.map +1 -1
- package/dist/providers/groq/index.js +414 -133
- package/dist/providers/groq/index.js.map +1 -1
- package/dist/providers/huggingface/index.cjs +414 -133
- package/dist/providers/huggingface/index.cjs.map +1 -1
- package/dist/providers/huggingface/index.js +414 -133
- package/dist/providers/huggingface/index.js.map +1 -1
- package/dist/providers/mistral/index.cjs +414 -133
- package/dist/providers/mistral/index.cjs.map +1 -1
- package/dist/providers/mistral/index.js +414 -133
- package/dist/providers/mistral/index.js.map +1 -1
- package/dist/providers/ollama/index.cjs +414 -133
- package/dist/providers/ollama/index.cjs.map +1 -1
- package/dist/providers/ollama/index.js +414 -133
- package/dist/providers/ollama/index.js.map +1 -1
- package/dist/providers/openai/index.cjs +452 -135
- package/dist/providers/openai/index.cjs.map +1 -1
- package/dist/providers/openai/index.js +452 -135
- package/dist/providers/openai/index.js.map +1 -1
- package/dist/providers/together/index.cjs +414 -133
- package/dist/providers/together/index.cjs.map +1 -1
- package/dist/providers/together/index.js +414 -133
- package/dist/providers/together/index.js.map +1 -1
- package/dist/providers/vercel-ai/index.cjs +398 -132
- package/dist/providers/vercel-ai/index.cjs.map +1 -1
- package/dist/providers/vercel-ai/index.js +398 -132
- package/dist/providers/vercel-ai/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -37,6 +37,35 @@ module.exports = __toCommonJS(instructor_exports);
|
|
|
37
37
|
// src/client.ts
|
|
38
38
|
var import_node_crypto3 = require("crypto");
|
|
39
39
|
|
|
40
|
+
// src/exporters/retry.ts
|
|
41
|
+
var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
|
|
42
|
+
var TOO_LARGE_STATUS = 413;
|
|
43
|
+
var RETRY_BACKOFF_BASE_S = 1;
|
|
44
|
+
var RETRY_BACKOFF_CAP_S = 30;
|
|
45
|
+
var DEFAULT_RETRY_HORIZON_S = 300;
|
|
46
|
+
var DEFAULT_SHUTDOWN_TIMEOUT_S = 10;
|
|
47
|
+
var RETRY_WARN_AFTER_ATTEMPTS = 3;
|
|
48
|
+
var jitter = { fraction: () => Math.random() };
|
|
49
|
+
function backoffDelayS(retryNumber, fraction) {
|
|
50
|
+
const exponent = Math.min(Math.max(retryNumber, 0), 62);
|
|
51
|
+
const ceiling = Math.min(RETRY_BACKOFF_CAP_S, RETRY_BACKOFF_BASE_S * 2 ** exponent);
|
|
52
|
+
return Math.min(Math.max(fraction, 0), 1) * ceiling;
|
|
53
|
+
}
|
|
54
|
+
var SECONDS = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
|
|
55
|
+
function parseRetryAfterS(value, nowMs = Date.now()) {
|
|
56
|
+
if (value === null || value === void 0) return null;
|
|
57
|
+
const text = String(value).trim();
|
|
58
|
+
if (text === "") return null;
|
|
59
|
+
if (SECONDS.test(text)) {
|
|
60
|
+
const seconds = Number(text);
|
|
61
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
|
|
62
|
+
}
|
|
63
|
+
if (!/[A-Za-z]/.test(text)) return null;
|
|
64
|
+
const when = Date.parse(text);
|
|
65
|
+
if (!Number.isFinite(when)) return null;
|
|
66
|
+
return Math.max(0, (when - nowMs) / 1e3);
|
|
67
|
+
}
|
|
68
|
+
|
|
40
69
|
// src/globals.ts
|
|
41
70
|
var import_node_async_hooks = require("async_hooks");
|
|
42
71
|
var G = globalThis;
|
|
@@ -131,7 +160,53 @@ function hasCredentials(url) {
|
|
|
131
160
|
}
|
|
132
161
|
}
|
|
133
162
|
|
|
163
|
+
// src/masking.ts
|
|
164
|
+
var CONTENT_IN_JSON_OBJECT = /* @__PURE__ */ new Map([
|
|
165
|
+
[
|
|
166
|
+
"llm.invocation_parameters",
|
|
167
|
+
/* @__PURE__ */ new Set([
|
|
168
|
+
"additionalinstructions",
|
|
169
|
+
// OpenAI assistants run
|
|
170
|
+
"chathistory",
|
|
171
|
+
// Cohere
|
|
172
|
+
"contents",
|
|
173
|
+
// Gemini
|
|
174
|
+
"documents",
|
|
175
|
+
// Cohere RAG
|
|
176
|
+
"functions",
|
|
177
|
+
"input",
|
|
178
|
+
"inputtext",
|
|
179
|
+
// Bedrock Titan
|
|
180
|
+
"instructions",
|
|
181
|
+
"message",
|
|
182
|
+
// Cohere
|
|
183
|
+
"messages",
|
|
184
|
+
"preamble",
|
|
185
|
+
// Cohere
|
|
186
|
+
"prediction",
|
|
187
|
+
// OpenAI predicted output
|
|
188
|
+
"prompt",
|
|
189
|
+
"system",
|
|
190
|
+
// Anthropic
|
|
191
|
+
"systeminstruction",
|
|
192
|
+
// Gemini
|
|
193
|
+
"texts",
|
|
194
|
+
// Cohere embed
|
|
195
|
+
"toolconfig",
|
|
196
|
+
// Gemini
|
|
197
|
+
"tools"
|
|
198
|
+
])
|
|
199
|
+
]
|
|
200
|
+
]);
|
|
201
|
+
var VALUE_RULE_PREFIXES = new Set(
|
|
202
|
+
[...CONTENT_IN_JSON_OBJECT.keys()].flatMap((key) => {
|
|
203
|
+
const segments = key.split(".");
|
|
204
|
+
return segments.slice(1).map((_, i) => segments.slice(0, i + 1).join("."));
|
|
205
|
+
})
|
|
206
|
+
);
|
|
207
|
+
|
|
134
208
|
// src/exporters/batch.ts
|
|
209
|
+
var SHUTDOWN_BUDGET_MS = DEFAULT_SHUTDOWN_TIMEOUT_S * 1e3;
|
|
135
210
|
var MAX_TIMEOUT_MS = 2 ** 31 - 1;
|
|
136
211
|
var MAX_BATCH_BYTES = 8 * 1024 * 1024;
|
|
137
212
|
var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
|
|
@@ -267,7 +342,7 @@ var SUPPLEMENTAL_RULES = [
|
|
|
267
342
|
];
|
|
268
343
|
|
|
269
344
|
// src/version.ts
|
|
270
|
-
var SDK_VERSION = "0.
|
|
345
|
+
var SDK_VERSION = "0.11.0";
|
|
271
346
|
|
|
272
347
|
// src/exporters/quota.ts
|
|
273
348
|
var QUOTA_REASON = "monthly_quota_exceeded";
|
|
@@ -375,12 +450,18 @@ var QuotaPause = class {
|
|
|
375
450
|
|
|
376
451
|
// src/exporters/http.ts
|
|
377
452
|
var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
|
|
378
|
-
var RETRY_AFTER_CEILING_MS = 1e4;
|
|
379
|
-
var REFUSAL_BACKOFF_BASE_MS = 1e3;
|
|
380
|
-
var REFUSAL_NO_HINT = -1;
|
|
381
453
|
var MISROUTE_WARN_WINDOW_MS = 3e5;
|
|
382
454
|
var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
|
|
383
455
|
var FAILURE_WARN_WINDOW_MS = 3e5;
|
|
456
|
+
var MAX_TIMER_MS = 2 ** 31 - 1;
|
|
457
|
+
function validHorizonS(value) {
|
|
458
|
+
if (value === void 0) return DEFAULT_RETRY_HORIZON_S;
|
|
459
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
|
|
460
|
+
warn(
|
|
461
|
+
`Risicare: retryHorizonS=${String(value)} is not a finite number of 0 or more; using the default, ${DEFAULT_RETRY_HORIZON_S} s.`
|
|
462
|
+
);
|
|
463
|
+
return DEFAULT_RETRY_HORIZON_S;
|
|
464
|
+
}
|
|
384
465
|
var HttpExporter = class {
|
|
385
466
|
name = "http";
|
|
386
467
|
_endpoint;
|
|
@@ -390,20 +471,28 @@ var HttpExporter = class {
|
|
|
390
471
|
_timeoutMs;
|
|
391
472
|
_maxRetries;
|
|
392
473
|
_compress;
|
|
474
|
+
_retryHorizonS;
|
|
475
|
+
/** Total HTTP requests that this exporter sent (each retry and each half of a split counts). */
|
|
476
|
+
attempts = 0;
|
|
393
477
|
// Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
|
|
394
|
-
// a "30-second prod restart" scenario
|
|
395
|
-
//
|
|
396
|
-
// cooldown gives the gateway time to come back before the half-open
|
|
397
|
-
// probe fires. Lower numbers (was 3@30s) tripped on transient blips.
|
|
478
|
+
// a "30-second prod restart" scenario. Since W2-1c only answers that a retry
|
|
479
|
+
// cannot change move it (see the block above).
|
|
398
480
|
_consecutiveFailures = 0;
|
|
399
481
|
_lastMisrouteWarnAt = -Infinity;
|
|
400
482
|
_lastFailureWarnAt = -Infinity;
|
|
483
|
+
_lastExhaustedWarnAt = -Infinity;
|
|
484
|
+
/** "log once" (W2-1c): the WARNING for a `too_large` drop is written one time. */
|
|
485
|
+
_tooLargeWarned = false;
|
|
401
486
|
/**
|
|
402
487
|
* The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
|
|
403
488
|
* 'unknown'). `null` after a success. A new kind in the same outage writes one more
|
|
404
489
|
* WARNING, also inside the window.
|
|
405
490
|
*/
|
|
406
491
|
_failureKind = null;
|
|
492
|
+
/** `endRetries()` was called, and `shutdown()` has not run since. */
|
|
493
|
+
_noWait = false;
|
|
494
|
+
/** The wake-ups of the backoff waits in progress. `endRetries()` calls each one. */
|
|
495
|
+
_waits = /* @__PURE__ */ new Set();
|
|
407
496
|
/** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
|
|
408
497
|
_safeEndpoint;
|
|
409
498
|
/** The endpoint holds userinfo. `fetch` refuses such a URL. */
|
|
@@ -414,6 +503,8 @@ var HttpExporter = class {
|
|
|
414
503
|
_acks = /* @__PURE__ */ new WeakMap();
|
|
415
504
|
/** The requests that each finished call sent, by its batch. Read once by `takeAttempts(spans)`. */
|
|
416
505
|
_requests = /* @__PURE__ */ new WeakMap();
|
|
506
|
+
/** The drop reason of each failed call, by its batch. Read once by `takeDropReason(spans)`. */
|
|
507
|
+
_dropReasons = /* @__PURE__ */ new WeakMap();
|
|
417
508
|
/** The batch processor dropped span(s) from a full queue in the quota pause (S-1). */
|
|
418
509
|
noteQuotaDrop(count = 1) {
|
|
419
510
|
this._quota.addDrops(count);
|
|
@@ -438,8 +529,16 @@ var HttpExporter = class {
|
|
|
438
529
|
this._projectId = options.projectId;
|
|
439
530
|
this._environment = options.environment;
|
|
440
531
|
this._timeoutMs = options.timeoutMs ?? 5e3;
|
|
441
|
-
|
|
532
|
+
let maxRetries = options.maxRetries;
|
|
533
|
+
if (maxRetries !== void 0 && !(Number.isInteger(maxRetries) && maxRetries >= 1)) {
|
|
534
|
+
warn(
|
|
535
|
+
`Risicare: maxRetries=${String(maxRetries)} is not a whole number of 1 or more; the exporter uses no count limit (the retry horizon is the limit).`
|
|
536
|
+
);
|
|
537
|
+
maxRetries = void 0;
|
|
538
|
+
}
|
|
539
|
+
this._maxRetries = maxRetries;
|
|
442
540
|
this._compress = options.compress ?? false;
|
|
541
|
+
this._retryHorizonS = validHorizonS(options.retryHorizonS);
|
|
443
542
|
this._safeEndpoint = safeUrl(this._endpoint);
|
|
444
543
|
this._endpointHasCredentials = hasCredentials(this._endpoint);
|
|
445
544
|
}
|
|
@@ -461,16 +560,18 @@ var HttpExporter = class {
|
|
|
461
560
|
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
462
561
|
return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
|
|
463
562
|
}
|
|
464
|
-
/**
|
|
563
|
+
/**
|
|
564
|
+
* The most attempts for one request body (`maxRetries`). `undefined` when no count is set:
|
|
565
|
+
* the retry horizon is the limit.
|
|
566
|
+
*/
|
|
465
567
|
get attemptsPerExport() {
|
|
466
568
|
return this._maxRetries;
|
|
467
569
|
}
|
|
468
570
|
/**
|
|
469
571
|
* Returns the number of HTTP requests that the `export()` call for `spans` sent, and clears
|
|
470
|
-
* it.
|
|
471
|
-
*
|
|
472
|
-
*
|
|
473
|
-
* kept per batch, as `takeAck` keeps the ack.
|
|
572
|
+
* it. Each retry and each half of a 413 split counts one; a call that the open circuit
|
|
573
|
+
* breaker or the quota pause stops sends none. Returns `null` when no call is on record for
|
|
574
|
+
* `spans`. The answer is kept per batch, as `takeAck` keeps the ack.
|
|
474
575
|
*/
|
|
475
576
|
takeAttempts(spans) {
|
|
476
577
|
const n = this._requests.get(spans) ?? null;
|
|
@@ -487,6 +588,12 @@ var HttpExporter = class {
|
|
|
487
588
|
this._acks.delete(spans);
|
|
488
589
|
return ack;
|
|
489
590
|
}
|
|
591
|
+
/** Returns why the `export()` call for `spans` failed (W2-1c), and clears it. See `SpanExporter`. */
|
|
592
|
+
takeDropReason(spans) {
|
|
593
|
+
const reason = this._dropReasons.get(spans) ?? null;
|
|
594
|
+
this._dropReasons.delete(spans);
|
|
595
|
+
return reason;
|
|
596
|
+
}
|
|
490
597
|
/** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
|
|
491
598
|
takeUnserializable(spans) {
|
|
492
599
|
const bad = this._unserializable.get(spans) ?? [];
|
|
@@ -495,7 +602,7 @@ var HttpExporter = class {
|
|
|
495
602
|
}
|
|
496
603
|
/**
|
|
497
604
|
* Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
|
|
498
|
-
* request, its retries and its backoff
|
|
605
|
+
* request, its retries and its backoff wait. The batch processor calls it when
|
|
499
606
|
* `shutdown()` abandons the batch, so that the call does not keep the process alive. The
|
|
500
607
|
* cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
|
|
501
608
|
* logs no WARNING.
|
|
@@ -505,24 +612,39 @@ var HttpExporter = class {
|
|
|
505
612
|
else for (const call of this._calls.values()) call.cancel.abort();
|
|
506
613
|
}
|
|
507
614
|
/**
|
|
508
|
-
*
|
|
615
|
+
* End the retry waits of this exporter until its next `shutdown()`. The batch processor
|
|
616
|
+
* calls it when `shutdown()` starts. A call that waits for a retry makes one more attempt
|
|
617
|
+
* at once. An attempt that fails after this is not retried: the call fails with the drop
|
|
618
|
+
* reason `shutdown_residue`. So a drain against a dead endpoint costs one attempt for each
|
|
619
|
+
* batch, not the shutdown budget.
|
|
620
|
+
*/
|
|
621
|
+
endRetries() {
|
|
622
|
+
this._noWait = true;
|
|
623
|
+
for (const wake of [...this._waits]) wake();
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Send one batch, with the W2-1c retry policy (see the block above the class).
|
|
627
|
+
*
|
|
628
|
+
* Resolves SUCCESS when the backend accounted for the batch: `takeAck` has the counts (and
|
|
629
|
+
* the spans that a 413 split dropped, in `dropped`). Resolves FAILURE when no span was
|
|
630
|
+
* accounted for: `takeDropReason` then says why, and the batch processor drops the batch
|
|
631
|
+
* with that reason.
|
|
509
632
|
*
|
|
510
633
|
* ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
|
|
511
|
-
* cuts a request that is already sent.
|
|
512
|
-
* healthy, slow server look like a failure: the span used a retry, the breaker moved, and
|
|
513
|
-
* the server stored the same spans again. Only `abort()` stops the call, and only
|
|
634
|
+
* cuts a request that is already sent. Only `abort()` stops the call, and only
|
|
514
635
|
* `shutdown()` calls it.
|
|
515
636
|
*/
|
|
516
637
|
async export(spans) {
|
|
517
638
|
if (spans.length === 0) return "success" /* SUCCESS */;
|
|
518
639
|
const call = {
|
|
519
640
|
cancel: new AbortController(),
|
|
520
|
-
|
|
641
|
+
retryAfterS: null,
|
|
521
642
|
misroute: null,
|
|
522
643
|
noRetry: false,
|
|
523
644
|
status: null,
|
|
524
645
|
error: null,
|
|
525
|
-
attempts: 0
|
|
646
|
+
attempts: 0,
|
|
647
|
+
ack: null
|
|
526
648
|
};
|
|
527
649
|
this._calls.set(spans, call);
|
|
528
650
|
try {
|
|
@@ -559,83 +681,236 @@ var HttpExporter = class {
|
|
|
559
681
|
);
|
|
560
682
|
}
|
|
561
683
|
if (parts.length === 0) return "success" /* SUCCESS */;
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
684
|
+
if (this._consecutiveFailures >= this._circuitBreakerThreshold && Date.now() < this._circuitOpenUntil) {
|
|
685
|
+
this._dropReasons.set(spans, "transport_refused");
|
|
686
|
+
return "failure" /* FAILURE */;
|
|
687
|
+
}
|
|
688
|
+
const out = { delivered: [], dropped: {}, failed: [], cancelled: false };
|
|
689
|
+
const start = performance.now();
|
|
690
|
+
await this._deliver(parts, start, call, out, true);
|
|
691
|
+
if (cancelled.aborted || out.cancelled) {
|
|
692
|
+
this._acks.delete(spans);
|
|
693
|
+
return "failure" /* FAILURE */;
|
|
694
|
+
}
|
|
695
|
+
return this._finish(spans, out, call.attempts);
|
|
696
|
+
}
|
|
697
|
+
/** The request body for `parts` (the serialized spans of one part of a batch). */
|
|
698
|
+
_payload(parts) {
|
|
699
|
+
return `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Send one part of a batch with the retry policy, and record its outcome in `out`.
|
|
703
|
+
* `maySplit` is true only for the whole batch: a 413 splits it in two one time. A half
|
|
704
|
+
* that gets 413 again is dropped as `too_large`.
|
|
705
|
+
*/
|
|
706
|
+
async _deliver(parts, start, call, out, maySplit) {
|
|
707
|
+
const n = parts.length;
|
|
708
|
+
if (!maySplit && this._quota.paused()) {
|
|
709
|
+
out.delivered.push({ n, ack: { accepted: 0, rejected: 0, quotaDropped: n } });
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
const result = await this._sendWithRetries(this._payload(parts), n, start, call);
|
|
713
|
+
if (result.kind === "delivered") {
|
|
714
|
+
out.delivered.push({ n, ack: result.ack });
|
|
715
|
+
} else if (result.kind === "too_large") {
|
|
716
|
+
if (maySplit && n > 1) {
|
|
717
|
+
const mid = Math.ceil(n / 2);
|
|
718
|
+
debug(`Ingest answered HTTP 413 for ${n} span(s): sending two halves of ${mid} and ${n - mid}`);
|
|
719
|
+
await this._deliver(parts.slice(0, mid), start, call, out, false);
|
|
720
|
+
if (!out.cancelled) await this._deliver(parts.slice(mid), start, call, out, false);
|
|
721
|
+
} else {
|
|
722
|
+
out.dropped.too_large = (out.dropped.too_large ?? 0) + n;
|
|
568
723
|
}
|
|
569
|
-
|
|
724
|
+
} else if (result.kind === "cancelled") {
|
|
725
|
+
out.cancelled = true;
|
|
726
|
+
} else {
|
|
727
|
+
out.failed.push({ n, reason: result.kind, answer: result.answer });
|
|
570
728
|
}
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
729
|
+
}
|
|
730
|
+
/** Send one request body until it is delivered or the policy stops. */
|
|
731
|
+
async _sendWithRetries(body, spansSent, start, call) {
|
|
732
|
+
const cancelled = call.cancel.signal;
|
|
733
|
+
let retryNumber = 0;
|
|
734
|
+
let attemptsHere = 0;
|
|
735
|
+
for (; ; ) {
|
|
736
|
+
if (cancelled.aborted) return { kind: "cancelled" };
|
|
737
|
+
call.retryAfterS = null;
|
|
574
738
|
call.misroute = null;
|
|
575
739
|
call.noRetry = false;
|
|
576
740
|
call.status = null;
|
|
577
741
|
call.error = null;
|
|
742
|
+
call.ack = null;
|
|
578
743
|
call.attempts++;
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
744
|
+
attemptsHere++;
|
|
745
|
+
this.attempts++;
|
|
746
|
+
const result = await this._sendRequest(body, spansSent, call);
|
|
747
|
+
if (cancelled.aborted) return { kind: "cancelled" };
|
|
748
|
+
if (result === "success" /* SUCCESS */) return { kind: "delivered", ack: call.ack };
|
|
749
|
+
if (call.status === TOO_LARGE_STATUS) return { kind: "too_large" };
|
|
750
|
+
const answer = {
|
|
751
|
+
status: call.status,
|
|
752
|
+
error: call.error,
|
|
753
|
+
misroute: call.misroute,
|
|
754
|
+
zeroAck: call.noRetry,
|
|
755
|
+
sent: spansSent
|
|
756
|
+
};
|
|
757
|
+
if (!this._retryable(call)) return { kind: "transport_refused", answer };
|
|
758
|
+
if (attemptsHere === RETRY_WARN_AFTER_ATTEMPTS) this._warnOutage(answer, true);
|
|
759
|
+
if (this._noWait) return { kind: "shutdown_residue", answer };
|
|
760
|
+
if (this._maxRetries !== void 0 && attemptsHere >= this._maxRetries) {
|
|
761
|
+
return { kind: "retry_exhausted", answer };
|
|
583
762
|
}
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
763
|
+
const remainingS = this._retryHorizonS - (performance.now() - start) / 1e3;
|
|
764
|
+
if (remainingS <= 0) return { kind: "retry_exhausted", answer };
|
|
765
|
+
const hint = call.retryAfterS;
|
|
766
|
+
const waitS = hint !== null && hint > 0 ? hint : backoffDelayS(retryNumber, jitter.fraction());
|
|
767
|
+
const delayS = Math.min(waitS, remainingS);
|
|
768
|
+
retryNumber++;
|
|
769
|
+
debug(
|
|
770
|
+
`Ingest attempt ${attemptsHere} failed (${answer.status ?? answer.error ?? "unknown"}); next attempt in ${delayS.toFixed(2)} s (${Math.round(remainingS)} s of the horizon left)`
|
|
771
|
+
);
|
|
772
|
+
await this._retryWait(delayS * 1e3, cancelled);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
/** True when the answer of the last attempt of `call` can change on a retry. */
|
|
776
|
+
_retryable(call) {
|
|
777
|
+
if (call.misroute !== null || call.noRetry) return false;
|
|
778
|
+
if (call.status !== null) return RETRY_STATUSES.has(call.status);
|
|
779
|
+
if (this._endpointHasCredentials) return false;
|
|
780
|
+
return call.error !== null;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Wait `ms` before the next attempt. `abort()` and `endRetries()` end the wait at once. The
|
|
784
|
+
* timer does not keep the process alive: when nothing else runs, `beforeExit` starts the
|
|
785
|
+
* SDK's `shutdown()`, which ends the wait.
|
|
786
|
+
*/
|
|
787
|
+
_retryWait(ms, signal) {
|
|
788
|
+
return new Promise((resolve) => {
|
|
789
|
+
if (signal.aborted || this._noWait || ms <= 0) return resolve();
|
|
790
|
+
const done = () => {
|
|
791
|
+
clearTimeout(timer);
|
|
792
|
+
signal.removeEventListener("abort", done);
|
|
793
|
+
this._waits.delete(done);
|
|
794
|
+
resolve();
|
|
795
|
+
};
|
|
796
|
+
const timer = setTimeout(done, Math.min(ms, MAX_TIMER_MS));
|
|
797
|
+
timer.unref?.();
|
|
798
|
+
signal.addEventListener("abort", done, { once: true });
|
|
799
|
+
this._waits.add(done);
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
/** Turn the outcome of the parts of one batch into the result of `export()`. */
|
|
803
|
+
_finish(spans, out, attempts) {
|
|
804
|
+
const reasons = new Set(out.failed.map((f) => f.reason));
|
|
805
|
+
if (out.delivered.length === 0 && Object.keys(out.dropped).length === 0 && reasons.size === 1) {
|
|
806
|
+
const reason = out.failed[0].reason;
|
|
807
|
+
const nFailed = out.failed.reduce((sum, f) => sum + f.n, 0);
|
|
808
|
+
this._dropReasons.set(spans, reason);
|
|
809
|
+
return this._fail(reason, out.failed[out.failed.length - 1].answer, nFailed, attempts);
|
|
810
|
+
}
|
|
811
|
+
let ack;
|
|
812
|
+
if (out.delivered.length === 1 && Object.keys(out.dropped).length === 0 && out.failed.length === 0) {
|
|
813
|
+
ack = out.delivered[0].ack;
|
|
814
|
+
} else {
|
|
815
|
+
let accepted = 0;
|
|
816
|
+
let rejected = 0;
|
|
817
|
+
let quotaDropped = 0;
|
|
818
|
+
for (const part of out.delivered) {
|
|
819
|
+
accepted += part.ack !== null ? part.ack.accepted : part.n;
|
|
820
|
+
rejected += part.ack !== null ? part.ack.rejected : 0;
|
|
821
|
+
quotaDropped += part.ack?.quotaDropped ?? 0;
|
|
596
822
|
}
|
|
823
|
+
const dropped = { ...out.dropped };
|
|
824
|
+
for (const f of out.failed) dropped[f.reason] = (dropped[f.reason] ?? 0) + f.n;
|
|
825
|
+
ack = { accepted, rejected };
|
|
826
|
+
if (quotaDropped > 0) ack.quotaDropped = quotaDropped;
|
|
827
|
+
if (Object.keys(dropped).length > 0) ack.dropped = dropped;
|
|
597
828
|
}
|
|
598
|
-
if (
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
829
|
+
if (ack !== null) this._acks.set(spans, ack);
|
|
830
|
+
this._consecutiveFailures = 0;
|
|
831
|
+
this._failureKind = null;
|
|
832
|
+
const tooLarge = out.dropped.too_large ?? 0;
|
|
833
|
+
if (tooLarge > 0) this._warnTooLarge(tooLarge);
|
|
834
|
+
for (const f of out.failed) {
|
|
835
|
+
if (f.reason === "retry_exhausted") this._warnExhausted(f.n, attempts, f.answer);
|
|
836
|
+
}
|
|
837
|
+
return "success" /* SUCCESS */;
|
|
838
|
+
}
|
|
839
|
+
/** End a call in which no span was accounted for. Always returns FAILURE. */
|
|
840
|
+
_fail(reason, answer, nSpans, attempts) {
|
|
841
|
+
if (reason === "shutdown_residue") {
|
|
842
|
+
debug(`Export ended by shutdown after ${attempts} attempt(s)`);
|
|
602
843
|
return "failure" /* FAILURE */;
|
|
603
844
|
}
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
this.
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
);
|
|
845
|
+
if (reason === "retry_exhausted") {
|
|
846
|
+
if (answer.status === null || !CAPACITY_REFUSAL_STATUSES.has(answer.status)) this._stepBreaker();
|
|
847
|
+
this._warnOutage(answer, true);
|
|
848
|
+
this._warnExhausted(nSpans, attempts, answer);
|
|
849
|
+
return "failure" /* FAILURE */;
|
|
610
850
|
}
|
|
851
|
+
this._stepBreaker();
|
|
852
|
+
this._warnOutage(answer, false);
|
|
853
|
+
return "failure" /* FAILURE */;
|
|
854
|
+
}
|
|
855
|
+
/** Count one failed call toward the circuit breaker. */
|
|
856
|
+
_stepBreaker() {
|
|
611
857
|
this._consecutiveFailures++;
|
|
612
|
-
if (misroute === null && !call.noRetry) {
|
|
613
|
-
const status = call.status;
|
|
614
|
-
const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
|
|
615
|
-
let write = false;
|
|
616
|
-
if (this._consecutiveFailures === 1 || this._failureKind === null) {
|
|
617
|
-
if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
|
|
618
|
-
this._lastFailureWarnAt = Date.now();
|
|
619
|
-
write = true;
|
|
620
|
-
}
|
|
621
|
-
this._failureKind = kind;
|
|
622
|
-
} else if (kind !== this._failureKind) {
|
|
623
|
-
this._failureKind = kind;
|
|
624
|
-
write = true;
|
|
625
|
-
}
|
|
626
|
-
if (write) this._warnOutage(kind, status, call.error);
|
|
627
|
-
}
|
|
628
858
|
if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
|
|
629
859
|
this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
|
|
630
860
|
warn(
|
|
631
861
|
`HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
|
|
632
862
|
);
|
|
633
863
|
}
|
|
634
|
-
return "failure" /* FAILURE */;
|
|
635
864
|
}
|
|
636
|
-
/**
|
|
637
|
-
|
|
865
|
+
/**
|
|
866
|
+
* The outage WARNING: at the first failure of an outage, and when its kind changes. At most
|
|
867
|
+
* one in the window for the first failure; a misroute has its own WARNING, at most one in
|
|
868
|
+
* the window. `retrying` is true for a retryable answer (written after
|
|
869
|
+
* `RETRY_WARN_AFTER_ATTEMPTS` failed attempts of one batch, or when its retries end before
|
|
870
|
+
* that), false for an answer that a retry cannot change (one attempt). The WARNING names the last HTTP status, or the error
|
|
871
|
+
* code when there was no answer. It never names the key or the response body, and names
|
|
872
|
+
* the API key as a cause only for a 401 or 403. An ack of 0 and 0 has its WARNING from
|
|
873
|
+
* `checkAck`.
|
|
874
|
+
*/
|
|
875
|
+
_warnOutage(answer, retrying) {
|
|
876
|
+
if (answer.misroute !== null) {
|
|
877
|
+
if (Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
|
|
878
|
+
this._lastMisrouteWarnAt = Date.now();
|
|
879
|
+
warn(
|
|
880
|
+
`Risicare: spans are NOT reaching ${this._safeEndpoint}. It answered POST /v1/spans with ${answer.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.`
|
|
881
|
+
);
|
|
882
|
+
}
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
if (answer.zeroAck) return;
|
|
886
|
+
const status = answer.status;
|
|
887
|
+
const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : answer.error !== null ? "none" : "unknown";
|
|
888
|
+
let write = false;
|
|
889
|
+
if (this._failureKind === null || !retrying && this._consecutiveFailures === 1) {
|
|
890
|
+
if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
|
|
891
|
+
this._lastFailureWarnAt = Date.now();
|
|
892
|
+
write = true;
|
|
893
|
+
}
|
|
894
|
+
this._failureKind = kind;
|
|
895
|
+
} else if (kind !== this._failureKind) {
|
|
896
|
+
this._failureKind = kind;
|
|
897
|
+
write = true;
|
|
898
|
+
}
|
|
899
|
+
if (!write) return;
|
|
638
900
|
const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
|
|
901
|
+
if (retrying) {
|
|
902
|
+
let limit = `${this._retryHorizonS} s from its first attempt (retryHorizonS)`;
|
|
903
|
+
if (this._maxRetries !== void 0) limit = `${this._maxRetries} attempt(s) (maxRetries) or ${limit}`;
|
|
904
|
+
const retryText = `The SDK sends each batch again with a growing wait, for up to ${limit}, and then drops it (reason=retry_exhausted).`;
|
|
905
|
+
if (kind === "http") {
|
|
906
|
+
warn(`${where}: it answered HTTP ${status}. ${retryText} Set debug: true to see each attempt.`);
|
|
907
|
+
} else {
|
|
908
|
+
warn(
|
|
909
|
+
`${where}: no answer (${answer.error}). The endpoint cannot be reached, or it did not answer in time. ${retryText} Set debug: true to see each attempt.`
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
639
914
|
const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
|
|
640
915
|
if (kind === "auth") {
|
|
641
916
|
warn(
|
|
@@ -643,15 +918,11 @@ var HttpExporter = class {
|
|
|
643
918
|
);
|
|
644
919
|
} else if (kind === "http") {
|
|
645
920
|
warn(
|
|
646
|
-
`${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.`
|
|
921
|
+
`${where}: it answered HTTP ${status}. The server did not take the batch, and a retry cannot change that answer. Check the endpoint and the server. ${tail} Set debug: true to see each attempt.`
|
|
647
922
|
);
|
|
648
923
|
} else if (kind === "none" && this._endpointHasCredentials) {
|
|
649
924
|
warn(
|
|
650
|
-
`${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}`
|
|
651
|
-
);
|
|
652
|
-
} else if (kind === "none") {
|
|
653
|
-
warn(
|
|
654
|
-
`${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.`
|
|
925
|
+
`${where}: no answer (${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}`
|
|
655
926
|
);
|
|
656
927
|
} else {
|
|
657
928
|
warn(
|
|
@@ -659,33 +930,38 @@ var HttpExporter = class {
|
|
|
659
930
|
);
|
|
660
931
|
}
|
|
661
932
|
}
|
|
933
|
+
/** The WARNING for spans dropped as `retry_exhausted`. At most one in the window. */
|
|
934
|
+
_warnExhausted(nSpans, attempts, answer) {
|
|
935
|
+
if (Date.now() - this._lastExhaustedWarnAt <= FAILURE_WARN_WINDOW_MS) return;
|
|
936
|
+
this._lastExhaustedWarnAt = Date.now();
|
|
937
|
+
const last = answer.status !== null ? `HTTP ${answer.status}` : `no answer (${answer.error})`;
|
|
938
|
+
const capacity = answer.status !== null && CAPACITY_REFUSAL_STATUSES.has(answer.status) ? " (over capacity)" : "";
|
|
939
|
+
const limit = this._maxRetries !== void 0 && attempts >= this._maxRetries ? `the maxRetries limit of ${this._maxRetries} attempt(s)` : `the retry horizon of ${this._retryHorizonS} s (retryHorizonS)`;
|
|
940
|
+
warn(
|
|
941
|
+
`Risicare: ${nSpans} span(s) DISCARDED (reason=retry_exhausted): ${this._safeEndpoint} did not take them in ${attempts} attempt(s), and ${limit} is used up. The last answer: ${last}${capacity}. A gateway outage that is longer than the retry horizon loses spans. To wait longer, raise retryHorizonS.`
|
|
942
|
+
);
|
|
943
|
+
}
|
|
944
|
+
/** The WARNING for spans dropped as `too_large`. One time for each exporter. */
|
|
945
|
+
_warnTooLarge(nSpans) {
|
|
946
|
+
if (this._tooLargeWarned) return;
|
|
947
|
+
this._tooLargeWarned = true;
|
|
948
|
+
warn(
|
|
949
|
+
`Risicare: ${nSpans} span(s) DISCARDED (reason=too_large): ${this._safeEndpoint} answered HTTP 413 (the request is too large) for a batch, and again for a half of it after one split. The SDK does not send these spans again. Make the span attributes smaller. This WARNING is written one time; droppedSpansByReason.too_large has the count.`
|
|
950
|
+
);
|
|
951
|
+
}
|
|
662
952
|
/** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
|
|
663
953
|
_noteMisroute(call, answer) {
|
|
664
954
|
call.misroute = this._scrub(answer, 300);
|
|
665
955
|
debug(`Ingest misroute: ${call.misroute}`);
|
|
666
956
|
return "failure" /* FAILURE */;
|
|
667
957
|
}
|
|
668
|
-
/**
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
* parse.
|
|
674
|
-
*/
|
|
675
|
-
_noteRefusal(call, status, retryAfterRaw) {
|
|
676
|
-
if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
|
|
677
|
-
let delay = REFUSAL_NO_HINT;
|
|
678
|
-
if (retryAfterRaw) {
|
|
679
|
-
const secs = Number(retryAfterRaw);
|
|
680
|
-
if (Number.isFinite(secs) && secs >= 0) {
|
|
681
|
-
delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
call.refusalAfterMs = delay;
|
|
685
|
-
debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
|
|
686
|
-
return true;
|
|
958
|
+
/** Record the `Retry-After` wait of a retryable answer for the retry loop. */
|
|
959
|
+
_noteRetryAfter(call, status, retryAfterRaw) {
|
|
960
|
+
if (!RETRY_STATUSES.has(status)) return;
|
|
961
|
+
call.retryAfterS = parseRetryAfterS(retryAfterRaw);
|
|
962
|
+
debug(`Ingest answered HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
|
|
687
963
|
}
|
|
688
|
-
async _sendRequest(body, spansSent, call
|
|
964
|
+
async _sendRequest(body, spansSent, call) {
|
|
689
965
|
const cancelled = call.cancel.signal;
|
|
690
966
|
const timeoutMs = this._timeoutMs;
|
|
691
967
|
const url = `${this._endpoint}/v1/spans`;
|
|
@@ -753,14 +1029,15 @@ var HttpExporter = class {
|
|
|
753
1029
|
} else if (ack.result === "success" /* SUCCESS */) {
|
|
754
1030
|
this._quota.accepted(`the ingest endpoint ${this._safeEndpoint}`);
|
|
755
1031
|
}
|
|
756
|
-
if (ack.result === "success" /* SUCCESS */)
|
|
1032
|
+
if (ack.result === "success" /* SUCCESS */) call.ack = ack.counts;
|
|
757
1033
|
if (ack.final) call.noRetry = true;
|
|
758
1034
|
return ack.result;
|
|
759
|
-
}
|
|
1035
|
+
}
|
|
1036
|
+
this._noteRetryAfter(call, response.status, response.headers?.get?.("Retry-After") ?? null);
|
|
1037
|
+
if (response.status === 408 || response.status === 504) {
|
|
760
1038
|
debug(`HTTP export timeout: ${response.status}`);
|
|
761
1039
|
return "timeout" /* TIMEOUT */;
|
|
762
1040
|
}
|
|
763
|
-
this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
|
|
764
1041
|
debug(`HTTP export failed: ${response.status}`);
|
|
765
1042
|
return "failure" /* FAILURE */;
|
|
766
1043
|
} catch (e) {
|
|
@@ -774,20 +1051,9 @@ var HttpExporter = class {
|
|
|
774
1051
|
}
|
|
775
1052
|
}
|
|
776
1053
|
shutdown() {
|
|
1054
|
+
this._noWait = false;
|
|
777
1055
|
}
|
|
778
1056
|
};
|
|
779
|
-
function sleep(ms, signal) {
|
|
780
|
-
return new Promise((resolve) => {
|
|
781
|
-
if (signal?.aborted) return resolve();
|
|
782
|
-
const done = () => {
|
|
783
|
-
clearTimeout(timer);
|
|
784
|
-
signal?.removeEventListener("abort", done);
|
|
785
|
-
resolve();
|
|
786
|
-
};
|
|
787
|
-
const timer = setTimeout(done, ms);
|
|
788
|
-
signal?.addEventListener("abort", done, { once: true });
|
|
789
|
-
});
|
|
790
|
-
}
|
|
791
1057
|
function asCount(v) {
|
|
792
1058
|
return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
|
|
793
1059
|
}
|