@libo11y/workers 0.0.0-stage → 0.8.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 +252 -2
- package/dist/context.d.ts +3 -0
- package/dist/context.js +50 -0
- package/dist/env.d.ts +16 -0
- package/dist/env.js +57 -0
- package/dist/exporters.d.ts +93 -0
- package/dist/exporters.js +278 -0
- package/dist/flush.d.ts +19 -0
- package/dist/flush.js +17 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +14 -0
- package/dist/instrument.d.ts +78 -0
- package/dist/instrument.js +158 -0
- package/dist/metric-reader.d.ts +25 -0
- package/dist/metric-reader.js +83 -0
- package/dist/platform.d.ts +29 -0
- package/dist/platform.js +31 -0
- package/dist/resource.d.ts +17 -0
- package/dist/resource.js +30 -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 +47 -4
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OTLP/HTTP export over fetch, for each signal core routes to otlp or console.
|
|
3
|
+
*
|
|
4
|
+
* A Worker has no sockets of its own, so every export is one fetch: through the global fetch by
|
|
5
|
+
* default, or through the function WorkersExporterOptions.fetch names, such as a service binding's
|
|
6
|
+
* or a Workers VPC binding's, which reach a collector the public internet cannot. The bodies are
|
|
7
|
+
* upstream's serializers (otlp-transformer) for spans and logs, and libo11y's for metrics, which
|
|
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.
|
|
13
|
+
*/
|
|
14
|
+
import { type ExporterRequest, type ExporterSet } from "@libo11y/core";
|
|
15
|
+
import { type ExportResult } from "@opentelemetry/core";
|
|
16
|
+
import { type ISerializer } from "@opentelemetry/otlp-transformer";
|
|
17
|
+
import { type OtelEnv } from "./env.ts";
|
|
18
|
+
/** A fetch function: the global fetch, or a binding's, such as `(req) => env.OTLP.fetch(req)`. */
|
|
19
|
+
export type WorkersFetch = (request: Request) => Promise<Response>;
|
|
20
|
+
/** Where and how the exporters send. Each field beats its OTEL_EXPORTER_OTLP_* variable. */
|
|
21
|
+
export interface WorkersExporterOptions {
|
|
22
|
+
/**
|
|
23
|
+
* The base URL, as OTEL_EXPORTER_OTLP_ENDPOINT: each signal posts to it with v1/traces, v1/metrics
|
|
24
|
+
* or v1/logs appended. Default http://localhost:4318.
|
|
25
|
+
*/
|
|
26
|
+
readonly endpoint?: string;
|
|
27
|
+
/** The full URL for spans, as OTEL_EXPORTER_OTLP_TRACES_ENDPOINT. Beats endpoint. */
|
|
28
|
+
readonly tracesEndpoint?: string;
|
|
29
|
+
/** The full URL for metrics, as OTEL_EXPORTER_OTLP_METRICS_ENDPOINT. Beats endpoint. */
|
|
30
|
+
readonly metricsEndpoint?: string;
|
|
31
|
+
/** The full URL for log records, as OTEL_EXPORTER_OTLP_LOGS_ENDPOINT. Beats endpoint. */
|
|
32
|
+
readonly logsEndpoint?: string;
|
|
33
|
+
/** Headers sent with every export, on top of those OTEL_EXPORTER_OTLP_HEADERS names. */
|
|
34
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
35
|
+
/**
|
|
36
|
+
* The function every export goes through. Default the global fetch. Pass a binding's to export
|
|
37
|
+
* through a service binding or a Workers VPC binding: `(req) => env.OTLP.fetch(req)`.
|
|
38
|
+
*/
|
|
39
|
+
readonly fetch?: WorkersFetch;
|
|
40
|
+
/** gzip the bodies with CompressionStream. Default OTEL_EXPORTER_OTLP_COMPRESSION, else "none". */
|
|
41
|
+
readonly compression?: "gzip" | "none";
|
|
42
|
+
/** The deadline of one export in milliseconds. Default OTEL_EXPORTER_OTLP_TIMEOUT, else 10000. */
|
|
43
|
+
readonly timeoutMillis?: number;
|
|
44
|
+
}
|
|
45
|
+
/** The options buildExporters takes beside core's request. */
|
|
46
|
+
export interface WorkersExportConfig {
|
|
47
|
+
readonly env: OtelEnv;
|
|
48
|
+
readonly exporter?: WorkersExporterOptions | undefined;
|
|
49
|
+
/** The least time between two metric exports of one isolate, in milliseconds. */
|
|
50
|
+
readonly metricsFlushIntervalMillis: number;
|
|
51
|
+
}
|
|
52
|
+
type SignalName = "traces" | "metrics" | "logs";
|
|
53
|
+
/** One signal's resolved export settings. */
|
|
54
|
+
export interface SignalExport {
|
|
55
|
+
readonly url: string;
|
|
56
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
57
|
+
readonly compression: "gzip" | "none";
|
|
58
|
+
readonly timeoutMillis: number;
|
|
59
|
+
readonly fetch: WorkersFetch;
|
|
60
|
+
}
|
|
61
|
+
/** Appends a signal path to a base URL as the OTLP exporter specification says. */
|
|
62
|
+
export declare function signalUrl(base: string, signal: SignalName): string;
|
|
63
|
+
/** Resolves one signal's export settings: option, then signal variable, then shared variable, then default. */
|
|
64
|
+
export declare function resolveSignalExport(signal: SignalName, options: WorkersExporterOptions | undefined, env: OtelEnv): SignalExport;
|
|
65
|
+
/** An export that got an HTTP status outside 2xx. */
|
|
66
|
+
export declare class OtlpHttpError extends Error {
|
|
67
|
+
readonly status: number;
|
|
68
|
+
constructor(status: number);
|
|
69
|
+
}
|
|
70
|
+
/** An export that did not finish before its deadline, or was stopped by shutdown. */
|
|
71
|
+
export declare class OtlpTimeoutError extends Error {
|
|
72
|
+
constructor(message: string);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Posts one signal's serialized batches over fetch. Every export has the signal's deadline;
|
|
76
|
+
* shutdown() stops what is in flight and fails every later export. Nothing here throws to the
|
|
77
|
+
* caller.
|
|
78
|
+
*/
|
|
79
|
+
export declare class FetchOtlpExporter<Internal> {
|
|
80
|
+
private readonly settings;
|
|
81
|
+
private readonly contentType;
|
|
82
|
+
private readonly serializer;
|
|
83
|
+
private readonly inFlight;
|
|
84
|
+
private stopped;
|
|
85
|
+
constructor(settings: SignalExport, contentType: string, serializer: ISerializer<Internal, unknown>);
|
|
86
|
+
export(items: Internal, resultCallback: (result: ExportResult) => void): void;
|
|
87
|
+
private send;
|
|
88
|
+
forceFlush(): Promise<void>;
|
|
89
|
+
shutdown(): Promise<void>;
|
|
90
|
+
}
|
|
91
|
+
/** Builds the exporters for every signal the configuration routes to "otlp" or "console". */
|
|
92
|
+
export declare function buildExporters(req: ExporterRequest, config: WorkersExportConfig): ExporterSet;
|
|
93
|
+
export {};
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OTLP/HTTP export over fetch, for each signal core routes to otlp or console.
|
|
3
|
+
*
|
|
4
|
+
* A Worker has no sockets of its own, so every export is one fetch: through the global fetch by
|
|
5
|
+
* default, or through the function WorkersExporterOptions.fetch names, such as a service binding's
|
|
6
|
+
* or a Workers VPC binding's, which reach a collector the public internet cannot. The bodies are
|
|
7
|
+
* upstream's serializers (otlp-transformer) for spans and logs, and libo11y's for metrics, which
|
|
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.
|
|
13
|
+
*/
|
|
14
|
+
import { exemplarMetricExporter, O11yError, OtlpJsonMetricsSerializer, } from "@libo11y/core";
|
|
15
|
+
import { OtlpProtobufMetricsSerializer } from "@libo11y/server/edge";
|
|
16
|
+
import { ExportResultCode } from "@opentelemetry/core";
|
|
17
|
+
import { JsonLogsSerializer, JsonTraceSerializer, ProtobufLogsSerializer, ProtobufTraceSerializer, } from "@opentelemetry/otlp-transformer";
|
|
18
|
+
import { ConsoleLogRecordExporter, } from "@opentelemetry/sdk-logs";
|
|
19
|
+
import { AggregationTemporality, ConsoleMetricExporter, InstrumentType, } from "@opentelemetry/sdk-metrics";
|
|
20
|
+
import { ConsoleSpanExporter } from "@opentelemetry/sdk-trace";
|
|
21
|
+
import { parseKeyValues } from "./env.js";
|
|
22
|
+
import { FlushMetricReader } from "./metric-reader.js";
|
|
23
|
+
const DEFAULT_ENDPOINT = "http://localhost:4318";
|
|
24
|
+
const DEFAULT_TIMEOUT_MILLIS = 10000;
|
|
25
|
+
const PROTOBUF = "application/x-protobuf";
|
|
26
|
+
const JSON_TYPE = "application/json";
|
|
27
|
+
function envValue(env, name) {
|
|
28
|
+
const v = env[name]?.trim();
|
|
29
|
+
return v === undefined || v === "" ? undefined : v;
|
|
30
|
+
}
|
|
31
|
+
function given(value) {
|
|
32
|
+
const v = value?.trim();
|
|
33
|
+
return v === undefined || v === "" ? undefined : v;
|
|
34
|
+
}
|
|
35
|
+
/** Appends a signal path to a base URL as the OTLP exporter specification says. */
|
|
36
|
+
export function signalUrl(base, signal) {
|
|
37
|
+
return `${base.endsWith("/") ? base : `${base}/`}v1/${signal}`;
|
|
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);
|
|
52
|
+
}
|
|
53
|
+
/** Resolves one signal's export settings: option, then signal variable, then shared variable, then default. */
|
|
54
|
+
export function resolveSignalExport(signal, options, env) {
|
|
55
|
+
const upper = signal.toUpperCase();
|
|
56
|
+
const own = given(signal === "traces"
|
|
57
|
+
? options?.tracesEndpoint
|
|
58
|
+
: signal === "metrics"
|
|
59
|
+
? options?.metricsEndpoint
|
|
60
|
+
: options?.logsEndpoint);
|
|
61
|
+
const base = given(options?.endpoint);
|
|
62
|
+
const url = own ??
|
|
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 ?? {}),
|
|
70
|
+
};
|
|
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
|
+
}
|
|
84
|
+
/** An export that got an HTTP status outside 2xx. */
|
|
85
|
+
export class OtlpHttpError extends Error {
|
|
86
|
+
status;
|
|
87
|
+
constructor(status) {
|
|
88
|
+
super(`OTLP export failed with HTTP status ${status}`);
|
|
89
|
+
this.name = "OtlpHttpError";
|
|
90
|
+
this.status = status;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** An export that did not finish before its deadline, or was stopped by shutdown. */
|
|
94
|
+
export class OtlpTimeoutError extends Error {
|
|
95
|
+
constructor(message) {
|
|
96
|
+
super(message);
|
|
97
|
+
this.name = "TimeoutError";
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
async function gzip(data) {
|
|
101
|
+
const stream = new Blob([data])
|
|
102
|
+
.stream()
|
|
103
|
+
.pipeThrough(new CompressionStream("gzip"));
|
|
104
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
105
|
+
}
|
|
106
|
+
function failed(error) {
|
|
107
|
+
return { code: ExportResultCode.FAILED, error: error instanceof Error ? error : new Error(String(error)) };
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Posts one signal's serialized batches over fetch. Every export has the signal's deadline;
|
|
111
|
+
* shutdown() stops what is in flight and fails every later export. Nothing here throws to the
|
|
112
|
+
* caller.
|
|
113
|
+
*/
|
|
114
|
+
export class FetchOtlpExporter {
|
|
115
|
+
settings;
|
|
116
|
+
contentType;
|
|
117
|
+
serializer;
|
|
118
|
+
inFlight = new Set();
|
|
119
|
+
stopped = false;
|
|
120
|
+
constructor(settings, contentType, serializer) {
|
|
121
|
+
this.settings = settings;
|
|
122
|
+
this.contentType = contentType;
|
|
123
|
+
this.serializer = serializer;
|
|
124
|
+
}
|
|
125
|
+
export(items, resultCallback) {
|
|
126
|
+
if (this.stopped) {
|
|
127
|
+
resultCallback(failed(new Error("o11y: the exporter is shut down")));
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
let body;
|
|
131
|
+
try {
|
|
132
|
+
body = this.serializer.serializeRequest(items);
|
|
133
|
+
}
|
|
134
|
+
catch (err) {
|
|
135
|
+
resultCallback(failed(err));
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (body === undefined) {
|
|
139
|
+
resultCallback(failed(new Error("o11y: the batch could not be serialized")));
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
this.send(body).then(() => resultCallback({ code: ExportResultCode.SUCCESS }), (err) => resultCallback(failed(err)));
|
|
143
|
+
}
|
|
144
|
+
async send(body) {
|
|
145
|
+
const { url, headers, compression, timeoutMillis, fetch: send } = this.settings;
|
|
146
|
+
const controller = new AbortController();
|
|
147
|
+
this.inFlight.add(controller);
|
|
148
|
+
const timer = setTimeout(() => controller.abort(new OtlpTimeoutError("o11y: the export did not finish before its deadline")), timeoutMillis);
|
|
149
|
+
try {
|
|
150
|
+
const payload = compression === "gzip" ? await gzip(body) : body;
|
|
151
|
+
const h = new Headers(headers);
|
|
152
|
+
h.set("content-type", this.contentType);
|
|
153
|
+
if (compression === "gzip")
|
|
154
|
+
h.set("content-encoding", "gzip");
|
|
155
|
+
const request = new Request(url, {
|
|
156
|
+
method: "POST",
|
|
157
|
+
headers: h,
|
|
158
|
+
body: payload,
|
|
159
|
+
signal: controller.signal,
|
|
160
|
+
});
|
|
161
|
+
const aborted = new Promise((_, reject) => {
|
|
162
|
+
controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
|
|
163
|
+
});
|
|
164
|
+
// A binding's fetch may not honor the signal, so the deadline also races it.
|
|
165
|
+
const response = await Promise.race([send(request), aborted]);
|
|
166
|
+
try {
|
|
167
|
+
await response.body?.cancel();
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
// The body is not needed; a failure to release it changes nothing.
|
|
171
|
+
}
|
|
172
|
+
if (response.status < 200 || response.status > 299)
|
|
173
|
+
throw new OtlpHttpError(response.status);
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
clearTimeout(timer);
|
|
177
|
+
this.inFlight.delete(controller);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
forceFlush() {
|
|
181
|
+
return Promise.resolve();
|
|
182
|
+
}
|
|
183
|
+
shutdown() {
|
|
184
|
+
this.stopped = true;
|
|
185
|
+
for (const controller of this.inFlight) {
|
|
186
|
+
controller.abort(new OtlpTimeoutError("o11y: the exporter shut down before the export finished"));
|
|
187
|
+
}
|
|
188
|
+
return Promise.resolve();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* The OTLP metric exporter: CUMULATIVE temporality, which Prometheus' OTLP receiver requires,
|
|
193
|
+
* unless OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE says delta or lowmemory.
|
|
194
|
+
*/
|
|
195
|
+
class FetchOtlpMetricExporter extends FetchOtlpExporter {
|
|
196
|
+
preference;
|
|
197
|
+
constructor(settings, contentType, serializer, preference) {
|
|
198
|
+
super(settings, contentType, serializer);
|
|
199
|
+
this.preference = preference;
|
|
200
|
+
}
|
|
201
|
+
selectAggregationTemporality(instrumentType) {
|
|
202
|
+
if (this.preference === "cumulative")
|
|
203
|
+
return AggregationTemporality.CUMULATIVE;
|
|
204
|
+
switch (instrumentType) {
|
|
205
|
+
case InstrumentType.COUNTER:
|
|
206
|
+
case InstrumentType.OBSERVABLE_COUNTER:
|
|
207
|
+
case InstrumentType.HISTOGRAM:
|
|
208
|
+
return AggregationTemporality.DELTA;
|
|
209
|
+
case InstrumentType.OBSERVABLE_GAUGE:
|
|
210
|
+
case InstrumentType.GAUGE:
|
|
211
|
+
return this.preference === "delta" ? AggregationTemporality.DELTA : AggregationTemporality.CUMULATIVE;
|
|
212
|
+
default:
|
|
213
|
+
return AggregationTemporality.CUMULATIVE;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
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
|
+
// build runs a constructor and reports a failure as Go's "o11y: building <kind>: %w".
|
|
222
|
+
function build(kind, fn) {
|
|
223
|
+
try {
|
|
224
|
+
return fn();
|
|
225
|
+
}
|
|
226
|
+
catch (err) {
|
|
227
|
+
throw new O11yError("EXPORTER", `o11y: building ${kind}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
function spanExporter(req, config) {
|
|
231
|
+
const { traces, protocol } = req.config;
|
|
232
|
+
if (traces === "console")
|
|
233
|
+
return new ConsoleSpanExporter();
|
|
234
|
+
if (traces !== "otlp")
|
|
235
|
+
return undefined;
|
|
236
|
+
return build("span exporter", () => {
|
|
237
|
+
const json = protocol.traces === "http/json";
|
|
238
|
+
return new FetchOtlpExporter(resolveSignalExport("traces", config.exporter, config.env), json ? JSON_TYPE : PROTOBUF, json ? JsonTraceSerializer : ProtobufTraceSerializer);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
function logExporter(req, config) {
|
|
242
|
+
const { logs, protocol } = req.config;
|
|
243
|
+
if (logs === "console")
|
|
244
|
+
return new ConsoleLogRecordExporter();
|
|
245
|
+
if (logs !== "otlp")
|
|
246
|
+
return undefined;
|
|
247
|
+
return build("log exporter", () => {
|
|
248
|
+
const json = protocol.logs === "http/json";
|
|
249
|
+
return new FetchOtlpExporter(resolveSignalExport("logs", config.exporter, config.env), json ? JSON_TYPE : PROTOBUF, json ? JsonLogsSerializer : ProtobufLogsSerializer);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
function metricReader(req, config) {
|
|
253
|
+
const { metrics, protocol, metricExport } = req.config;
|
|
254
|
+
if (metrics !== "otlp" && metrics !== "console")
|
|
255
|
+
return undefined;
|
|
256
|
+
return build("metric reader", () => {
|
|
257
|
+
const json = protocol.metrics === "http/json";
|
|
258
|
+
const inner = metrics === "console"
|
|
259
|
+
? new ConsoleMetricExporter({ temporalitySelector: () => AggregationTemporality.CUMULATIVE })
|
|
260
|
+
: new FetchOtlpMetricExporter(resolveSignalExport("metrics", config.exporter, config.env), json ? JSON_TYPE : PROTOBUF, json ? OtlpJsonMetricsSerializer : OtlpProtobufMetricsSerializer, temporalityPreference(config.env));
|
|
261
|
+
return new FlushMetricReader({
|
|
262
|
+
exporter: exemplarMetricExporter(inner, req.exemplars),
|
|
263
|
+
intervalMillis: config.metricsFlushIntervalMillis,
|
|
264
|
+
timeoutMillis: metricExport.timeoutMillis,
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
/** Builds the exporters for every signal the configuration routes to "otlp" or "console". */
|
|
269
|
+
export function buildExporters(req, config) {
|
|
270
|
+
const spans = spanExporter(req, config);
|
|
271
|
+
const reader = metricReader(req, config);
|
|
272
|
+
const logs = logExporter(req, config);
|
|
273
|
+
return {
|
|
274
|
+
...(spans === undefined ? {} : { spanExporter: spans }),
|
|
275
|
+
...(reader === undefined ? {} : { metricReader: reader }),
|
|
276
|
+
...(logs === undefined ? {} : { logExporter: logs }),
|
|
277
|
+
};
|
|
278
|
+
}
|
package/dist/flush.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
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 type { LifecycleOptions, SignalReport, Telemetry } from "@libo11y/core";
|
|
7
|
+
/** What has waitUntil: a Worker's ExecutionContext or a Durable Object's DurableObjectState. */
|
|
8
|
+
export interface WaitUntil {
|
|
9
|
+
/** Keeps the invocation alive until promise settles. */
|
|
10
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Flushes telemetry after the invocation, through ctx.waitUntil, so the export outlives the
|
|
14
|
+
* response. Traces and logs export on every flush; metrics only when the platform's
|
|
15
|
+
* metricsFlushIntervalMillis has passed since their last export. The flush has core's deadline
|
|
16
|
+
* (options.timeoutMillis, default 5000 ms). telemetry may be a promise, such as setup's. Returns the
|
|
17
|
+
* flush, which never rejects, for a caller that wants to wait for it.
|
|
18
|
+
*/
|
|
19
|
+
export declare function scheduleFlush(ctx: WaitUntil, telemetry: Telemetry | Promise<Telemetry>, options?: LifecycleOptions): Promise<SignalReport>;
|
package/dist/flush.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flushes telemetry after the invocation, through ctx.waitUntil, so the export outlives the
|
|
3
|
+
* response. Traces and logs export on every flush; metrics only when the platform's
|
|
4
|
+
* metricsFlushIntervalMillis has passed since their last export. The flush has core's deadline
|
|
5
|
+
* (options.timeoutMillis, default 5000 ms). telemetry may be a promise, such as setup's. Returns the
|
|
6
|
+
* flush, which never rejects, for a caller that wants to wait for it.
|
|
7
|
+
*/
|
|
8
|
+
export function scheduleFlush(ctx, telemetry, options) {
|
|
9
|
+
const flushing = Promise.resolve(telemetry).then((t) => t.forceFlush(options), (error) => ({ ok: false, errors: [{ signal: "lifecycle", error }] }));
|
|
10
|
+
try {
|
|
11
|
+
ctx.waitUntil(flushing);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
// Outside an invocation waitUntil can throw; the flush still runs as far as the runtime lets it.
|
|
15
|
+
}
|
|
16
|
+
return flushing;
|
|
17
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
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 AsyncLocalStorage context, metrics
|
|
4
|
+
* exported on flush, flushing through waitUntil, and spans for fetch, queue and scheduled handlers.
|
|
5
|
+
* It needs the nodejs_compat (or nodejs_als) compatibility flag for node:async_hooks.
|
|
6
|
+
*/
|
|
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/server/edge";
|
|
9
|
+
export { createContextManager } from "./context.ts";
|
|
10
|
+
export type { WorkersExporterOptions, WorkersFetch } from "./exporters.ts";
|
|
11
|
+
export { scheduleFlush, type WaitUntil } from "./flush.ts";
|
|
12
|
+
export { type InstrumentOptions, instrument, type WorkerHandler, type WorkerMessageBatch, type WorkerScheduledController, } from "./instrument.ts";
|
|
13
|
+
export { DEFAULT_METRICS_FLUSH_INTERVAL_MILLIS, type WorkersPlatformOptions, workersPlatform, } from "./platform.ts";
|
|
14
|
+
export { createTelemetry, setup, type WorkersOptions } from "./setup.ts";
|
|
15
|
+
export { VERSION } from "./version.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
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 AsyncLocalStorage context, metrics
|
|
4
|
+
* exported on flush, flushing through waitUntil, and spans for fetch, queue and scheduled handlers.
|
|
5
|
+
* It needs the nodejs_compat (or nodejs_als) compatibility flag for node:async_hooks.
|
|
6
|
+
*/
|
|
7
|
+
export { O11yError, } from "@libo11y/core";
|
|
8
|
+
export { instrumentFetch, instrumentServe, setRoute, } from "@libo11y/server/edge";
|
|
9
|
+
export { createContextManager } from "./context.js";
|
|
10
|
+
export { scheduleFlush } from "./flush.js";
|
|
11
|
+
export { instrument, } from "./instrument.js";
|
|
12
|
+
export { DEFAULT_METRICS_FLUSH_INTERVAL_MILLIS, workersPlatform, } from "./platform.js";
|
|
13
|
+
export { createTelemetry, setup } from "./setup.js";
|
|
14
|
+
export { VERSION } from "./version.js";
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* instrument: a thin wrapper for a plain Worker's handler object. Each invocation sets telemetry up
|
|
3
|
+
* (once per isolate), runs the handler inside a span, and flushes through waitUntil.
|
|
4
|
+
*
|
|
5
|
+
* - fetch runs through instrumentServe from @libo11y/server/edge: a SERVER span named
|
|
6
|
+
* "<METHOD> <route>" that continues an inbound W3C traceparent, the stable HTTP semantic
|
|
7
|
+
* conventions, and http.server.request.duration with exemplars.
|
|
8
|
+
* - queue gets a CONSUMER span "process <queue>" with the messaging attributes.
|
|
9
|
+
* - scheduled gets a SERVER span "scheduled <cron>" with the FaaS timer attributes.
|
|
10
|
+
*
|
|
11
|
+
* Any other member of the handler (email, tail, a Durable Object class export) passes through
|
|
12
|
+
* unchanged. An application that builds its own server spans, as Effect's HttpServer does, calls
|
|
13
|
+
* setup and scheduleFlush itself instead.
|
|
14
|
+
*
|
|
15
|
+
* The telemetry never fails an invocation: when setup fails, the handler runs without telemetry
|
|
16
|
+
* and the failure is written once per isolate to console.warn.
|
|
17
|
+
*/
|
|
18
|
+
import type { LifecycleOptions, Telemetry } from "@libo11y/core";
|
|
19
|
+
import { type ServeOptions } from "@libo11y/server/edge";
|
|
20
|
+
import { type WaitUntil } from "./flush.ts";
|
|
21
|
+
import { type WorkersOptions } from "./setup.ts";
|
|
22
|
+
/** The fields of a queue MessageBatch the span reads. */
|
|
23
|
+
export interface WorkerMessageBatch {
|
|
24
|
+
/** The queue's name: messaging.destination.name. */
|
|
25
|
+
readonly queue: string;
|
|
26
|
+
/** The messages: their count is messaging.batch.message_count. */
|
|
27
|
+
readonly messages: readonly unknown[];
|
|
28
|
+
}
|
|
29
|
+
/** The fields of a ScheduledController the span reads. */
|
|
30
|
+
export interface WorkerScheduledController {
|
|
31
|
+
/** The cron pattern that fired: faas.cron. */
|
|
32
|
+
readonly cron: string;
|
|
33
|
+
/** When the invocation was scheduled, in milliseconds since the epoch: faas.time. */
|
|
34
|
+
readonly scheduledTime: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The handlers instrument wraps, as a Worker's default export declares them. Every member is
|
|
38
|
+
* optional; members it does not know pass through.
|
|
39
|
+
*/
|
|
40
|
+
export interface WorkerHandler<Env> {
|
|
41
|
+
/** An HTTP request: a SERVER span through instrumentServe. */
|
|
42
|
+
fetch?(request: Request, env: Env, ctx: WaitUntil): Response | Promise<Response>;
|
|
43
|
+
/** A queue batch: a CONSUMER span "process <queue>". */
|
|
44
|
+
queue?(batch: WorkerMessageBatch, env: Env, ctx: WaitUntil): void | Promise<void>;
|
|
45
|
+
/** A Cron Trigger: a SERVER span "scheduled <cron>". */
|
|
46
|
+
scheduled?(controller: WorkerScheduledController, env: Env, ctx: WaitUntil): void | Promise<void>;
|
|
47
|
+
}
|
|
48
|
+
/** Options for instrument. */
|
|
49
|
+
export interface InstrumentOptions<Env> {
|
|
50
|
+
/**
|
|
51
|
+
* The telemetry options for the isolate, from the first invocation's env: the service identity,
|
|
52
|
+
* `env` itself for its OTEL_* variables, and the exporter, such as a binding's fetch. Read once,
|
|
53
|
+
* by the invocation that sets telemetry up.
|
|
54
|
+
*/
|
|
55
|
+
readonly options?: (env: Env) => WorkersOptions;
|
|
56
|
+
/**
|
|
57
|
+
* Supplies the telemetry instead of setting it up, as a test passes a `@libo11y/test` recorder's.
|
|
58
|
+
* It beats options.
|
|
59
|
+
*/
|
|
60
|
+
readonly telemetry?: (env: Env) => Telemetry | Promise<Telemetry>;
|
|
61
|
+
/** instrumentServe's options for fetch, such as route and publicEndpoint. */
|
|
62
|
+
readonly serve?: Omit<ServeOptions, "telemetry">;
|
|
63
|
+
/** The deadline of the flush after each invocation. Default core's, 5000 ms. */
|
|
64
|
+
readonly flush?: LifecycleOptions;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Wraps a Worker's handler object: fetch, queue and scheduled run inside spans and flush through
|
|
68
|
+
* waitUntil after every invocation. The result is a new plain object with the handler's own
|
|
69
|
+
* members, so pass an object literal rather than a class instance. Pass the handler you would
|
|
70
|
+
* export:
|
|
71
|
+
*
|
|
72
|
+
* ```ts
|
|
73
|
+
* export default instrument(handler, {
|
|
74
|
+
* options: (env) => ({ serviceName: "api", environment: env.ENVIRONMENT, env }),
|
|
75
|
+
* });
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export declare function instrument<Env, H extends WorkerHandler<Env>>(handler: H, opts: InstrumentOptions<Env>): H & WorkerHandler<Env>;
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { instrumentServe } from "@libo11y/server/edge";
|
|
2
|
+
import { SpanKind, SpanStatusCode } from "@opentelemetry/api";
|
|
3
|
+
import { scheduleFlush } from "./flush.js";
|
|
4
|
+
import { setup } from "./setup.js";
|
|
5
|
+
import { VERSION } from "./version.js";
|
|
6
|
+
/** The instrumentation scope of the queue and scheduled spans. */
|
|
7
|
+
const SCOPE = "@libo11y/workers";
|
|
8
|
+
function errorType(err) {
|
|
9
|
+
if (err instanceof Error && err.name !== "")
|
|
10
|
+
return err.name;
|
|
11
|
+
return "_OTHER";
|
|
12
|
+
}
|
|
13
|
+
function fail(span, err) {
|
|
14
|
+
try {
|
|
15
|
+
if (err instanceof Error)
|
|
16
|
+
span.recordException(err);
|
|
17
|
+
else
|
|
18
|
+
span.recordException(String(err));
|
|
19
|
+
span.setAttribute("error.type", errorType(err));
|
|
20
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// A span that cannot record changes nothing the caller sees.
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Runs fn inside a span of telemetry's tracer and ends it, recording a throw and rethrowing it.
|
|
28
|
+
* A span that cannot start leaves fn uninstrumented.
|
|
29
|
+
*/
|
|
30
|
+
async function inSpan(telemetry, name, kind, attributes, fn) {
|
|
31
|
+
let started;
|
|
32
|
+
try {
|
|
33
|
+
const tracer = telemetry.tracerProvider.getTracer(SCOPE, VERSION);
|
|
34
|
+
started = (run) => tracer.startActiveSpan(name, { kind, attributes }, run);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
started = undefined;
|
|
38
|
+
}
|
|
39
|
+
if (started === undefined)
|
|
40
|
+
return fn();
|
|
41
|
+
return started(async (span) => {
|
|
42
|
+
try {
|
|
43
|
+
return await fn();
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
fail(span, err);
|
|
47
|
+
throw err;
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
try {
|
|
51
|
+
span.end();
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// As above.
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Wraps a Worker's handler object: fetch, queue and scheduled run inside spans and flush through
|
|
61
|
+
* waitUntil after every invocation. The result is a new plain object with the handler's own
|
|
62
|
+
* members, so pass an object literal rather than a class instance. Pass the handler you would
|
|
63
|
+
* export:
|
|
64
|
+
*
|
|
65
|
+
* ```ts
|
|
66
|
+
* export default instrument(handler, {
|
|
67
|
+
* options: (env) => ({ serviceName: "api", environment: env.ENVIRONMENT, env }),
|
|
68
|
+
* });
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export function instrument(handler, opts) {
|
|
72
|
+
let warned = false;
|
|
73
|
+
const served = new WeakMap();
|
|
74
|
+
const telemetryFor = async (env) => {
|
|
75
|
+
try {
|
|
76
|
+
if (opts.telemetry !== undefined)
|
|
77
|
+
return await opts.telemetry(env);
|
|
78
|
+
return await setup(opts.options?.(env) ?? {});
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
if (!warned) {
|
|
82
|
+
warned = true;
|
|
83
|
+
try {
|
|
84
|
+
console.warn(`o11y: telemetry is off: ${err instanceof Error ? err.message : String(err)}`);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
// Nothing is left to report to.
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
const wrapped = { ...handler };
|
|
94
|
+
const fetchHandler = handler.fetch;
|
|
95
|
+
if (fetchHandler !== undefined) {
|
|
96
|
+
const run = (request, env, ctx) => fetchHandler.call(handler, request, env, ctx);
|
|
97
|
+
wrapped.fetch = async (request, env, ctx) => {
|
|
98
|
+
const telemetry = await telemetryFor(env);
|
|
99
|
+
if (telemetry === undefined)
|
|
100
|
+
return run(request, env, ctx);
|
|
101
|
+
let serve = served.get(telemetry);
|
|
102
|
+
if (serve === undefined) {
|
|
103
|
+
serve = instrumentServe(run, { ...opts.serve, telemetry });
|
|
104
|
+
served.set(telemetry, serve);
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
return await serve(request, env, ctx);
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
scheduleFlush(ctx, telemetry, opts.flush);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
const queueHandler = handler.queue;
|
|
115
|
+
if (queueHandler !== undefined) {
|
|
116
|
+
wrapped.queue = async (batch, env, ctx) => {
|
|
117
|
+
const telemetry = await telemetryFor(env);
|
|
118
|
+
if (telemetry === undefined)
|
|
119
|
+
return queueHandler.call(handler, batch, env, ctx);
|
|
120
|
+
const attributes = {
|
|
121
|
+
"messaging.system": "cloudflare_queues",
|
|
122
|
+
"messaging.operation.type": "process",
|
|
123
|
+
"messaging.operation.name": "process",
|
|
124
|
+
"messaging.destination.name": batch.queue,
|
|
125
|
+
"messaging.batch.message_count": batch.messages.length,
|
|
126
|
+
"faas.trigger": "pubsub",
|
|
127
|
+
};
|
|
128
|
+
try {
|
|
129
|
+
return await inSpan(telemetry, `process ${batch.queue}`, SpanKind.CONSUMER, attributes, () => queueHandler.call(handler, batch, env, ctx));
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
scheduleFlush(ctx, telemetry, opts.flush);
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const scheduledHandler = handler.scheduled;
|
|
137
|
+
if (scheduledHandler !== undefined) {
|
|
138
|
+
wrapped.scheduled = async (controller, env, ctx) => {
|
|
139
|
+
const telemetry = await telemetryFor(env);
|
|
140
|
+
if (telemetry === undefined)
|
|
141
|
+
return scheduledHandler.call(handler, controller, env, ctx);
|
|
142
|
+
const attributes = { "faas.trigger": "timer", "faas.cron": controller.cron };
|
|
143
|
+
try {
|
|
144
|
+
attributes["faas.time"] = new Date(controller.scheduledTime).toISOString();
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// An invalid time leaves the attribute out.
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
return await inSpan(telemetry, `scheduled ${controller.cron}`, SpanKind.SERVER, attributes, () => scheduledHandler.call(handler, controller, env, ctx));
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
scheduleFlush(ctx, telemetry, opts.flush);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
return wrapped;
|
|
158
|
+
}
|