@libo11y/workers 0.8.0 → 0.9.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 +114 -50
- package/dist/adapters.d.ts +102 -0
- package/dist/adapters.js +282 -0
- package/dist/env.d.ts +0 -6
- package/dist/env.js +2 -18
- package/dist/exporters.d.ts +16 -18
- package/dist/exporters.js +206 -95
- package/dist/flush.d.ts +25 -10
- package/dist/flush.js +32 -5
- package/dist/index.d.ts +12 -8
- package/dist/index.js +10 -6
- package/dist/instrument.d.ts +28 -33
- package/dist/instrument.js +35 -77
- package/dist/log-processor.d.ts +23 -0
- package/dist/log-processor.js +157 -0
- package/dist/metric-reader.d.ts +23 -3
- package/dist/metric-reader.js +189 -30
- package/dist/platform.d.ts +15 -4
- package/dist/platform.js +16 -3
- package/dist/rum-proxy.d.ts +69 -0
- package/dist/rum-proxy.js +174 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +6 -7
package/dist/env.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* (KV namespaces, service bindings, Durable Object namespaces). The string-valued OTEL_* keys of
|
|
5
5
|
* that object are the standard variables; nothing else is read.
|
|
6
6
|
*/
|
|
7
|
+
import { parseOtlpHeaders } from "@libo11y/core/internal";
|
|
7
8
|
/** Picks the string-valued OTEL_* keys of a Worker's env bindings. Any other key is ignored. */
|
|
8
9
|
export function otelEnv(bindings) {
|
|
9
10
|
const out = {};
|
|
@@ -36,22 +37,5 @@ export function otelEnv(bindings) {
|
|
|
36
37
|
* malformed pair is skipped.
|
|
37
38
|
*/
|
|
38
39
|
export function parseKeyValues(raw) {
|
|
39
|
-
|
|
40
|
-
if (raw === undefined)
|
|
41
|
-
return out;
|
|
42
|
-
for (const pair of raw.split(",")) {
|
|
43
|
-
const eq = pair.indexOf("=");
|
|
44
|
-
if (eq < 0)
|
|
45
|
-
continue;
|
|
46
|
-
try {
|
|
47
|
-
const key = decodeURIComponent(pair.slice(0, eq).trim());
|
|
48
|
-
const value = decodeURIComponent(pair.slice(eq + 1).trim());
|
|
49
|
-
if (key !== "")
|
|
50
|
-
out[key] = value;
|
|
51
|
-
}
|
|
52
|
-
catch {
|
|
53
|
-
// A pair whose percent-encoding is malformed is skipped.
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
return out;
|
|
40
|
+
return parseOtlpHeaders(raw, "standard");
|
|
57
41
|
}
|
package/dist/exporters.d.ts
CHANGED
|
@@ -1,20 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* OTLP/HTTP export over fetch, for each signal core routes to otlp or console.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* write exemplars. Each export has a deadline and can be stopped. An export never throws: a failure
|
|
9
|
-
* is handed to the result callback, where core's export watch reports it.
|
|
10
|
-
*
|
|
11
|
-
* The configuration of each signal is its option, then its OTEL_EXPORTER_OTLP_<SIGNAL>_* variable,
|
|
12
|
-
* then the shared OTEL_EXPORTER_OTLP_* variable, then the default.
|
|
4
|
+
* Configuration resolution, bounded retry (up to 2 retries / 3 total attempts with 200-1000 ms
|
|
5
|
+
* equal jitter capped within the shared export and waitUntil flush deadline), gzip compression,
|
|
6
|
+
* and bounded 2xx partialSuccess inspection all live in @libo11y/core/internal. This module keeps
|
|
7
|
+
* only the thin fetch / Workers VPC binding sender racing against an AbortController timer.
|
|
13
8
|
*/
|
|
14
9
|
import { type ExporterRequest, type ExporterSet } from "@libo11y/core";
|
|
10
|
+
import { type OtlpSignal, type OtlpTemporalityPreference, type RetryTimers } from "@libo11y/core/internal";
|
|
15
11
|
import { type ExportResult } from "@opentelemetry/core";
|
|
16
12
|
import { type ISerializer } from "@opentelemetry/otlp-transformer";
|
|
17
|
-
import {
|
|
13
|
+
import type { OtelEnv } from "./env.ts";
|
|
18
14
|
/** A fetch function: the global fetch, or a binding's, such as `(req) => env.OTLP.fetch(req)`. */
|
|
19
15
|
export type WorkersFetch = (request: Request) => Promise<Response>;
|
|
20
16
|
/** Where and how the exporters send. Each field beats its OTEL_EXPORTER_OTLP_* variable. */
|
|
@@ -49,19 +45,19 @@ export interface WorkersExportConfig {
|
|
|
49
45
|
/** The least time between two metric exports of one isolate, in milliseconds. */
|
|
50
46
|
readonly metricsFlushIntervalMillis: number;
|
|
51
47
|
}
|
|
52
|
-
type SignalName = "traces" | "metrics" | "logs";
|
|
53
48
|
/** One signal's resolved export settings. */
|
|
54
49
|
export interface SignalExport {
|
|
55
50
|
readonly url: string;
|
|
56
51
|
readonly headers: Readonly<Record<string, string>>;
|
|
57
52
|
readonly compression: "gzip" | "none";
|
|
58
53
|
readonly timeoutMillis: number;
|
|
54
|
+
readonly temporalityPreference?: OtlpTemporalityPreference;
|
|
59
55
|
readonly fetch: WorkersFetch;
|
|
60
56
|
}
|
|
61
57
|
/** Appends a signal path to a base URL as the OTLP exporter specification says. */
|
|
62
|
-
export declare function signalUrl(base: string, signal:
|
|
58
|
+
export declare function signalUrl(base: string, signal: OtlpSignal): string;
|
|
63
59
|
/** Resolves one signal's export settings: option, then signal variable, then shared variable, then default. */
|
|
64
|
-
export declare function resolveSignalExport(signal:
|
|
60
|
+
export declare function resolveSignalExport(signal: OtlpSignal, options: WorkersExporterOptions | undefined, env: OtelEnv): SignalExport;
|
|
65
61
|
/** An export that got an HTTP status outside 2xx. */
|
|
66
62
|
export declare class OtlpHttpError extends Error {
|
|
67
63
|
readonly status: number;
|
|
@@ -72,22 +68,24 @@ export declare class OtlpTimeoutError extends Error {
|
|
|
72
68
|
constructor(message: string);
|
|
73
69
|
}
|
|
74
70
|
/**
|
|
75
|
-
* Posts one signal's serialized batches over fetch
|
|
76
|
-
* shutdown() stops what is in flight and fails every later export. Nothing
|
|
77
|
-
* caller.
|
|
71
|
+
* Posts one signal's serialized batches over fetch with bounded retry inside the shared export
|
|
72
|
+
* and flush deadline. shutdown() stops what is in flight and fails every later export. Nothing
|
|
73
|
+
* here throws to the caller.
|
|
78
74
|
*/
|
|
79
75
|
export declare class FetchOtlpExporter<Internal> {
|
|
76
|
+
private readonly signal;
|
|
80
77
|
private readonly settings;
|
|
81
78
|
private readonly contentType;
|
|
82
79
|
private readonly serializer;
|
|
80
|
+
private readonly timers;
|
|
83
81
|
private readonly inFlight;
|
|
84
82
|
private stopped;
|
|
85
|
-
constructor(settings: SignalExport, contentType: string, serializer: ISerializer<Internal, unknown
|
|
83
|
+
constructor(settings: SignalExport, contentType: string, serializer: ISerializer<Internal, unknown>, signal?: OtlpSignal, timers?: RetryTimers);
|
|
86
84
|
export(items: Internal, resultCallback: (result: ExportResult) => void): void;
|
|
87
85
|
private send;
|
|
86
|
+
private attemptSend;
|
|
88
87
|
forceFlush(): Promise<void>;
|
|
89
88
|
shutdown(): Promise<void>;
|
|
90
89
|
}
|
|
91
90
|
/** Builds the exporters for every signal the configuration routes to "otlp" or "console". */
|
|
92
91
|
export declare function buildExporters(req: ExporterRequest, config: WorkersExportConfig): ExporterSet;
|
|
93
|
-
export {};
|
package/dist/exporters.js
CHANGED
|
@@ -1,85 +1,71 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* OTLP/HTTP export over fetch, for each signal core routes to otlp or console.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* write exemplars. Each export has a deadline and can be stopped. An export never throws: a failure
|
|
9
|
-
* is handed to the result callback, where core's export watch reports it.
|
|
10
|
-
*
|
|
11
|
-
* The configuration of each signal is its option, then its OTEL_EXPORTER_OTLP_<SIGNAL>_* variable,
|
|
12
|
-
* then the shared OTEL_EXPORTER_OTLP_* variable, then the default.
|
|
4
|
+
* Configuration resolution, bounded retry (up to 2 retries / 3 total attempts with 200-1000 ms
|
|
5
|
+
* equal jitter capped within the shared export and waitUntil flush deadline), gzip compression,
|
|
6
|
+
* and bounded 2xx partialSuccess inspection all live in @libo11y/core/internal. This module keeps
|
|
7
|
+
* only the thin fetch / Workers VPC binding sender racing against an AbortController timer.
|
|
13
8
|
*/
|
|
14
9
|
import { exemplarMetricExporter, O11yError, OtlpJsonMetricsSerializer, } from "@libo11y/core";
|
|
15
|
-
import { OtlpProtobufMetricsSerializer } from "@libo11y/
|
|
10
|
+
import { OtlpProtobufMetricsSerializer } from "@libo11y/core/edge";
|
|
11
|
+
import { clampTimerMillis, classifyHttpStatus, gzipBytes, inspectPartialSuccess, joinOtlpSignalPath, readBoundedResponseBytes, resolveOtlpSignalConfig, retryOtlpSend, } from "@libo11y/core/internal";
|
|
16
12
|
import { ExportResultCode } from "@opentelemetry/core";
|
|
17
13
|
import { JsonLogsSerializer, JsonTraceSerializer, ProtobufLogsSerializer, ProtobufTraceSerializer, } from "@opentelemetry/otlp-transformer";
|
|
18
14
|
import { ConsoleLogRecordExporter, } from "@opentelemetry/sdk-logs";
|
|
19
15
|
import { AggregationTemporality, ConsoleMetricExporter, InstrumentType, } from "@opentelemetry/sdk-metrics";
|
|
20
16
|
import { ConsoleSpanExporter } from "@opentelemetry/sdk-trace";
|
|
21
|
-
import {
|
|
17
|
+
import { activeFlushContext } from "./flush.js";
|
|
22
18
|
import { FlushMetricReader } from "./metric-reader.js";
|
|
23
19
|
const DEFAULT_ENDPOINT = "http://localhost:4318";
|
|
24
|
-
const DEFAULT_TIMEOUT_MILLIS = 10000;
|
|
25
20
|
const PROTOBUF = "application/x-protobuf";
|
|
26
21
|
const JSON_TYPE = "application/json";
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
22
|
+
const WORKERS_ENV_PROFILE = {
|
|
23
|
+
envKeys: "full",
|
|
24
|
+
urlMode: "standard",
|
|
25
|
+
timeoutParseMode: "strict-uint",
|
|
26
|
+
defaultEndpoint: DEFAULT_ENDPOINT,
|
|
27
|
+
defaultCompression: "none",
|
|
28
|
+
defaultProtocol: "http/protobuf",
|
|
29
|
+
};
|
|
30
|
+
const WORKERS_STATUS_POLICY = {
|
|
31
|
+
retryableStatuses: [429, 502, 503, 504],
|
|
32
|
+
retryAfterStatuses: "all-retryable",
|
|
33
|
+
retryAfterMode: "strict-rfc9110",
|
|
34
|
+
};
|
|
35
|
+
const WORKERS_RETRY_BASE = {
|
|
36
|
+
maxRetries: 2,
|
|
37
|
+
timeoutMode: "shared-deadline",
|
|
38
|
+
initialBackoffMillis: 200,
|
|
39
|
+
maxBackoffMillis: 1000,
|
|
40
|
+
backoffMultiplier: 2,
|
|
41
|
+
jitterMode: "equal-jitter",
|
|
42
|
+
jitterRatio: 0.2,
|
|
43
|
+
retryAfterMode: "override",
|
|
44
|
+
};
|
|
45
|
+
const DEFAULT_RETRY_TIMERS = {
|
|
46
|
+
now: () => Date.now(),
|
|
47
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
48
|
+
clearTimeout: (handle) => clearTimeout(handle),
|
|
49
|
+
random: () => Math.random(),
|
|
50
|
+
};
|
|
51
|
+
function globalFetch(request) {
|
|
52
|
+
return fetch(request);
|
|
34
53
|
}
|
|
35
54
|
/** Appends a signal path to a base URL as the OTLP exporter specification says. */
|
|
36
55
|
export function signalUrl(base, signal) {
|
|
37
|
-
return
|
|
38
|
-
}
|
|
39
|
-
function compressionFrom(value) {
|
|
40
|
-
const v = value?.trim().toLowerCase();
|
|
41
|
-
if (v === "gzip" || v === "none")
|
|
42
|
-
return v;
|
|
43
|
-
return undefined;
|
|
44
|
-
}
|
|
45
|
-
function timeoutFrom(value) {
|
|
46
|
-
if (value === undefined || !/^[0-9]+$/.test(value.trim()))
|
|
47
|
-
return undefined;
|
|
48
|
-
return Number(value.trim());
|
|
49
|
-
}
|
|
50
|
-
function globalFetch(request) {
|
|
51
|
-
return fetch(request);
|
|
56
|
+
return joinOtlpSignalPath(base, signal);
|
|
52
57
|
}
|
|
53
58
|
/** Resolves one signal's export settings: option, then signal variable, then shared variable, then default. */
|
|
54
59
|
export function resolveSignalExport(signal, options, env) {
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
:
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
(base === undefined ? undefined : signalUrl(base, signal)) ??
|
|
64
|
-
envValue(env, `OTEL_EXPORTER_OTLP_${upper}_ENDPOINT`) ??
|
|
65
|
-
signalUrl(envValue(env, "OTEL_EXPORTER_OTLP_ENDPOINT") ?? DEFAULT_ENDPOINT, signal);
|
|
66
|
-
const headers = {
|
|
67
|
-
...parseKeyValues(env.OTEL_EXPORTER_OTLP_HEADERS),
|
|
68
|
-
...parseKeyValues(env[`OTEL_EXPORTER_OTLP_${upper}_HEADERS`]),
|
|
69
|
-
...(options?.headers ?? {}),
|
|
60
|
+
const resolved = resolveOtlpSignalConfig(signal, options ?? {}, env, WORKERS_ENV_PROFILE);
|
|
61
|
+
return {
|
|
62
|
+
url: resolved.url ?? joinOtlpSignalPath(DEFAULT_ENDPOINT, signal),
|
|
63
|
+
headers: resolved.headers,
|
|
64
|
+
compression: resolved.compression,
|
|
65
|
+
timeoutMillis: resolved.timeoutMillis,
|
|
66
|
+
temporalityPreference: resolved.temporalityPreference,
|
|
67
|
+
fetch: options?.fetch ?? globalFetch,
|
|
70
68
|
};
|
|
71
|
-
const compression = compressionFrom(options?.compression) ??
|
|
72
|
-
compressionFrom(env[`OTEL_EXPORTER_OTLP_${upper}_COMPRESSION`]) ??
|
|
73
|
-
compressionFrom(env.OTEL_EXPORTER_OTLP_COMPRESSION) ??
|
|
74
|
-
"none";
|
|
75
|
-
const optionTimeout = options?.timeoutMillis;
|
|
76
|
-
const timeoutMillis = (typeof optionTimeout === "number" && Number.isFinite(optionTimeout) && optionTimeout >= 0
|
|
77
|
-
? optionTimeout
|
|
78
|
-
: undefined) ??
|
|
79
|
-
timeoutFrom(env[`OTEL_EXPORTER_OTLP_${upper}_TIMEOUT`]) ??
|
|
80
|
-
timeoutFrom(env.OTEL_EXPORTER_OTLP_TIMEOUT) ??
|
|
81
|
-
DEFAULT_TIMEOUT_MILLIS;
|
|
82
|
-
return { url, headers, compression, timeoutMillis, fetch: options?.fetch ?? globalFetch };
|
|
83
69
|
}
|
|
84
70
|
/** An export that got an HTTP status outside 2xx. */
|
|
85
71
|
export class OtlpHttpError extends Error {
|
|
@@ -97,30 +83,53 @@ export class OtlpTimeoutError extends Error {
|
|
|
97
83
|
this.name = "TimeoutError";
|
|
98
84
|
}
|
|
99
85
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
86
|
+
function toError(err) {
|
|
87
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
88
|
+
}
|
|
89
|
+
function compressWithin(body, budgetMillis, shutdownSignal, timers) {
|
|
90
|
+
if (shutdownSignal.aborted) {
|
|
91
|
+
return Promise.reject(toError(shutdownSignal.reason ??
|
|
92
|
+
new OtlpTimeoutError("o11y: the exporter shut down before the export finished")));
|
|
93
|
+
}
|
|
94
|
+
let timer;
|
|
95
|
+
let onAbort;
|
|
96
|
+
const bounded = new Promise((_, reject) => {
|
|
97
|
+
onAbort = () => reject(toError(shutdownSignal.reason ??
|
|
98
|
+
new OtlpTimeoutError("o11y: the exporter shut down before the export finished")));
|
|
99
|
+
shutdownSignal.addEventListener("abort", onAbort, { once: true });
|
|
100
|
+
timer = timers.setTimeout(() => {
|
|
101
|
+
reject(new OtlpTimeoutError("o11y: the export did not finish before its deadline"));
|
|
102
|
+
}, clampTimerMillis(budgetMillis));
|
|
103
|
+
});
|
|
104
|
+
return Promise.race([gzipBytes(body), bounded]).finally(() => {
|
|
105
|
+
if (timer !== undefined)
|
|
106
|
+
timers.clearTimeout(timer);
|
|
107
|
+
if (onAbort !== undefined)
|
|
108
|
+
shutdownSignal.removeEventListener("abort", onAbort);
|
|
109
|
+
});
|
|
105
110
|
}
|
|
106
111
|
function failed(error) {
|
|
107
|
-
return { code: ExportResultCode.FAILED, error:
|
|
112
|
+
return { code: ExportResultCode.FAILED, error: toError(error) };
|
|
108
113
|
}
|
|
109
114
|
/**
|
|
110
|
-
* Posts one signal's serialized batches over fetch
|
|
111
|
-
* shutdown() stops what is in flight and fails every later export. Nothing
|
|
112
|
-
* caller.
|
|
115
|
+
* Posts one signal's serialized batches over fetch with bounded retry inside the shared export
|
|
116
|
+
* and flush deadline. shutdown() stops what is in flight and fails every later export. Nothing
|
|
117
|
+
* here throws to the caller.
|
|
113
118
|
*/
|
|
114
119
|
export class FetchOtlpExporter {
|
|
120
|
+
signal;
|
|
115
121
|
settings;
|
|
116
122
|
contentType;
|
|
117
123
|
serializer;
|
|
124
|
+
timers;
|
|
118
125
|
inFlight = new Set();
|
|
119
126
|
stopped = false;
|
|
120
|
-
constructor(settings, contentType, serializer) {
|
|
127
|
+
constructor(settings, contentType, serializer, signal = "traces", timers) {
|
|
128
|
+
this.signal = signal;
|
|
121
129
|
this.settings = settings;
|
|
122
130
|
this.contentType = contentType;
|
|
123
131
|
this.serializer = serializer;
|
|
132
|
+
this.timers = timers ?? DEFAULT_RETRY_TIMERS;
|
|
124
133
|
}
|
|
125
134
|
export(items, resultCallback) {
|
|
126
135
|
if (this.stopped) {
|
|
@@ -143,38 +152,142 @@ export class FetchOtlpExporter {
|
|
|
143
152
|
}
|
|
144
153
|
async send(body) {
|
|
145
154
|
const { url, headers, compression, timeoutMillis, fetch: send } = this.settings;
|
|
155
|
+
const timers = this.timers;
|
|
156
|
+
const startedAt = timers.now();
|
|
157
|
+
const flushCtx = activeFlushContext();
|
|
158
|
+
const remainingFlush = flushCtx !== undefined ? Math.max(0, flushCtx.deadlineAt - startedAt) : Number.POSITIVE_INFINITY;
|
|
159
|
+
const initialBudget = Math.min(timeoutMillis, remainingFlush);
|
|
160
|
+
if (initialBudget <= 0) {
|
|
161
|
+
throw new OtlpTimeoutError("o11y: the export did not finish before its deadline");
|
|
162
|
+
}
|
|
163
|
+
const deadlineAt = startedAt + initialBudget;
|
|
146
164
|
const controller = new AbortController();
|
|
147
165
|
this.inFlight.add(controller);
|
|
148
|
-
const timer = setTimeout(() => controller.abort(new OtlpTimeoutError("o11y: the export did not finish before its deadline")), timeoutMillis);
|
|
149
166
|
try {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
167
|
+
let payload = body;
|
|
168
|
+
let compressed = false;
|
|
169
|
+
if (compression === "gzip") {
|
|
170
|
+
const gz = await compressWithin(body, initialBudget, controller.signal, timers);
|
|
171
|
+
if (gz !== undefined) {
|
|
172
|
+
payload = gz;
|
|
173
|
+
compressed = true;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
if (controller.signal.aborted) {
|
|
177
|
+
throw toError(controller.signal.reason ??
|
|
178
|
+
new OtlpTimeoutError("o11y: the exporter shut down before the export finished"));
|
|
179
|
+
}
|
|
180
|
+
const budgetMillis = deadlineAt - timers.now();
|
|
181
|
+
if (budgetMillis <= 0) {
|
|
182
|
+
throw new OtlpTimeoutError("o11y: the export did not finish before its deadline");
|
|
183
|
+
}
|
|
184
|
+
const baseHeaders = new Headers(headers);
|
|
185
|
+
baseHeaders.set("content-type", this.contentType);
|
|
186
|
+
if (compressed)
|
|
187
|
+
baseHeaders.set("content-encoding", "gzip");
|
|
188
|
+
else
|
|
189
|
+
baseHeaders.delete("content-encoding");
|
|
190
|
+
const result = await retryOtlpSend((remainingMillis) => this.attemptSend(send, url, baseHeaders, payload, remainingMillis, controller.signal, timers), {
|
|
191
|
+
...WORKERS_RETRY_BASE,
|
|
192
|
+
timeoutMillis: budgetMillis,
|
|
193
|
+
timers,
|
|
194
|
+
abortedError: () => toError(controller.signal.reason ??
|
|
195
|
+
new OtlpTimeoutError("o11y: the exporter shut down before the export finished")),
|
|
196
|
+
}, controller.signal);
|
|
197
|
+
if (result.status !== "success") {
|
|
198
|
+
throw result.error ?? new Error("o11y: OTLP export failed");
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
this.inFlight.delete(controller);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
async attemptSend(send, url, baseHeaders, payload, remainingMillis, shutdownSignal, timers) {
|
|
206
|
+
if (shutdownSignal.aborted) {
|
|
207
|
+
return {
|
|
208
|
+
status: "failure",
|
|
209
|
+
error: toError(shutdownSignal.reason ??
|
|
210
|
+
new OtlpTimeoutError("o11y: the exporter shut down before the export finished")),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
if (remainingMillis <= 0) {
|
|
214
|
+
return {
|
|
215
|
+
status: "failure",
|
|
216
|
+
error: new OtlpTimeoutError("o11y: the export did not finish before its deadline"),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
const attemptController = new AbortController();
|
|
220
|
+
const onShutdown = () => {
|
|
221
|
+
attemptController.abort(shutdownSignal.reason ??
|
|
222
|
+
new OtlpTimeoutError("o11y: the exporter shut down before the export finished"));
|
|
223
|
+
};
|
|
224
|
+
shutdownSignal.addEventListener("abort", onShutdown, { once: true });
|
|
225
|
+
let timedOut = false;
|
|
226
|
+
const timer = timers.setTimeout(() => {
|
|
227
|
+
timedOut = true;
|
|
228
|
+
attemptController.abort(new OtlpTimeoutError("o11y: the export did not finish before its deadline"));
|
|
229
|
+
}, clampTimerMillis(remainingMillis));
|
|
230
|
+
try {
|
|
155
231
|
const request = new Request(url, {
|
|
156
232
|
method: "POST",
|
|
157
|
-
headers:
|
|
233
|
+
headers: new Headers(baseHeaders),
|
|
158
234
|
body: payload,
|
|
159
|
-
signal:
|
|
235
|
+
signal: attemptController.signal,
|
|
160
236
|
});
|
|
161
237
|
const aborted = new Promise((_, reject) => {
|
|
162
|
-
|
|
238
|
+
if (attemptController.signal.aborted) {
|
|
239
|
+
reject(attemptController.signal.reason);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
attemptController.signal.addEventListener("abort", () => reject(attemptController.signal.reason), {
|
|
243
|
+
once: true,
|
|
244
|
+
});
|
|
163
245
|
});
|
|
164
|
-
|
|
165
|
-
|
|
246
|
+
let response;
|
|
247
|
+
try {
|
|
248
|
+
// A binding's fetch may not honor the signal, so the deadline also races it.
|
|
249
|
+
response = await Promise.race([Promise.resolve().then(() => send(request)), aborted]);
|
|
250
|
+
}
|
|
251
|
+
catch (err) {
|
|
252
|
+
if (shutdownSignal.aborted) {
|
|
253
|
+
return { status: "failure", error: toError(shutdownSignal.reason ?? err) };
|
|
254
|
+
}
|
|
255
|
+
if (timedOut || attemptController.signal.aborted) {
|
|
256
|
+
return {
|
|
257
|
+
status: "failure",
|
|
258
|
+
error: attemptController.signal.reason instanceof Error
|
|
259
|
+
? attemptController.signal.reason
|
|
260
|
+
: new OtlpTimeoutError("o11y: the export did not finish before its deadline"),
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
return { status: "retryable", error: toError(err) };
|
|
264
|
+
}
|
|
265
|
+
const classification = classifyHttpStatus(response.status, response.headers.get("retry-after"), WORKERS_STATUS_POLICY, timers.now());
|
|
266
|
+
if (classification.kind === "ok") {
|
|
267
|
+
const bytes = await Promise.race([
|
|
268
|
+
readBoundedResponseBytes(response),
|
|
269
|
+
aborted.catch(() => undefined),
|
|
270
|
+
]);
|
|
271
|
+
inspectPartialSuccess(this.signal, response.status, bytes, this.serializer);
|
|
272
|
+
return { status: "success" };
|
|
273
|
+
}
|
|
274
|
+
// Release the unread error body asynchronously so a slow or hanging cancel() never stalls
|
|
275
|
+
// retry classification or consumes the remaining retry budget.
|
|
166
276
|
try {
|
|
167
|
-
|
|
277
|
+
void response.body?.cancel().catch(() => { });
|
|
168
278
|
}
|
|
169
279
|
catch {
|
|
170
280
|
// The body is not needed; a failure to release it changes nothing.
|
|
171
281
|
}
|
|
172
|
-
|
|
173
|
-
|
|
282
|
+
const httpError = new OtlpHttpError(response.status);
|
|
283
|
+
if (classification.kind === "retry") {
|
|
284
|
+
return { status: "retryable", retryInMillis: classification.retryAfterMillis, error: httpError };
|
|
285
|
+
}
|
|
286
|
+
return { status: "failure", error: httpError };
|
|
174
287
|
}
|
|
175
288
|
finally {
|
|
176
|
-
clearTimeout(timer);
|
|
177
|
-
|
|
289
|
+
timers.clearTimeout(timer);
|
|
290
|
+
shutdownSignal.removeEventListener("abort", onShutdown);
|
|
178
291
|
}
|
|
179
292
|
}
|
|
180
293
|
forceFlush() {
|
|
@@ -195,7 +308,7 @@ export class FetchOtlpExporter {
|
|
|
195
308
|
class FetchOtlpMetricExporter extends FetchOtlpExporter {
|
|
196
309
|
preference;
|
|
197
310
|
constructor(settings, contentType, serializer, preference) {
|
|
198
|
-
super(settings, contentType, serializer);
|
|
311
|
+
super(settings, contentType, serializer, "metrics");
|
|
199
312
|
this.preference = preference;
|
|
200
313
|
}
|
|
201
314
|
selectAggregationTemporality(instrumentType) {
|
|
@@ -214,10 +327,6 @@ class FetchOtlpMetricExporter extends FetchOtlpExporter {
|
|
|
214
327
|
}
|
|
215
328
|
}
|
|
216
329
|
}
|
|
217
|
-
function temporalityPreference(env) {
|
|
218
|
-
const v = envValue(env, "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE")?.toLowerCase();
|
|
219
|
-
return v === "delta" || v === "lowmemory" ? v : "cumulative";
|
|
220
|
-
}
|
|
221
330
|
// build runs a constructor and reports a failure as Go's "o11y: building <kind>: %w".
|
|
222
331
|
function build(kind, fn) {
|
|
223
332
|
try {
|
|
@@ -235,7 +344,7 @@ function spanExporter(req, config) {
|
|
|
235
344
|
return undefined;
|
|
236
345
|
return build("span exporter", () => {
|
|
237
346
|
const json = protocol.traces === "http/json";
|
|
238
|
-
return new FetchOtlpExporter(resolveSignalExport("traces", config.exporter, config.env), json ? JSON_TYPE : PROTOBUF, json ? JsonTraceSerializer : ProtobufTraceSerializer);
|
|
347
|
+
return new FetchOtlpExporter(resolveSignalExport("traces", config.exporter, config.env), json ? JSON_TYPE : PROTOBUF, json ? JsonTraceSerializer : ProtobufTraceSerializer, "traces");
|
|
239
348
|
});
|
|
240
349
|
}
|
|
241
350
|
function logExporter(req, config) {
|
|
@@ -246,7 +355,7 @@ function logExporter(req, config) {
|
|
|
246
355
|
return undefined;
|
|
247
356
|
return build("log exporter", () => {
|
|
248
357
|
const json = protocol.logs === "http/json";
|
|
249
|
-
return new FetchOtlpExporter(resolveSignalExport("logs", config.exporter, config.env), json ? JSON_TYPE : PROTOBUF, json ? JsonLogsSerializer : ProtobufLogsSerializer);
|
|
358
|
+
return new FetchOtlpExporter(resolveSignalExport("logs", config.exporter, config.env), json ? JSON_TYPE : PROTOBUF, json ? JsonLogsSerializer : ProtobufLogsSerializer, "logs");
|
|
250
359
|
});
|
|
251
360
|
}
|
|
252
361
|
function metricReader(req, config) {
|
|
@@ -255,11 +364,13 @@ function metricReader(req, config) {
|
|
|
255
364
|
return undefined;
|
|
256
365
|
return build("metric reader", () => {
|
|
257
366
|
const json = protocol.metrics === "http/json";
|
|
367
|
+
const resolved = metrics === "otlp" ? resolveSignalExport("metrics", config.exporter, config.env) : undefined;
|
|
258
368
|
const inner = metrics === "console"
|
|
259
369
|
? new ConsoleMetricExporter({ temporalitySelector: () => AggregationTemporality.CUMULATIVE })
|
|
260
|
-
: new FetchOtlpMetricExporter(
|
|
370
|
+
: new FetchOtlpMetricExporter(resolved, json ? JSON_TYPE : PROTOBUF, json ? OtlpJsonMetricsSerializer : OtlpProtobufMetricsSerializer, resolved?.temporalityPreference ?? "cumulative");
|
|
261
371
|
return new FlushMetricReader({
|
|
262
372
|
exporter: exemplarMetricExporter(inner, req.exemplars),
|
|
373
|
+
exemplars: req.exemplars,
|
|
263
374
|
intervalMillis: config.metricsFlushIntervalMillis,
|
|
264
375
|
timeoutMillis: metricExport.timeoutMillis,
|
|
265
376
|
});
|
package/dist/flush.d.ts
CHANGED
|
@@ -1,19 +1,34 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Flushing after an invocation. A Worker invocation ends when its response is sent, and work it
|
|
3
|
-
* started is cancelled unless the invocation hands it to waitUntil. An ExecutionContext and a
|
|
4
|
-
* DurableObjectState both have waitUntil, so one helper serves Workers and Durable Objects.
|
|
5
|
-
*/
|
|
6
1
|
import type { LifecycleOptions, SignalReport, Telemetry } from "@libo11y/core";
|
|
7
2
|
/** What has waitUntil: a Worker's ExecutionContext or a Durable Object's DurableObjectState. */
|
|
8
3
|
export interface WaitUntil {
|
|
9
4
|
/** Keeps the invocation alive until promise settles. */
|
|
10
5
|
waitUntil(promise: Promise<unknown>): void;
|
|
11
6
|
}
|
|
7
|
+
/** Options for {@link scheduleFlush}. */
|
|
8
|
+
export interface WorkersFlushOptions extends LifecycleOptions {
|
|
9
|
+
/**
|
|
10
|
+
* When true, bypasses the isolate's metricsFlushIntervalMillis throttle for this flush so
|
|
11
|
+
* changed cumulative metrics (or DELTA snapshots) are collected and exported within this
|
|
12
|
+
* invocation. Queue and scheduled handlers in instrument() enable this automatically so mixed
|
|
13
|
+
* Workers do not lose queue or cron counts to the fetch throttle.
|
|
14
|
+
*/
|
|
15
|
+
readonly forceMetrics?: boolean;
|
|
16
|
+
}
|
|
17
|
+
/** Per-flush context propagated via AsyncLocalStorage to FlushMetricReader and OTLP exporters. */
|
|
18
|
+
export interface FlushContext {
|
|
19
|
+
readonly forceMetrics: boolean;
|
|
20
|
+
readonly deadlineAt: number;
|
|
21
|
+
}
|
|
22
|
+
/** Returns the active flush context for the current async execution, if any. */
|
|
23
|
+
export declare function activeFlushContext(): FlushContext | undefined;
|
|
24
|
+
/** Runs fn inside an explicit FlushContext. */
|
|
25
|
+
export declare function withFlushContext<T>(ctx: FlushContext, fn: () => T): T;
|
|
12
26
|
/**
|
|
13
27
|
* Flushes telemetry after the invocation, through ctx.waitUntil, so the export outlives the
|
|
14
|
-
* response. Traces and logs export on every flush; metrics
|
|
15
|
-
* metricsFlushIntervalMillis has passed
|
|
16
|
-
* (options.timeoutMillis, default 5000 ms)
|
|
17
|
-
*
|
|
28
|
+
* response. Traces and logs export on every flush; metrics export when changed (or when the
|
|
29
|
+
* platform's metricsFlushIntervalMillis has passed, or when options.forceMetrics is true). The
|
|
30
|
+
* flush has core's deadline (options.timeoutMillis, default 5000 ms), which also caps OTLP
|
|
31
|
+
* exporter retries. telemetry may be a promise, such as setup's. Returns the flush, which never
|
|
32
|
+
* rejects, for a caller that wants to wait for it.
|
|
18
33
|
*/
|
|
19
|
-
export declare function scheduleFlush(ctx: WaitUntil, telemetry: Telemetry | Promise<Telemetry>, options?:
|
|
34
|
+
export declare function scheduleFlush(ctx: WaitUntil, telemetry: Telemetry | Promise<Telemetry>, options?: WorkersFlushOptions): Promise<SignalReport>;
|
package/dist/flush.js
CHANGED
|
@@ -1,12 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flushing after an invocation. A Worker invocation ends when its response is sent, and work it
|
|
3
|
+
* started is cancelled unless the invocation hands it to waitUntil. An ExecutionContext and a
|
|
4
|
+
* DurableObjectState both have waitUntil, so one helper serves Workers and Durable Objects.
|
|
5
|
+
*/
|
|
6
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
7
|
+
import { clampTimerMillis } from "@libo11y/core/internal";
|
|
8
|
+
const DEFAULT_FLUSH_TIMEOUT_MILLIS = 5000;
|
|
9
|
+
const flushContextStorage = new AsyncLocalStorage();
|
|
10
|
+
/** Returns the active flush context for the current async execution, if any. */
|
|
11
|
+
export function activeFlushContext() {
|
|
12
|
+
return flushContextStorage.getStore();
|
|
13
|
+
}
|
|
14
|
+
/** Runs fn inside an explicit FlushContext. */
|
|
15
|
+
export function withFlushContext(ctx, fn) {
|
|
16
|
+
return flushContextStorage.run(ctx, fn);
|
|
17
|
+
}
|
|
18
|
+
function resolveFlushTimeout(given) {
|
|
19
|
+
const ms = typeof given === "string" && given.trim() !== "" ? Number(given) : given;
|
|
20
|
+
if (typeof ms !== "number" || Number.isNaN(ms))
|
|
21
|
+
return DEFAULT_FLUSH_TIMEOUT_MILLIS;
|
|
22
|
+
return clampTimerMillis(ms);
|
|
23
|
+
}
|
|
1
24
|
/**
|
|
2
25
|
* Flushes telemetry after the invocation, through ctx.waitUntil, so the export outlives the
|
|
3
|
-
* response. Traces and logs export on every flush; metrics
|
|
4
|
-
* metricsFlushIntervalMillis has passed
|
|
5
|
-
* (options.timeoutMillis, default 5000 ms)
|
|
6
|
-
*
|
|
26
|
+
* response. Traces and logs export on every flush; metrics export when changed (or when the
|
|
27
|
+
* platform's metricsFlushIntervalMillis has passed, or when options.forceMetrics is true). The
|
|
28
|
+
* flush has core's deadline (options.timeoutMillis, default 5000 ms), which also caps OTLP
|
|
29
|
+
* exporter retries. telemetry may be a promise, such as setup's. Returns the flush, which never
|
|
30
|
+
* rejects, for a caller that wants to wait for it.
|
|
7
31
|
*/
|
|
8
32
|
export function scheduleFlush(ctx, telemetry, options) {
|
|
9
|
-
const
|
|
33
|
+
const forceMetrics = options?.forceMetrics === true;
|
|
34
|
+
const timeoutMillis = resolveFlushTimeout(options?.timeoutMillis);
|
|
35
|
+
const lifecycleOpts = options?.timeoutMillis === undefined ? undefined : { timeoutMillis: options.timeoutMillis };
|
|
36
|
+
const flushing = Promise.resolve(telemetry).then((t) => flushContextStorage.run({ forceMetrics, deadlineAt: Date.now() + timeoutMillis }, () => t.forceFlush(lifecycleOpts)), (error) => ({ ok: false, errors: [{ signal: "lifecycle", error }] }));
|
|
10
37
|
try {
|
|
11
38
|
ctx.waitUntil(flushing);
|
|
12
39
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The libo11y platform for Cloudflare Workers and Durable Objects (workerd): setup memoized per
|
|
3
|
-
* isolate, OTLP/HTTP export over fetch or a binding's fetch, the
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* isolate, OTLP/HTTP export with bounded retry over fetch or a binding's fetch, the
|
|
4
|
+
* AsyncLocalStorage context, dirty-aware snapshot-diffing metrics exported on flush, flushing
|
|
5
|
+
* through waitUntil, composable Workers/DO/alarm/scheduled/queue tracing primitives, and the
|
|
6
|
+
* authenticated RUM gateway proxy helper. Needs the nodejs_compat (or nodejs_als) flag for
|
|
7
|
+
* node:async_hooks.
|
|
6
8
|
*/
|
|
7
|
-
export { type LifecycleOptions, type Logger, O11yError, type O11yErrorCode, type SignalReport, type Telemetry, type TelemetryOptions, } from "@libo11y/core";
|
|
8
|
-
export { type FetchOptions, instrumentFetch, instrumentServe, type ServeOptions, setRoute, } from "@libo11y/
|
|
9
|
+
export { type Carrier, type LifecycleOptions, type Logger, O11yError, type O11yErrorCode, type SignalReport, type Telemetry, type TelemetryOptions, } from "@libo11y/core";
|
|
10
|
+
export { type AttachQueueCarrierOptions, attachQueueCarrier, type BatchQueueMessagesOptions, batchQueueMessages, DEFAULT_CARRIER_FIELD, DEFAULT_QUEUE_BATCH_MAX_BYTES, DEFAULT_QUEUE_MESSAGE_MAX_BYTES, type ExtractQueueCarrierOptions, extractQueueCarrier, type FetchOptions, instrumentFetch, instrumentServe, type ServeOptions, setRoute, } from "@libo11y/core/edge";
|
|
11
|
+
export { enrichDurableObjectSpan, type TraceAlarmOptions, type TraceQueueBatchOptions, type TraceScheduledOptions, type TraceSpanOptions, traceAlarm, traceDurableObjectCall, traceDurableObjectMethod, traceDurableObjectMethods, traceDurableObjectStub, traceQueueBatch, traceScheduled, type WorkerMessageBatch, type WorkerScheduledController, } from "./adapters.ts";
|
|
9
12
|
export { createContextManager } from "./context.ts";
|
|
10
13
|
export type { WorkersExporterOptions, WorkersFetch } from "./exporters.ts";
|
|
11
|
-
export { scheduleFlush, type WaitUntil } from "./flush.ts";
|
|
12
|
-
export { type InstrumentOptions, instrument, type WorkerHandler
|
|
13
|
-
export { DEFAULT_METRICS_FLUSH_INTERVAL_MILLIS, type WorkersPlatformOptions, workersPlatform, } from "./platform.ts";
|
|
14
|
+
export { scheduleFlush, type WaitUntil, type WorkersFlushOptions } from "./flush.ts";
|
|
15
|
+
export { type InstrumentOptions, instrument, type WorkerHandler } from "./instrument.ts";
|
|
16
|
+
export { DEFAULT_INSTRUMENT_METRICS_FLUSH_INTERVAL_MILLIS, DEFAULT_METRICS_FLUSH_INTERVAL_MILLIS, type WorkersPlatformOptions, workersPlatform, } from "./platform.ts";
|
|
17
|
+
export { buildRumUpstreamRequest, createRumProxy, DEFAULT_RUM_PROXY_PREFIX, DEFAULT_TRUSTED_EDGE_HEADER, isRumProxyPath, proxyRum, type RumProxyOptions, type RumTrustedEdgeOptions, } from "./rum-proxy.ts";
|
|
14
18
|
export { createTelemetry, setup, type WorkersOptions } from "./setup.ts";
|
|
15
19
|
export { VERSION } from "./version.ts";
|