@libo11y/workers 0.0.0-stage → 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/LICENSE +202 -0
- package/README.md +316 -2
- package/dist/adapters.d.ts +102 -0
- package/dist/adapters.js +282 -0
- package/dist/context.d.ts +3 -0
- package/dist/context.js +50 -0
- package/dist/env.d.ts +10 -0
- package/dist/env.js +41 -0
- package/dist/exporters.d.ts +91 -0
- package/dist/exporters.js +389 -0
- package/dist/flush.d.ts +34 -0
- package/dist/flush.js +44 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +18 -0
- package/dist/instrument.d.ts +73 -0
- package/dist/instrument.js +116 -0
- package/dist/log-processor.d.ts +23 -0
- package/dist/log-processor.js +157 -0
- package/dist/metric-reader.d.ts +45 -0
- package/dist/metric-reader.js +242 -0
- package/dist/platform.d.ts +40 -0
- package/dist/platform.js +44 -0
- package/dist/resource.d.ts +17 -0
- package/dist/resource.js +30 -0
- package/dist/rum-proxy.d.ts +69 -0
- package/dist/rum-proxy.js +174 -0
- package/dist/setup.d.ts +29 -0
- package/dist/setup.js +69 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/package.json +46 -4
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OTLP/HTTP export over fetch, for each signal core routes to otlp or console.
|
|
3
|
+
*
|
|
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.
|
|
8
|
+
*/
|
|
9
|
+
import { exemplarMetricExporter, O11yError, OtlpJsonMetricsSerializer, } from "@libo11y/core";
|
|
10
|
+
import { OtlpProtobufMetricsSerializer } from "@libo11y/core/edge";
|
|
11
|
+
import { clampTimerMillis, classifyHttpStatus, gzipBytes, inspectPartialSuccess, joinOtlpSignalPath, readBoundedResponseBytes, resolveOtlpSignalConfig, retryOtlpSend, } from "@libo11y/core/internal";
|
|
12
|
+
import { ExportResultCode } from "@opentelemetry/core";
|
|
13
|
+
import { JsonLogsSerializer, JsonTraceSerializer, ProtobufLogsSerializer, ProtobufTraceSerializer, } from "@opentelemetry/otlp-transformer";
|
|
14
|
+
import { ConsoleLogRecordExporter, } from "@opentelemetry/sdk-logs";
|
|
15
|
+
import { AggregationTemporality, ConsoleMetricExporter, InstrumentType, } from "@opentelemetry/sdk-metrics";
|
|
16
|
+
import { ConsoleSpanExporter } from "@opentelemetry/sdk-trace";
|
|
17
|
+
import { activeFlushContext } from "./flush.js";
|
|
18
|
+
import { FlushMetricReader } from "./metric-reader.js";
|
|
19
|
+
const DEFAULT_ENDPOINT = "http://localhost:4318";
|
|
20
|
+
const PROTOBUF = "application/x-protobuf";
|
|
21
|
+
const JSON_TYPE = "application/json";
|
|
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);
|
|
53
|
+
}
|
|
54
|
+
/** Appends a signal path to a base URL as the OTLP exporter specification says. */
|
|
55
|
+
export function signalUrl(base, signal) {
|
|
56
|
+
return joinOtlpSignalPath(base, signal);
|
|
57
|
+
}
|
|
58
|
+
/** Resolves one signal's export settings: option, then signal variable, then shared variable, then default. */
|
|
59
|
+
export function resolveSignalExport(signal, options, env) {
|
|
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,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** An export that got an HTTP status outside 2xx. */
|
|
71
|
+
export class OtlpHttpError extends Error {
|
|
72
|
+
status;
|
|
73
|
+
constructor(status) {
|
|
74
|
+
super(`OTLP export failed with HTTP status ${status}`);
|
|
75
|
+
this.name = "OtlpHttpError";
|
|
76
|
+
this.status = status;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** An export that did not finish before its deadline, or was stopped by shutdown. */
|
|
80
|
+
export class OtlpTimeoutError extends Error {
|
|
81
|
+
constructor(message) {
|
|
82
|
+
super(message);
|
|
83
|
+
this.name = "TimeoutError";
|
|
84
|
+
}
|
|
85
|
+
}
|
|
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
|
+
});
|
|
110
|
+
}
|
|
111
|
+
function failed(error) {
|
|
112
|
+
return { code: ExportResultCode.FAILED, error: toError(error) };
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
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.
|
|
118
|
+
*/
|
|
119
|
+
export class FetchOtlpExporter {
|
|
120
|
+
signal;
|
|
121
|
+
settings;
|
|
122
|
+
contentType;
|
|
123
|
+
serializer;
|
|
124
|
+
timers;
|
|
125
|
+
inFlight = new Set();
|
|
126
|
+
stopped = false;
|
|
127
|
+
constructor(settings, contentType, serializer, signal = "traces", timers) {
|
|
128
|
+
this.signal = signal;
|
|
129
|
+
this.settings = settings;
|
|
130
|
+
this.contentType = contentType;
|
|
131
|
+
this.serializer = serializer;
|
|
132
|
+
this.timers = timers ?? DEFAULT_RETRY_TIMERS;
|
|
133
|
+
}
|
|
134
|
+
export(items, resultCallback) {
|
|
135
|
+
if (this.stopped) {
|
|
136
|
+
resultCallback(failed(new Error("o11y: the exporter is shut down")));
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
let body;
|
|
140
|
+
try {
|
|
141
|
+
body = this.serializer.serializeRequest(items);
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
resultCallback(failed(err));
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (body === undefined) {
|
|
148
|
+
resultCallback(failed(new Error("o11y: the batch could not be serialized")));
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
this.send(body).then(() => resultCallback({ code: ExportResultCode.SUCCESS }), (err) => resultCallback(failed(err)));
|
|
152
|
+
}
|
|
153
|
+
async send(body) {
|
|
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;
|
|
164
|
+
const controller = new AbortController();
|
|
165
|
+
this.inFlight.add(controller);
|
|
166
|
+
try {
|
|
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 {
|
|
231
|
+
const request = new Request(url, {
|
|
232
|
+
method: "POST",
|
|
233
|
+
headers: new Headers(baseHeaders),
|
|
234
|
+
body: payload,
|
|
235
|
+
signal: attemptController.signal,
|
|
236
|
+
});
|
|
237
|
+
const aborted = new Promise((_, reject) => {
|
|
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
|
+
});
|
|
245
|
+
});
|
|
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.
|
|
276
|
+
try {
|
|
277
|
+
void response.body?.cancel().catch(() => { });
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
// The body is not needed; a failure to release it changes nothing.
|
|
281
|
+
}
|
|
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 };
|
|
287
|
+
}
|
|
288
|
+
finally {
|
|
289
|
+
timers.clearTimeout(timer);
|
|
290
|
+
shutdownSignal.removeEventListener("abort", onShutdown);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
forceFlush() {
|
|
294
|
+
return Promise.resolve();
|
|
295
|
+
}
|
|
296
|
+
shutdown() {
|
|
297
|
+
this.stopped = true;
|
|
298
|
+
for (const controller of this.inFlight) {
|
|
299
|
+
controller.abort(new OtlpTimeoutError("o11y: the exporter shut down before the export finished"));
|
|
300
|
+
}
|
|
301
|
+
return Promise.resolve();
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* The OTLP metric exporter: CUMULATIVE temporality, which Prometheus' OTLP receiver requires,
|
|
306
|
+
* unless OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE says delta or lowmemory.
|
|
307
|
+
*/
|
|
308
|
+
class FetchOtlpMetricExporter extends FetchOtlpExporter {
|
|
309
|
+
preference;
|
|
310
|
+
constructor(settings, contentType, serializer, preference) {
|
|
311
|
+
super(settings, contentType, serializer, "metrics");
|
|
312
|
+
this.preference = preference;
|
|
313
|
+
}
|
|
314
|
+
selectAggregationTemporality(instrumentType) {
|
|
315
|
+
if (this.preference === "cumulative")
|
|
316
|
+
return AggregationTemporality.CUMULATIVE;
|
|
317
|
+
switch (instrumentType) {
|
|
318
|
+
case InstrumentType.COUNTER:
|
|
319
|
+
case InstrumentType.OBSERVABLE_COUNTER:
|
|
320
|
+
case InstrumentType.HISTOGRAM:
|
|
321
|
+
return AggregationTemporality.DELTA;
|
|
322
|
+
case InstrumentType.OBSERVABLE_GAUGE:
|
|
323
|
+
case InstrumentType.GAUGE:
|
|
324
|
+
return this.preference === "delta" ? AggregationTemporality.DELTA : AggregationTemporality.CUMULATIVE;
|
|
325
|
+
default:
|
|
326
|
+
return AggregationTemporality.CUMULATIVE;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
// build runs a constructor and reports a failure as Go's "o11y: building <kind>: %w".
|
|
331
|
+
function build(kind, fn) {
|
|
332
|
+
try {
|
|
333
|
+
return fn();
|
|
334
|
+
}
|
|
335
|
+
catch (err) {
|
|
336
|
+
throw new O11yError("EXPORTER", `o11y: building ${kind}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
function spanExporter(req, config) {
|
|
340
|
+
const { traces, protocol } = req.config;
|
|
341
|
+
if (traces === "console")
|
|
342
|
+
return new ConsoleSpanExporter();
|
|
343
|
+
if (traces !== "otlp")
|
|
344
|
+
return undefined;
|
|
345
|
+
return build("span exporter", () => {
|
|
346
|
+
const json = protocol.traces === "http/json";
|
|
347
|
+
return new FetchOtlpExporter(resolveSignalExport("traces", config.exporter, config.env), json ? JSON_TYPE : PROTOBUF, json ? JsonTraceSerializer : ProtobufTraceSerializer, "traces");
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
function logExporter(req, config) {
|
|
351
|
+
const { logs, protocol } = req.config;
|
|
352
|
+
if (logs === "console")
|
|
353
|
+
return new ConsoleLogRecordExporter();
|
|
354
|
+
if (logs !== "otlp")
|
|
355
|
+
return undefined;
|
|
356
|
+
return build("log exporter", () => {
|
|
357
|
+
const json = protocol.logs === "http/json";
|
|
358
|
+
return new FetchOtlpExporter(resolveSignalExport("logs", config.exporter, config.env), json ? JSON_TYPE : PROTOBUF, json ? JsonLogsSerializer : ProtobufLogsSerializer, "logs");
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
function metricReader(req, config) {
|
|
362
|
+
const { metrics, protocol, metricExport } = req.config;
|
|
363
|
+
if (metrics !== "otlp" && metrics !== "console")
|
|
364
|
+
return undefined;
|
|
365
|
+
return build("metric reader", () => {
|
|
366
|
+
const json = protocol.metrics === "http/json";
|
|
367
|
+
const resolved = metrics === "otlp" ? resolveSignalExport("metrics", config.exporter, config.env) : undefined;
|
|
368
|
+
const inner = metrics === "console"
|
|
369
|
+
? new ConsoleMetricExporter({ temporalitySelector: () => AggregationTemporality.CUMULATIVE })
|
|
370
|
+
: new FetchOtlpMetricExporter(resolved, json ? JSON_TYPE : PROTOBUF, json ? OtlpJsonMetricsSerializer : OtlpProtobufMetricsSerializer, resolved?.temporalityPreference ?? "cumulative");
|
|
371
|
+
return new FlushMetricReader({
|
|
372
|
+
exporter: exemplarMetricExporter(inner, req.exemplars),
|
|
373
|
+
exemplars: req.exemplars,
|
|
374
|
+
intervalMillis: config.metricsFlushIntervalMillis,
|
|
375
|
+
timeoutMillis: metricExport.timeoutMillis,
|
|
376
|
+
});
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
/** Builds the exporters for every signal the configuration routes to "otlp" or "console". */
|
|
380
|
+
export function buildExporters(req, config) {
|
|
381
|
+
const spans = spanExporter(req, config);
|
|
382
|
+
const reader = metricReader(req, config);
|
|
383
|
+
const logs = logExporter(req, config);
|
|
384
|
+
return {
|
|
385
|
+
...(spans === undefined ? {} : { spanExporter: spans }),
|
|
386
|
+
...(reader === undefined ? {} : { metricReader: reader }),
|
|
387
|
+
...(logs === undefined ? {} : { logExporter: logs }),
|
|
388
|
+
};
|
|
389
|
+
}
|
package/dist/flush.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { LifecycleOptions, SignalReport, Telemetry } from "@libo11y/core";
|
|
2
|
+
/** What has waitUntil: a Worker's ExecutionContext or a Durable Object's DurableObjectState. */
|
|
3
|
+
export interface WaitUntil {
|
|
4
|
+
/** Keeps the invocation alive until promise settles. */
|
|
5
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
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;
|
|
26
|
+
/**
|
|
27
|
+
* Flushes telemetry after the invocation, through ctx.waitUntil, so the export outlives the
|
|
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.
|
|
33
|
+
*/
|
|
34
|
+
export declare function scheduleFlush(ctx: WaitUntil, telemetry: Telemetry | Promise<Telemetry>, options?: WorkersFlushOptions): Promise<SignalReport>;
|
package/dist/flush.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
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
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Flushes telemetry after the invocation, through ctx.waitUntil, so the export outlives the
|
|
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.
|
|
31
|
+
*/
|
|
32
|
+
export function scheduleFlush(ctx, telemetry, options) {
|
|
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 }] }));
|
|
37
|
+
try {
|
|
38
|
+
ctx.waitUntil(flushing);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// Outside an invocation waitUntil can throw; the flush still runs as far as the runtime lets it.
|
|
42
|
+
}
|
|
43
|
+
return flushing;
|
|
44
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The libo11y platform for Cloudflare Workers and Durable Objects (workerd): setup memoized per
|
|
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.
|
|
8
|
+
*/
|
|
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";
|
|
12
|
+
export { createContextManager } from "./context.ts";
|
|
13
|
+
export type { WorkersExporterOptions, WorkersFetch } from "./exporters.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";
|
|
18
|
+
export { createTelemetry, setup, type WorkersOptions } from "./setup.ts";
|
|
19
|
+
export { VERSION } from "./version.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The libo11y platform for Cloudflare Workers and Durable Objects (workerd): setup memoized per
|
|
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.
|
|
8
|
+
*/
|
|
9
|
+
export { O11yError, } from "@libo11y/core";
|
|
10
|
+
export { attachQueueCarrier, batchQueueMessages, DEFAULT_CARRIER_FIELD, DEFAULT_QUEUE_BATCH_MAX_BYTES, DEFAULT_QUEUE_MESSAGE_MAX_BYTES, extractQueueCarrier, instrumentFetch, instrumentServe, setRoute, } from "@libo11y/core/edge";
|
|
11
|
+
export { enrichDurableObjectSpan, traceAlarm, traceDurableObjectCall, traceDurableObjectMethod, traceDurableObjectMethods, traceDurableObjectStub, traceQueueBatch, traceScheduled, } from "./adapters.js";
|
|
12
|
+
export { createContextManager } from "./context.js";
|
|
13
|
+
export { scheduleFlush } from "./flush.js";
|
|
14
|
+
export { instrument } from "./instrument.js";
|
|
15
|
+
export { DEFAULT_INSTRUMENT_METRICS_FLUSH_INTERVAL_MILLIS, DEFAULT_METRICS_FLUSH_INTERVAL_MILLIS, workersPlatform, } from "./platform.js";
|
|
16
|
+
export { buildRumUpstreamRequest, createRumProxy, DEFAULT_RUM_PROXY_PREFIX, DEFAULT_TRUSTED_EDGE_HEADER, isRumProxyPath, proxyRum, } from "./rum-proxy.js";
|
|
17
|
+
export { createTelemetry, setup } from "./setup.js";
|
|
18
|
+
export { VERSION } from "./version.js";
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* instrument: a thin wrapper for a Worker's handler object. Each invocation sets telemetry up (once
|
|
3
|
+
* per isolate), runs the handler inside a span, and flushes through waitUntil.
|
|
4
|
+
*
|
|
5
|
+
* - fetch runs through instrumentServe from @libo11y/core/edge unless `serve: false` is set (for
|
|
6
|
+
* framework HTTP servers such as Effect's HttpRouter that emit their own server spans while
|
|
7
|
+
* keeping isolate setup and waitUntil flushing).
|
|
8
|
+
* - queue gets a CONSUMER span "process <queue>" via traceQueueBatch, automatically linking
|
|
9
|
+
* detached _o11y Carriers from batch messages, and flushes with forceMetrics: true.
|
|
10
|
+
* - scheduled gets a SERVER span "scheduled <cron>" via traceScheduled and flushes with
|
|
11
|
+
* forceMetrics: true.
|
|
12
|
+
*
|
|
13
|
+
* When wrapping fetch with instrumentServe (serve !== false) and options.metricsFlushIntervalMillis
|
|
14
|
+
* is unset, instrument defaults metricsFlushIntervalMillis to 15000 ms (batched HTTP RED metrics),
|
|
15
|
+
* while queue and scheduled flushes force changed metrics immediately so mixed Workers never lose
|
|
16
|
+
* queue or cron counts to the fetch throttle. When serve is false or the handler has no fetch,
|
|
17
|
+
* setup()'s flush-on-change default (0) applies.
|
|
18
|
+
*
|
|
19
|
+
* The telemetry never fails an invocation: when setup fails, the handler runs without telemetry
|
|
20
|
+
* and the failure is written once per isolate to console.warn.
|
|
21
|
+
*/
|
|
22
|
+
import type { Telemetry } from "@libo11y/core";
|
|
23
|
+
import { type ServeOptions } from "@libo11y/core/edge";
|
|
24
|
+
import { type WorkerMessageBatch, type WorkerScheduledController } from "./adapters.ts";
|
|
25
|
+
import { type WaitUntil, type WorkersFlushOptions } from "./flush.ts";
|
|
26
|
+
import { type WorkersOptions } from "./setup.ts";
|
|
27
|
+
export type { WorkerMessageBatch, WorkerScheduledController } from "./adapters.ts";
|
|
28
|
+
/**
|
|
29
|
+
* The handlers instrument wraps, as a Worker's default export declares them. Every member is
|
|
30
|
+
* optional; members it does not know pass through.
|
|
31
|
+
*/
|
|
32
|
+
export interface WorkerHandler<Env> {
|
|
33
|
+
/** An HTTP request: a SERVER span through instrumentServe unless `serve: false`. */
|
|
34
|
+
fetch?(request: Request, env: Env, ctx: WaitUntil): Response | Promise<Response>;
|
|
35
|
+
/** A queue batch: a CONSUMER span "process <queue>" with extracted carrier links. */
|
|
36
|
+
queue?(batch: WorkerMessageBatch, env: Env, ctx: WaitUntil): void | Promise<void>;
|
|
37
|
+
/** A Cron Trigger: a SERVER span "scheduled <cron>". */
|
|
38
|
+
scheduled?(controller: WorkerScheduledController, env: Env, ctx: WaitUntil): void | Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
/** Options for instrument. */
|
|
41
|
+
export interface InstrumentOptions<Env> {
|
|
42
|
+
/**
|
|
43
|
+
* The telemetry options for the isolate, from the first invocation's env: the service identity,
|
|
44
|
+
* `env` itself for its OTEL_* variables, and the exporter, such as a binding's fetch. Read once,
|
|
45
|
+
* by the invocation that sets telemetry up.
|
|
46
|
+
*/
|
|
47
|
+
readonly options?: (env: Env) => WorkersOptions;
|
|
48
|
+
/**
|
|
49
|
+
* Supplies the telemetry instead of setting it up, as a test passes a `@libo11y/test` recorder's.
|
|
50
|
+
* It beats options.
|
|
51
|
+
*/
|
|
52
|
+
readonly telemetry?: (env: Env) => Telemetry | Promise<Telemetry>;
|
|
53
|
+
/**
|
|
54
|
+
* instrumentServe's options for fetch, such as route and publicEndpoint, or `false` to skip
|
|
55
|
+
* instrumentServe when a framework (such as Effect HttpRouter) owns its own HTTP server spans.
|
|
56
|
+
*/
|
|
57
|
+
readonly serve?: Omit<ServeOptions, "telemetry"> | false;
|
|
58
|
+
/** Options for the flush after each invocation (default deadline 5000 ms). */
|
|
59
|
+
readonly flush?: WorkersFlushOptions;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Wraps a Worker's handler object: fetch, queue and scheduled run inside spans and flush through
|
|
63
|
+
* waitUntil after every invocation. The result is a new plain object with the handler's own
|
|
64
|
+
* members, so pass an object literal rather than a class instance. Pass the handler you would
|
|
65
|
+
* export:
|
|
66
|
+
*
|
|
67
|
+
* ```ts
|
|
68
|
+
* export default instrument(handler, {
|
|
69
|
+
* options: (env) => ({ serviceName: "api", environment: env.ENVIRONMENT, env }),
|
|
70
|
+
* });
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
export declare function instrument<Env, H extends WorkerHandler<Env>>(handler: H, opts: InstrumentOptions<Env>): H & WorkerHandler<Env>;
|