risicare 0.10.0 → 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 +76 -5
- package/README.md +157 -39
- package/dist/frameworks/instructor.cjs +338 -117
- package/dist/frameworks/instructor.cjs.map +1 -1
- package/dist/frameworks/instructor.js +338 -117
- package/dist/frameworks/instructor.js.map +1 -1
- package/dist/frameworks/langchain.cjs +351 -130
- package/dist/frameworks/langchain.cjs.map +1 -1
- package/dist/frameworks/langchain.js +351 -130
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/frameworks/langgraph.cjs +351 -130
- package/dist/frameworks/langgraph.cjs.map +1 -1
- package/dist/frameworks/langgraph.js +351 -130
- package/dist/frameworks/langgraph.js.map +1 -1
- package/dist/frameworks/llamaindex.cjs +351 -130
- package/dist/frameworks/llamaindex.cjs.map +1 -1
- package/dist/frameworks/llamaindex.js +351 -130
- package/dist/frameworks/llamaindex.js.map +1 -1
- package/dist/index.cjs +808 -226
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +137 -21
- package/dist/index.d.ts +137 -21
- package/dist/index.js +804 -226
- package/dist/index.js.map +1 -1
- package/dist/providers/anthropic/index.cjs +351 -130
- package/dist/providers/anthropic/index.cjs.map +1 -1
- package/dist/providers/anthropic/index.js +351 -130
- package/dist/providers/anthropic/index.js.map +1 -1
- package/dist/providers/bedrock/index.cjs +346 -125
- package/dist/providers/bedrock/index.cjs.map +1 -1
- package/dist/providers/bedrock/index.js +346 -125
- package/dist/providers/bedrock/index.js.map +1 -1
- package/dist/providers/cerebras/index.cjs +351 -130
- package/dist/providers/cerebras/index.cjs.map +1 -1
- package/dist/providers/cerebras/index.js +351 -130
- package/dist/providers/cerebras/index.js.map +1 -1
- package/dist/providers/cohere/index.cjs +351 -130
- package/dist/providers/cohere/index.cjs.map +1 -1
- package/dist/providers/cohere/index.js +351 -130
- package/dist/providers/cohere/index.js.map +1 -1
- package/dist/providers/google/index.cjs +351 -130
- package/dist/providers/google/index.cjs.map +1 -1
- package/dist/providers/google/index.js +351 -130
- package/dist/providers/google/index.js.map +1 -1
- package/dist/providers/groq/index.cjs +351 -130
- package/dist/providers/groq/index.cjs.map +1 -1
- package/dist/providers/groq/index.js +351 -130
- package/dist/providers/groq/index.js.map +1 -1
- package/dist/providers/huggingface/index.cjs +351 -130
- package/dist/providers/huggingface/index.cjs.map +1 -1
- package/dist/providers/huggingface/index.js +351 -130
- package/dist/providers/huggingface/index.js.map +1 -1
- package/dist/providers/mistral/index.cjs +351 -130
- package/dist/providers/mistral/index.cjs.map +1 -1
- package/dist/providers/mistral/index.js +351 -130
- package/dist/providers/mistral/index.js.map +1 -1
- package/dist/providers/ollama/index.cjs +351 -130
- package/dist/providers/ollama/index.cjs.map +1 -1
- package/dist/providers/ollama/index.js +351 -130
- package/dist/providers/ollama/index.js.map +1 -1
- package/dist/providers/openai/index.cjs +351 -130
- package/dist/providers/openai/index.cjs.map +1 -1
- package/dist/providers/openai/index.js +351 -130
- package/dist/providers/openai/index.js.map +1 -1
- package/dist/providers/together/index.cjs +351 -130
- package/dist/providers/together/index.cjs.map +1 -1
- package/dist/providers/together/index.js +351 -130
- package/dist/providers/together/index.js.map +1 -1
- package/dist/providers/vercel-ai/index.cjs +351 -130
- package/dist/providers/vercel-ai/index.cjs.map +1 -1
- package/dist/providers/vercel-ai/index.js +351 -130
- package/dist/providers/vercel-ai/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
// src/client.ts
|
|
2
2
|
import { createHash as createHash2 } from "crypto";
|
|
3
3
|
|
|
4
|
+
// src/exporters/retry.ts
|
|
5
|
+
var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
|
|
6
|
+
var TOO_LARGE_STATUS = 413;
|
|
7
|
+
var RETRY_BACKOFF_BASE_S = 1;
|
|
8
|
+
var RETRY_BACKOFF_CAP_S = 30;
|
|
9
|
+
var DEFAULT_RETRY_HORIZON_S = 300;
|
|
10
|
+
var DEFAULT_SHUTDOWN_TIMEOUT_S = 10;
|
|
11
|
+
var RETRY_WARN_AFTER_ATTEMPTS = 3;
|
|
12
|
+
var jitter = { fraction: () => Math.random() };
|
|
13
|
+
function backoffDelayS(retryNumber, fraction) {
|
|
14
|
+
const exponent = Math.min(Math.max(retryNumber, 0), 62);
|
|
15
|
+
const ceiling = Math.min(RETRY_BACKOFF_CAP_S, RETRY_BACKOFF_BASE_S * 2 ** exponent);
|
|
16
|
+
return Math.min(Math.max(fraction, 0), 1) * ceiling;
|
|
17
|
+
}
|
|
18
|
+
var SECONDS = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
|
|
19
|
+
function parseRetryAfterS(value, nowMs = Date.now()) {
|
|
20
|
+
if (value === null || value === void 0) return null;
|
|
21
|
+
const text = String(value).trim();
|
|
22
|
+
if (text === "") return null;
|
|
23
|
+
if (SECONDS.test(text)) {
|
|
24
|
+
const seconds = Number(text);
|
|
25
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
|
|
26
|
+
}
|
|
27
|
+
if (!/[A-Za-z]/.test(text)) return null;
|
|
28
|
+
const when = Date.parse(text);
|
|
29
|
+
if (!Number.isFinite(when)) return null;
|
|
30
|
+
return Math.max(0, (when - nowMs) / 1e3);
|
|
31
|
+
}
|
|
32
|
+
|
|
4
33
|
// src/globals.ts
|
|
5
34
|
import { AsyncLocalStorage } from "async_hooks";
|
|
6
35
|
var G = globalThis;
|
|
@@ -147,10 +176,19 @@ var VALUE_RULE_PREFIXES = new Set(
|
|
|
147
176
|
);
|
|
148
177
|
|
|
149
178
|
// src/exporters/batch.ts
|
|
179
|
+
var SHUTDOWN_BUDGET_MS = DEFAULT_SHUTDOWN_TIMEOUT_S * 1e3;
|
|
150
180
|
var MAX_TIMEOUT_MS = 2 ** 31 - 1;
|
|
151
181
|
var MAX_BATCH_BYTES = 8 * 1024 * 1024;
|
|
152
182
|
var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
|
|
153
183
|
|
|
184
|
+
// src/context/storage.ts
|
|
185
|
+
function storage() {
|
|
186
|
+
return getContextStorage();
|
|
187
|
+
}
|
|
188
|
+
function getContext() {
|
|
189
|
+
return storage().getStore() ?? {};
|
|
190
|
+
}
|
|
191
|
+
|
|
154
192
|
// src/ids.ts
|
|
155
193
|
import { randomBytes } from "crypto";
|
|
156
194
|
|
|
@@ -281,16 +319,8 @@ var SUPPLEMENTAL_RULES = [
|
|
|
281
319
|
{ re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "u"), code: "PERCEPTION.PARSING.JSON_INVALID" }
|
|
282
320
|
];
|
|
283
321
|
|
|
284
|
-
// src/context/storage.ts
|
|
285
|
-
function storage() {
|
|
286
|
-
return getContextStorage();
|
|
287
|
-
}
|
|
288
|
-
function getContext() {
|
|
289
|
-
return storage().getStore() ?? {};
|
|
290
|
-
}
|
|
291
|
-
|
|
292
322
|
// src/version.ts
|
|
293
|
-
var SDK_VERSION = "0.
|
|
323
|
+
var SDK_VERSION = "0.11.0";
|
|
294
324
|
|
|
295
325
|
// src/exporters/quota.ts
|
|
296
326
|
var QUOTA_REASON = "monthly_quota_exceeded";
|
|
@@ -398,12 +428,18 @@ var QuotaPause = class {
|
|
|
398
428
|
|
|
399
429
|
// src/exporters/http.ts
|
|
400
430
|
var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
|
|
401
|
-
var RETRY_AFTER_CEILING_MS = 1e4;
|
|
402
|
-
var REFUSAL_BACKOFF_BASE_MS = 1e3;
|
|
403
|
-
var REFUSAL_NO_HINT = -1;
|
|
404
431
|
var MISROUTE_WARN_WINDOW_MS = 3e5;
|
|
405
432
|
var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
|
|
406
433
|
var FAILURE_WARN_WINDOW_MS = 3e5;
|
|
434
|
+
var MAX_TIMER_MS = 2 ** 31 - 1;
|
|
435
|
+
function validHorizonS(value) {
|
|
436
|
+
if (value === void 0) return DEFAULT_RETRY_HORIZON_S;
|
|
437
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
|
|
438
|
+
warn(
|
|
439
|
+
`Risicare: retryHorizonS=${String(value)} is not a finite number of 0 or more; using the default, ${DEFAULT_RETRY_HORIZON_S} s.`
|
|
440
|
+
);
|
|
441
|
+
return DEFAULT_RETRY_HORIZON_S;
|
|
442
|
+
}
|
|
407
443
|
var HttpExporter = class {
|
|
408
444
|
name = "http";
|
|
409
445
|
_endpoint;
|
|
@@ -413,20 +449,28 @@ var HttpExporter = class {
|
|
|
413
449
|
_timeoutMs;
|
|
414
450
|
_maxRetries;
|
|
415
451
|
_compress;
|
|
452
|
+
_retryHorizonS;
|
|
453
|
+
/** Total HTTP requests that this exporter sent (each retry and each half of a split counts). */
|
|
454
|
+
attempts = 0;
|
|
416
455
|
// Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
|
|
417
|
-
// a "30-second prod restart" scenario
|
|
418
|
-
//
|
|
419
|
-
// cooldown gives the gateway time to come back before the half-open
|
|
420
|
-
// probe fires. Lower numbers (was 3@30s) tripped on transient blips.
|
|
456
|
+
// a "30-second prod restart" scenario. Since W2-1c only answers that a retry
|
|
457
|
+
// cannot change move it (see the block above).
|
|
421
458
|
_consecutiveFailures = 0;
|
|
422
459
|
_lastMisrouteWarnAt = -Infinity;
|
|
423
460
|
_lastFailureWarnAt = -Infinity;
|
|
461
|
+
_lastExhaustedWarnAt = -Infinity;
|
|
462
|
+
/** "log once" (W2-1c): the WARNING for a `too_large` drop is written one time. */
|
|
463
|
+
_tooLargeWarned = false;
|
|
424
464
|
/**
|
|
425
465
|
* The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
|
|
426
466
|
* 'unknown'). `null` after a success. A new kind in the same outage writes one more
|
|
427
467
|
* WARNING, also inside the window.
|
|
428
468
|
*/
|
|
429
469
|
_failureKind = null;
|
|
470
|
+
/** `endRetries()` was called, and `shutdown()` has not run since. */
|
|
471
|
+
_noWait = false;
|
|
472
|
+
/** The wake-ups of the backoff waits in progress. `endRetries()` calls each one. */
|
|
473
|
+
_waits = /* @__PURE__ */ new Set();
|
|
430
474
|
/** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
|
|
431
475
|
_safeEndpoint;
|
|
432
476
|
/** The endpoint holds userinfo. `fetch` refuses such a URL. */
|
|
@@ -437,6 +481,8 @@ var HttpExporter = class {
|
|
|
437
481
|
_acks = /* @__PURE__ */ new WeakMap();
|
|
438
482
|
/** The requests that each finished call sent, by its batch. Read once by `takeAttempts(spans)`. */
|
|
439
483
|
_requests = /* @__PURE__ */ new WeakMap();
|
|
484
|
+
/** The drop reason of each failed call, by its batch. Read once by `takeDropReason(spans)`. */
|
|
485
|
+
_dropReasons = /* @__PURE__ */ new WeakMap();
|
|
440
486
|
/** The batch processor dropped span(s) from a full queue in the quota pause (S-1). */
|
|
441
487
|
noteQuotaDrop(count = 1) {
|
|
442
488
|
this._quota.addDrops(count);
|
|
@@ -461,8 +507,16 @@ var HttpExporter = class {
|
|
|
461
507
|
this._projectId = options.projectId;
|
|
462
508
|
this._environment = options.environment;
|
|
463
509
|
this._timeoutMs = options.timeoutMs ?? 5e3;
|
|
464
|
-
|
|
510
|
+
let maxRetries = options.maxRetries;
|
|
511
|
+
if (maxRetries !== void 0 && !(Number.isInteger(maxRetries) && maxRetries >= 1)) {
|
|
512
|
+
warn(
|
|
513
|
+
`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).`
|
|
514
|
+
);
|
|
515
|
+
maxRetries = void 0;
|
|
516
|
+
}
|
|
517
|
+
this._maxRetries = maxRetries;
|
|
465
518
|
this._compress = options.compress ?? false;
|
|
519
|
+
this._retryHorizonS = validHorizonS(options.retryHorizonS);
|
|
466
520
|
this._safeEndpoint = safeUrl(this._endpoint);
|
|
467
521
|
this._endpointHasCredentials = hasCredentials(this._endpoint);
|
|
468
522
|
}
|
|
@@ -484,16 +538,18 @@ var HttpExporter = class {
|
|
|
484
538
|
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
485
539
|
return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
|
|
486
540
|
}
|
|
487
|
-
/**
|
|
541
|
+
/**
|
|
542
|
+
* The most attempts for one request body (`maxRetries`). `undefined` when no count is set:
|
|
543
|
+
* the retry horizon is the limit.
|
|
544
|
+
*/
|
|
488
545
|
get attemptsPerExport() {
|
|
489
546
|
return this._maxRetries;
|
|
490
547
|
}
|
|
491
548
|
/**
|
|
492
549
|
* Returns the number of HTTP requests that the `export()` call for `spans` sent, and clears
|
|
493
|
-
* it.
|
|
494
|
-
*
|
|
495
|
-
*
|
|
496
|
-
* kept per batch, as `takeAck` keeps the ack.
|
|
550
|
+
* it. Each retry and each half of a 413 split counts one; a call that the open circuit
|
|
551
|
+
* breaker or the quota pause stops sends none. Returns `null` when no call is on record for
|
|
552
|
+
* `spans`. The answer is kept per batch, as `takeAck` keeps the ack.
|
|
497
553
|
*/
|
|
498
554
|
takeAttempts(spans) {
|
|
499
555
|
const n = this._requests.get(spans) ?? null;
|
|
@@ -510,6 +566,12 @@ var HttpExporter = class {
|
|
|
510
566
|
this._acks.delete(spans);
|
|
511
567
|
return ack;
|
|
512
568
|
}
|
|
569
|
+
/** Returns why the `export()` call for `spans` failed (W2-1c), and clears it. See `SpanExporter`. */
|
|
570
|
+
takeDropReason(spans) {
|
|
571
|
+
const reason = this._dropReasons.get(spans) ?? null;
|
|
572
|
+
this._dropReasons.delete(spans);
|
|
573
|
+
return reason;
|
|
574
|
+
}
|
|
513
575
|
/** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
|
|
514
576
|
takeUnserializable(spans) {
|
|
515
577
|
const bad = this._unserializable.get(spans) ?? [];
|
|
@@ -518,7 +580,7 @@ var HttpExporter = class {
|
|
|
518
580
|
}
|
|
519
581
|
/**
|
|
520
582
|
* Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
|
|
521
|
-
* request, its retries and its backoff
|
|
583
|
+
* request, its retries and its backoff wait. The batch processor calls it when
|
|
522
584
|
* `shutdown()` abandons the batch, so that the call does not keep the process alive. The
|
|
523
585
|
* cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
|
|
524
586
|
* logs no WARNING.
|
|
@@ -528,24 +590,39 @@ var HttpExporter = class {
|
|
|
528
590
|
else for (const call of this._calls.values()) call.cancel.abort();
|
|
529
591
|
}
|
|
530
592
|
/**
|
|
531
|
-
*
|
|
593
|
+
* End the retry waits of this exporter until its next `shutdown()`. The batch processor
|
|
594
|
+
* calls it when `shutdown()` starts. A call that waits for a retry makes one more attempt
|
|
595
|
+
* at once. An attempt that fails after this is not retried: the call fails with the drop
|
|
596
|
+
* reason `shutdown_residue`. So a drain against a dead endpoint costs one attempt for each
|
|
597
|
+
* batch, not the shutdown budget.
|
|
598
|
+
*/
|
|
599
|
+
endRetries() {
|
|
600
|
+
this._noWait = true;
|
|
601
|
+
for (const wake of [...this._waits]) wake();
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* Send one batch, with the W2-1c retry policy (see the block above the class).
|
|
605
|
+
*
|
|
606
|
+
* Resolves SUCCESS when the backend accounted for the batch: `takeAck` has the counts (and
|
|
607
|
+
* the spans that a 413 split dropped, in `dropped`). Resolves FAILURE when no span was
|
|
608
|
+
* accounted for: `takeDropReason` then says why, and the batch processor drops the batch
|
|
609
|
+
* with that reason.
|
|
532
610
|
*
|
|
533
611
|
* ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
|
|
534
|
-
* cuts a request that is already sent.
|
|
535
|
-
* healthy, slow server look like a failure: the span used a retry, the breaker moved, and
|
|
536
|
-
* the server stored the same spans again. Only `abort()` stops the call, and only
|
|
612
|
+
* cuts a request that is already sent. Only `abort()` stops the call, and only
|
|
537
613
|
* `shutdown()` calls it.
|
|
538
614
|
*/
|
|
539
615
|
async export(spans) {
|
|
540
616
|
if (spans.length === 0) return "success" /* SUCCESS */;
|
|
541
617
|
const call = {
|
|
542
618
|
cancel: new AbortController(),
|
|
543
|
-
|
|
619
|
+
retryAfterS: null,
|
|
544
620
|
misroute: null,
|
|
545
621
|
noRetry: false,
|
|
546
622
|
status: null,
|
|
547
623
|
error: null,
|
|
548
|
-
attempts: 0
|
|
624
|
+
attempts: 0,
|
|
625
|
+
ack: null
|
|
549
626
|
};
|
|
550
627
|
this._calls.set(spans, call);
|
|
551
628
|
try {
|
|
@@ -582,83 +659,236 @@ var HttpExporter = class {
|
|
|
582
659
|
);
|
|
583
660
|
}
|
|
584
661
|
if (parts.length === 0) return "success" /* SUCCESS */;
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
662
|
+
if (this._consecutiveFailures >= this._circuitBreakerThreshold && Date.now() < this._circuitOpenUntil) {
|
|
663
|
+
this._dropReasons.set(spans, "transport_refused");
|
|
664
|
+
return "failure" /* FAILURE */;
|
|
665
|
+
}
|
|
666
|
+
const out = { delivered: [], dropped: {}, failed: [], cancelled: false };
|
|
667
|
+
const start = performance.now();
|
|
668
|
+
await this._deliver(parts, start, call, out, true);
|
|
669
|
+
if (cancelled.aborted || out.cancelled) {
|
|
670
|
+
this._acks.delete(spans);
|
|
671
|
+
return "failure" /* FAILURE */;
|
|
672
|
+
}
|
|
673
|
+
return this._finish(spans, out, call.attempts);
|
|
674
|
+
}
|
|
675
|
+
/** The request body for `parts` (the serialized spans of one part of a batch). */
|
|
676
|
+
_payload(parts) {
|
|
677
|
+
return `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* Send one part of a batch with the retry policy, and record its outcome in `out`.
|
|
681
|
+
* `maySplit` is true only for the whole batch: a 413 splits it in two one time. A half
|
|
682
|
+
* that gets 413 again is dropped as `too_large`.
|
|
683
|
+
*/
|
|
684
|
+
async _deliver(parts, start, call, out, maySplit) {
|
|
685
|
+
const n = parts.length;
|
|
686
|
+
if (!maySplit && this._quota.paused()) {
|
|
687
|
+
out.delivered.push({ n, ack: { accepted: 0, rejected: 0, quotaDropped: n } });
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
const result = await this._sendWithRetries(this._payload(parts), n, start, call);
|
|
691
|
+
if (result.kind === "delivered") {
|
|
692
|
+
out.delivered.push({ n, ack: result.ack });
|
|
693
|
+
} else if (result.kind === "too_large") {
|
|
694
|
+
if (maySplit && n > 1) {
|
|
695
|
+
const mid = Math.ceil(n / 2);
|
|
696
|
+
debug(`Ingest answered HTTP 413 for ${n} span(s): sending two halves of ${mid} and ${n - mid}`);
|
|
697
|
+
await this._deliver(parts.slice(0, mid), start, call, out, false);
|
|
698
|
+
if (!out.cancelled) await this._deliver(parts.slice(mid), start, call, out, false);
|
|
699
|
+
} else {
|
|
700
|
+
out.dropped.too_large = (out.dropped.too_large ?? 0) + n;
|
|
591
701
|
}
|
|
592
|
-
|
|
702
|
+
} else if (result.kind === "cancelled") {
|
|
703
|
+
out.cancelled = true;
|
|
704
|
+
} else {
|
|
705
|
+
out.failed.push({ n, reason: result.kind, answer: result.answer });
|
|
593
706
|
}
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
707
|
+
}
|
|
708
|
+
/** Send one request body until it is delivered or the policy stops. */
|
|
709
|
+
async _sendWithRetries(body, spansSent, start, call) {
|
|
710
|
+
const cancelled = call.cancel.signal;
|
|
711
|
+
let retryNumber = 0;
|
|
712
|
+
let attemptsHere = 0;
|
|
713
|
+
for (; ; ) {
|
|
714
|
+
if (cancelled.aborted) return { kind: "cancelled" };
|
|
715
|
+
call.retryAfterS = null;
|
|
597
716
|
call.misroute = null;
|
|
598
717
|
call.noRetry = false;
|
|
599
718
|
call.status = null;
|
|
600
719
|
call.error = null;
|
|
720
|
+
call.ack = null;
|
|
601
721
|
call.attempts++;
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
}
|
|
607
|
-
if (
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
722
|
+
attemptsHere++;
|
|
723
|
+
this.attempts++;
|
|
724
|
+
const result = await this._sendRequest(body, spansSent, call);
|
|
725
|
+
if (cancelled.aborted) return { kind: "cancelled" };
|
|
726
|
+
if (result === "success" /* SUCCESS */) return { kind: "delivered", ack: call.ack };
|
|
727
|
+
if (call.status === TOO_LARGE_STATUS) return { kind: "too_large" };
|
|
728
|
+
const answer = {
|
|
729
|
+
status: call.status,
|
|
730
|
+
error: call.error,
|
|
731
|
+
misroute: call.misroute,
|
|
732
|
+
zeroAck: call.noRetry,
|
|
733
|
+
sent: spansSent
|
|
734
|
+
};
|
|
735
|
+
if (!this._retryable(call)) return { kind: "transport_refused", answer };
|
|
736
|
+
if (attemptsHere === RETRY_WARN_AFTER_ATTEMPTS) this._warnOutage(answer, true);
|
|
737
|
+
if (this._noWait) return { kind: "shutdown_residue", answer };
|
|
738
|
+
if (this._maxRetries !== void 0 && attemptsHere >= this._maxRetries) {
|
|
739
|
+
return { kind: "retry_exhausted", answer };
|
|
611
740
|
}
|
|
612
|
-
|
|
613
|
-
if (
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
741
|
+
const remainingS = this._retryHorizonS - (performance.now() - start) / 1e3;
|
|
742
|
+
if (remainingS <= 0) return { kind: "retry_exhausted", answer };
|
|
743
|
+
const hint = call.retryAfterS;
|
|
744
|
+
const waitS = hint !== null && hint > 0 ? hint : backoffDelayS(retryNumber, jitter.fraction());
|
|
745
|
+
const delayS = Math.min(waitS, remainingS);
|
|
746
|
+
retryNumber++;
|
|
747
|
+
debug(
|
|
748
|
+
`Ingest attempt ${attemptsHere} failed (${answer.status ?? answer.error ?? "unknown"}); next attempt in ${delayS.toFixed(2)} s (${Math.round(remainingS)} s of the horizon left)`
|
|
749
|
+
);
|
|
750
|
+
await this._retryWait(delayS * 1e3, cancelled);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
/** True when the answer of the last attempt of `call` can change on a retry. */
|
|
754
|
+
_retryable(call) {
|
|
755
|
+
if (call.misroute !== null || call.noRetry) return false;
|
|
756
|
+
if (call.status !== null) return RETRY_STATUSES.has(call.status);
|
|
757
|
+
if (this._endpointHasCredentials) return false;
|
|
758
|
+
return call.error !== null;
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* Wait `ms` before the next attempt. `abort()` and `endRetries()` end the wait at once. The
|
|
762
|
+
* timer does not keep the process alive: when nothing else runs, `beforeExit` starts the
|
|
763
|
+
* SDK's `shutdown()`, which ends the wait.
|
|
764
|
+
*/
|
|
765
|
+
_retryWait(ms, signal) {
|
|
766
|
+
return new Promise((resolve) => {
|
|
767
|
+
if (signal.aborted || this._noWait || ms <= 0) return resolve();
|
|
768
|
+
const done = () => {
|
|
769
|
+
clearTimeout(timer);
|
|
770
|
+
signal.removeEventListener("abort", done);
|
|
771
|
+
this._waits.delete(done);
|
|
772
|
+
resolve();
|
|
773
|
+
};
|
|
774
|
+
const timer = setTimeout(done, Math.min(ms, MAX_TIMER_MS));
|
|
775
|
+
timer.unref?.();
|
|
776
|
+
signal.addEventListener("abort", done, { once: true });
|
|
777
|
+
this._waits.add(done);
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
/** Turn the outcome of the parts of one batch into the result of `export()`. */
|
|
781
|
+
_finish(spans, out, attempts) {
|
|
782
|
+
const reasons = new Set(out.failed.map((f) => f.reason));
|
|
783
|
+
if (out.delivered.length === 0 && Object.keys(out.dropped).length === 0 && reasons.size === 1) {
|
|
784
|
+
const reason = out.failed[0].reason;
|
|
785
|
+
const nFailed = out.failed.reduce((sum, f) => sum + f.n, 0);
|
|
786
|
+
this._dropReasons.set(spans, reason);
|
|
787
|
+
return this._fail(reason, out.failed[out.failed.length - 1].answer, nFailed, attempts);
|
|
788
|
+
}
|
|
789
|
+
let ack;
|
|
790
|
+
if (out.delivered.length === 1 && Object.keys(out.dropped).length === 0 && out.failed.length === 0) {
|
|
791
|
+
ack = out.delivered[0].ack;
|
|
792
|
+
} else {
|
|
793
|
+
let accepted = 0;
|
|
794
|
+
let rejected = 0;
|
|
795
|
+
let quotaDropped = 0;
|
|
796
|
+
for (const part of out.delivered) {
|
|
797
|
+
accepted += part.ack !== null ? part.ack.accepted : part.n;
|
|
798
|
+
rejected += part.ack !== null ? part.ack.rejected : 0;
|
|
799
|
+
quotaDropped += part.ack?.quotaDropped ?? 0;
|
|
619
800
|
}
|
|
801
|
+
const dropped = { ...out.dropped };
|
|
802
|
+
for (const f of out.failed) dropped[f.reason] = (dropped[f.reason] ?? 0) + f.n;
|
|
803
|
+
ack = { accepted, rejected };
|
|
804
|
+
if (quotaDropped > 0) ack.quotaDropped = quotaDropped;
|
|
805
|
+
if (Object.keys(dropped).length > 0) ack.dropped = dropped;
|
|
620
806
|
}
|
|
621
|
-
if (
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
807
|
+
if (ack !== null) this._acks.set(spans, ack);
|
|
808
|
+
this._consecutiveFailures = 0;
|
|
809
|
+
this._failureKind = null;
|
|
810
|
+
const tooLarge = out.dropped.too_large ?? 0;
|
|
811
|
+
if (tooLarge > 0) this._warnTooLarge(tooLarge);
|
|
812
|
+
for (const f of out.failed) {
|
|
813
|
+
if (f.reason === "retry_exhausted") this._warnExhausted(f.n, attempts, f.answer);
|
|
814
|
+
}
|
|
815
|
+
return "success" /* SUCCESS */;
|
|
816
|
+
}
|
|
817
|
+
/** End a call in which no span was accounted for. Always returns FAILURE. */
|
|
818
|
+
_fail(reason, answer, nSpans, attempts) {
|
|
819
|
+
if (reason === "shutdown_residue") {
|
|
820
|
+
debug(`Export ended by shutdown after ${attempts} attempt(s)`);
|
|
625
821
|
return "failure" /* FAILURE */;
|
|
626
822
|
}
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
this.
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
);
|
|
823
|
+
if (reason === "retry_exhausted") {
|
|
824
|
+
if (answer.status === null || !CAPACITY_REFUSAL_STATUSES.has(answer.status)) this._stepBreaker();
|
|
825
|
+
this._warnOutage(answer, true);
|
|
826
|
+
this._warnExhausted(nSpans, attempts, answer);
|
|
827
|
+
return "failure" /* FAILURE */;
|
|
633
828
|
}
|
|
829
|
+
this._stepBreaker();
|
|
830
|
+
this._warnOutage(answer, false);
|
|
831
|
+
return "failure" /* FAILURE */;
|
|
832
|
+
}
|
|
833
|
+
/** Count one failed call toward the circuit breaker. */
|
|
834
|
+
_stepBreaker() {
|
|
634
835
|
this._consecutiveFailures++;
|
|
635
|
-
if (misroute === null && !call.noRetry) {
|
|
636
|
-
const status = call.status;
|
|
637
|
-
const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
|
|
638
|
-
let write = false;
|
|
639
|
-
if (this._consecutiveFailures === 1 || this._failureKind === null) {
|
|
640
|
-
if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
|
|
641
|
-
this._lastFailureWarnAt = Date.now();
|
|
642
|
-
write = true;
|
|
643
|
-
}
|
|
644
|
-
this._failureKind = kind;
|
|
645
|
-
} else if (kind !== this._failureKind) {
|
|
646
|
-
this._failureKind = kind;
|
|
647
|
-
write = true;
|
|
648
|
-
}
|
|
649
|
-
if (write) this._warnOutage(kind, status, call.error);
|
|
650
|
-
}
|
|
651
836
|
if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
|
|
652
837
|
this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
|
|
653
838
|
warn(
|
|
654
839
|
`HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
|
|
655
840
|
);
|
|
656
841
|
}
|
|
657
|
-
return "failure" /* FAILURE */;
|
|
658
842
|
}
|
|
659
|
-
/**
|
|
660
|
-
|
|
843
|
+
/**
|
|
844
|
+
* The outage WARNING: at the first failure of an outage, and when its kind changes. At most
|
|
845
|
+
* one in the window for the first failure; a misroute has its own WARNING, at most one in
|
|
846
|
+
* the window. `retrying` is true for a retryable answer (written after
|
|
847
|
+
* `RETRY_WARN_AFTER_ATTEMPTS` failed attempts of one batch, or when its retries end before
|
|
848
|
+
* that), false for an answer that a retry cannot change (one attempt). The WARNING names the last HTTP status, or the error
|
|
849
|
+
* code when there was no answer. It never names the key or the response body, and names
|
|
850
|
+
* the API key as a cause only for a 401 or 403. An ack of 0 and 0 has its WARNING from
|
|
851
|
+
* `checkAck`.
|
|
852
|
+
*/
|
|
853
|
+
_warnOutage(answer, retrying) {
|
|
854
|
+
if (answer.misroute !== null) {
|
|
855
|
+
if (Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
|
|
856
|
+
this._lastMisrouteWarnAt = Date.now();
|
|
857
|
+
warn(
|
|
858
|
+
`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.`
|
|
859
|
+
);
|
|
860
|
+
}
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
if (answer.zeroAck) return;
|
|
864
|
+
const status = answer.status;
|
|
865
|
+
const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : answer.error !== null ? "none" : "unknown";
|
|
866
|
+
let write = false;
|
|
867
|
+
if (this._failureKind === null || !retrying && this._consecutiveFailures === 1) {
|
|
868
|
+
if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
|
|
869
|
+
this._lastFailureWarnAt = Date.now();
|
|
870
|
+
write = true;
|
|
871
|
+
}
|
|
872
|
+
this._failureKind = kind;
|
|
873
|
+
} else if (kind !== this._failureKind) {
|
|
874
|
+
this._failureKind = kind;
|
|
875
|
+
write = true;
|
|
876
|
+
}
|
|
877
|
+
if (!write) return;
|
|
661
878
|
const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
|
|
879
|
+
if (retrying) {
|
|
880
|
+
let limit = `${this._retryHorizonS} s from its first attempt (retryHorizonS)`;
|
|
881
|
+
if (this._maxRetries !== void 0) limit = `${this._maxRetries} attempt(s) (maxRetries) or ${limit}`;
|
|
882
|
+
const retryText = `The SDK sends each batch again with a growing wait, for up to ${limit}, and then drops it (reason=retry_exhausted).`;
|
|
883
|
+
if (kind === "http") {
|
|
884
|
+
warn(`${where}: it answered HTTP ${status}. ${retryText} Set debug: true to see each attempt.`);
|
|
885
|
+
} else {
|
|
886
|
+
warn(
|
|
887
|
+
`${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.`
|
|
888
|
+
);
|
|
889
|
+
}
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
662
892
|
const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
|
|
663
893
|
if (kind === "auth") {
|
|
664
894
|
warn(
|
|
@@ -666,15 +896,11 @@ var HttpExporter = class {
|
|
|
666
896
|
);
|
|
667
897
|
} else if (kind === "http") {
|
|
668
898
|
warn(
|
|
669
|
-
`${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.`
|
|
899
|
+
`${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.`
|
|
670
900
|
);
|
|
671
901
|
} else if (kind === "none" && this._endpointHasCredentials) {
|
|
672
902
|
warn(
|
|
673
|
-
`${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}`
|
|
674
|
-
);
|
|
675
|
-
} else if (kind === "none") {
|
|
676
|
-
warn(
|
|
677
|
-
`${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.`
|
|
903
|
+
`${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}`
|
|
678
904
|
);
|
|
679
905
|
} else {
|
|
680
906
|
warn(
|
|
@@ -682,33 +908,38 @@ var HttpExporter = class {
|
|
|
682
908
|
);
|
|
683
909
|
}
|
|
684
910
|
}
|
|
911
|
+
/** The WARNING for spans dropped as `retry_exhausted`. At most one in the window. */
|
|
912
|
+
_warnExhausted(nSpans, attempts, answer) {
|
|
913
|
+
if (Date.now() - this._lastExhaustedWarnAt <= FAILURE_WARN_WINDOW_MS) return;
|
|
914
|
+
this._lastExhaustedWarnAt = Date.now();
|
|
915
|
+
const last = answer.status !== null ? `HTTP ${answer.status}` : `no answer (${answer.error})`;
|
|
916
|
+
const capacity = answer.status !== null && CAPACITY_REFUSAL_STATUSES.has(answer.status) ? " (over capacity)" : "";
|
|
917
|
+
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)`;
|
|
918
|
+
warn(
|
|
919
|
+
`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.`
|
|
920
|
+
);
|
|
921
|
+
}
|
|
922
|
+
/** The WARNING for spans dropped as `too_large`. One time for each exporter. */
|
|
923
|
+
_warnTooLarge(nSpans) {
|
|
924
|
+
if (this._tooLargeWarned) return;
|
|
925
|
+
this._tooLargeWarned = true;
|
|
926
|
+
warn(
|
|
927
|
+
`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.`
|
|
928
|
+
);
|
|
929
|
+
}
|
|
685
930
|
/** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
|
|
686
931
|
_noteMisroute(call, answer) {
|
|
687
932
|
call.misroute = this._scrub(answer, 300);
|
|
688
933
|
debug(`Ingest misroute: ${call.misroute}`);
|
|
689
934
|
return "failure" /* FAILURE */;
|
|
690
935
|
}
|
|
691
|
-
/**
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
* parse.
|
|
697
|
-
*/
|
|
698
|
-
_noteRefusal(call, status, retryAfterRaw) {
|
|
699
|
-
if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
|
|
700
|
-
let delay = REFUSAL_NO_HINT;
|
|
701
|
-
if (retryAfterRaw) {
|
|
702
|
-
const secs = Number(retryAfterRaw);
|
|
703
|
-
if (Number.isFinite(secs) && secs >= 0) {
|
|
704
|
-
delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
call.refusalAfterMs = delay;
|
|
708
|
-
debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
|
|
709
|
-
return true;
|
|
936
|
+
/** Record the `Retry-After` wait of a retryable answer for the retry loop. */
|
|
937
|
+
_noteRetryAfter(call, status, retryAfterRaw) {
|
|
938
|
+
if (!RETRY_STATUSES.has(status)) return;
|
|
939
|
+
call.retryAfterS = parseRetryAfterS(retryAfterRaw);
|
|
940
|
+
debug(`Ingest answered HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
|
|
710
941
|
}
|
|
711
|
-
async _sendRequest(body, spansSent, call
|
|
942
|
+
async _sendRequest(body, spansSent, call) {
|
|
712
943
|
const cancelled = call.cancel.signal;
|
|
713
944
|
const timeoutMs = this._timeoutMs;
|
|
714
945
|
const url = `${this._endpoint}/v1/spans`;
|
|
@@ -776,14 +1007,15 @@ var HttpExporter = class {
|
|
|
776
1007
|
} else if (ack.result === "success" /* SUCCESS */) {
|
|
777
1008
|
this._quota.accepted(`the ingest endpoint ${this._safeEndpoint}`);
|
|
778
1009
|
}
|
|
779
|
-
if (ack.result === "success" /* SUCCESS */)
|
|
1010
|
+
if (ack.result === "success" /* SUCCESS */) call.ack = ack.counts;
|
|
780
1011
|
if (ack.final) call.noRetry = true;
|
|
781
1012
|
return ack.result;
|
|
782
|
-
}
|
|
1013
|
+
}
|
|
1014
|
+
this._noteRetryAfter(call, response.status, response.headers?.get?.("Retry-After") ?? null);
|
|
1015
|
+
if (response.status === 408 || response.status === 504) {
|
|
783
1016
|
debug(`HTTP export timeout: ${response.status}`);
|
|
784
1017
|
return "timeout" /* TIMEOUT */;
|
|
785
1018
|
}
|
|
786
|
-
this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
|
|
787
1019
|
debug(`HTTP export failed: ${response.status}`);
|
|
788
1020
|
return "failure" /* FAILURE */;
|
|
789
1021
|
} catch (e) {
|
|
@@ -797,20 +1029,9 @@ var HttpExporter = class {
|
|
|
797
1029
|
}
|
|
798
1030
|
}
|
|
799
1031
|
shutdown() {
|
|
1032
|
+
this._noWait = false;
|
|
800
1033
|
}
|
|
801
1034
|
};
|
|
802
|
-
function sleep(ms, signal) {
|
|
803
|
-
return new Promise((resolve) => {
|
|
804
|
-
if (signal?.aborted) return resolve();
|
|
805
|
-
const done = () => {
|
|
806
|
-
clearTimeout(timer);
|
|
807
|
-
signal?.removeEventListener("abort", done);
|
|
808
|
-
resolve();
|
|
809
|
-
};
|
|
810
|
-
const timer = setTimeout(done, ms);
|
|
811
|
-
signal?.addEventListener("abort", done, { once: true });
|
|
812
|
-
});
|
|
813
|
-
}
|
|
814
1035
|
function asCount(v) {
|
|
815
1036
|
return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
|
|
816
1037
|
}
|