@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,116 @@
|
|
|
1
|
+
import { instrumentServe } from "@libo11y/core/edge";
|
|
2
|
+
import { traceQueueBatch, traceScheduled, } from "./adapters.js";
|
|
3
|
+
import { scheduleFlush } from "./flush.js";
|
|
4
|
+
import { DEFAULT_INSTRUMENT_METRICS_FLUSH_INTERVAL_MILLIS } from "./platform.js";
|
|
5
|
+
import { setup } from "./setup.js";
|
|
6
|
+
/**
|
|
7
|
+
* Wraps a Worker's handler object: fetch, queue and scheduled run inside spans and flush through
|
|
8
|
+
* waitUntil after every invocation. The result is a new plain object with the handler's own
|
|
9
|
+
* members, so pass an object literal rather than a class instance. Pass the handler you would
|
|
10
|
+
* export:
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* export default instrument(handler, {
|
|
14
|
+
* options: (env) => ({ serviceName: "api", environment: env.ENVIRONMENT, env }),
|
|
15
|
+
* });
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
export function instrument(handler, opts) {
|
|
19
|
+
let warned = false;
|
|
20
|
+
const served = new WeakMap();
|
|
21
|
+
const usesInstrumentServe = handler.fetch !== undefined && opts.serve !== false;
|
|
22
|
+
const telemetryFor = async (env) => {
|
|
23
|
+
try {
|
|
24
|
+
if (opts.telemetry !== undefined)
|
|
25
|
+
return await opts.telemetry(env);
|
|
26
|
+
const userOptions = opts.options?.(env) ?? {};
|
|
27
|
+
const resolvedOptions = usesInstrumentServe && userOptions.metricsFlushIntervalMillis === undefined
|
|
28
|
+
? { ...userOptions, metricsFlushIntervalMillis: DEFAULT_INSTRUMENT_METRICS_FLUSH_INTERVAL_MILLIS }
|
|
29
|
+
: userOptions;
|
|
30
|
+
return await setup(resolvedOptions);
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
if (!warned) {
|
|
34
|
+
warned = true;
|
|
35
|
+
try {
|
|
36
|
+
console.warn(`o11y: telemetry is off: ${err instanceof Error ? err.message : String(err)}`);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// Nothing is left to report to.
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
const wrapped = { ...handler };
|
|
46
|
+
const fetchHandler = handler.fetch;
|
|
47
|
+
if (fetchHandler !== undefined) {
|
|
48
|
+
const run = (request, env, ctx) => fetchHandler.call(handler, request, env, ctx);
|
|
49
|
+
const serveOptions = opts.serve;
|
|
50
|
+
wrapped.fetch = async (request, env, ctx) => {
|
|
51
|
+
const telemetry = await telemetryFor(env);
|
|
52
|
+
if (telemetry === undefined)
|
|
53
|
+
return run(request, env, ctx);
|
|
54
|
+
if (serveOptions === false) {
|
|
55
|
+
try {
|
|
56
|
+
return await run(request, env, ctx);
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
scheduleFlush(ctx, telemetry, opts.flush);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
let serve = served.get(telemetry);
|
|
63
|
+
if (serve === undefined) {
|
|
64
|
+
serve = instrumentServe(run, { ...serveOptions, telemetry });
|
|
65
|
+
served.set(telemetry, serve);
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
return await serve(request, env, ctx);
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
scheduleFlush(ctx, telemetry, opts.flush);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
const queueHandler = handler.queue;
|
|
76
|
+
if (queueHandler !== undefined) {
|
|
77
|
+
const queueFlush = {
|
|
78
|
+
...opts.flush,
|
|
79
|
+
forceMetrics: opts.flush?.forceMetrics ?? true,
|
|
80
|
+
};
|
|
81
|
+
wrapped.queue = async (batch, env, ctx) => {
|
|
82
|
+
const telemetry = await telemetryFor(env);
|
|
83
|
+
if (telemetry === undefined)
|
|
84
|
+
return queueHandler.call(handler, batch, env, ctx);
|
|
85
|
+
try {
|
|
86
|
+
return await traceQueueBatch(batch, () => queueHandler.call(handler, batch, env, ctx), {
|
|
87
|
+
telemetry,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
scheduleFlush(ctx, telemetry, queueFlush);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const scheduledHandler = handler.scheduled;
|
|
96
|
+
if (scheduledHandler !== undefined) {
|
|
97
|
+
const scheduledFlush = {
|
|
98
|
+
...opts.flush,
|
|
99
|
+
forceMetrics: opts.flush?.forceMetrics ?? true,
|
|
100
|
+
};
|
|
101
|
+
wrapped.scheduled = async (controller, env, ctx) => {
|
|
102
|
+
const telemetry = await telemetryFor(env);
|
|
103
|
+
if (telemetry === undefined)
|
|
104
|
+
return scheduledHandler.call(handler, controller, env, ctx);
|
|
105
|
+
try {
|
|
106
|
+
return await traceScheduled(controller, () => scheduledHandler.call(handler, controller, env, ctx), {
|
|
107
|
+
telemetry,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
scheduleFlush(ctx, telemetry, scheduledFlush);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
return wrapped;
|
|
116
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { LogRecordExporter, LogRecordProcessor, ReadWriteLogRecord } from "@opentelemetry/sdk-logs";
|
|
2
|
+
/** Options for {@link IsolatedBatchLogRecordProcessor}. */
|
|
3
|
+
export interface IsolatedBatchLogRecordProcessorOptions {
|
|
4
|
+
readonly exporter: LogRecordExporter;
|
|
5
|
+
readonly maxQueueSize?: number;
|
|
6
|
+
readonly maxExportBatchSize?: number;
|
|
7
|
+
readonly exportTimeoutMillis?: number;
|
|
8
|
+
}
|
|
9
|
+
/** Batching LogRecordProcessor whose flushes are strictly isolated to the calling invocation. */
|
|
10
|
+
export declare class IsolatedBatchLogRecordProcessor implements LogRecordProcessor {
|
|
11
|
+
private readonly exporter;
|
|
12
|
+
private readonly maxQueueSize;
|
|
13
|
+
private readonly maxExportBatchSize;
|
|
14
|
+
private readonly exportTimeoutMillis;
|
|
15
|
+
private buffer;
|
|
16
|
+
private shutdownOnce;
|
|
17
|
+
constructor(options: IsolatedBatchLogRecordProcessorOptions);
|
|
18
|
+
onEmit(logRecord: ReadWriteLogRecord): void;
|
|
19
|
+
forceFlush(): Promise<void>;
|
|
20
|
+
shutdown(): Promise<void>;
|
|
21
|
+
private flushExporter;
|
|
22
|
+
private exportBatch;
|
|
23
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Invocation-isolated batching LogRecordProcessor for workerd.
|
|
3
|
+
*
|
|
4
|
+
* Unlike BatchLogRecordProcessor wrapped in CoalescingLogRecordProcessor, each forceFlush()
|
|
5
|
+
* synchronously drains buffered records and exports them inside the calling invocation's own
|
|
6
|
+
* IoContext without sharing promises or arming cross-invocation timers.
|
|
7
|
+
*/
|
|
8
|
+
import { clampTimerMillis } from "@libo11y/core/internal";
|
|
9
|
+
import { context } from "@opentelemetry/api";
|
|
10
|
+
import { ExportResultCode, suppressTracing } from "@opentelemetry/core";
|
|
11
|
+
const DEFAULT_MAX_QUEUE_SIZE = 2048;
|
|
12
|
+
const DEFAULT_MAX_EXPORT_BATCH_SIZE = 512;
|
|
13
|
+
const DEFAULT_EXPORT_TIMEOUT_MILLIS = 5000;
|
|
14
|
+
/** Batching LogRecordProcessor whose flushes are strictly isolated to the calling invocation. */
|
|
15
|
+
export class IsolatedBatchLogRecordProcessor {
|
|
16
|
+
exporter;
|
|
17
|
+
maxQueueSize;
|
|
18
|
+
maxExportBatchSize;
|
|
19
|
+
exportTimeoutMillis;
|
|
20
|
+
buffer = [];
|
|
21
|
+
shutdownOnce;
|
|
22
|
+
constructor(options) {
|
|
23
|
+
this.exporter = options.exporter;
|
|
24
|
+
const rawQueue = options.maxQueueSize;
|
|
25
|
+
this.maxQueueSize =
|
|
26
|
+
typeof rawQueue === "number" && Number.isFinite(rawQueue)
|
|
27
|
+
? Math.max(0, Math.floor(rawQueue))
|
|
28
|
+
: DEFAULT_MAX_QUEUE_SIZE;
|
|
29
|
+
const rawBatch = options.maxExportBatchSize;
|
|
30
|
+
const parsedBatch = typeof rawBatch === "number" && Number.isFinite(rawBatch)
|
|
31
|
+
? Math.floor(rawBatch)
|
|
32
|
+
: DEFAULT_MAX_EXPORT_BATCH_SIZE;
|
|
33
|
+
this.maxExportBatchSize = Math.max(1, Math.min(parsedBatch, Math.max(1, this.maxQueueSize)));
|
|
34
|
+
const rawTimeout = options.exportTimeoutMillis;
|
|
35
|
+
this.exportTimeoutMillis =
|
|
36
|
+
typeof rawTimeout === "number" && !Number.isNaN(rawTimeout)
|
|
37
|
+
? clampTimerMillis(rawTimeout)
|
|
38
|
+
: DEFAULT_EXPORT_TIMEOUT_MILLIS;
|
|
39
|
+
}
|
|
40
|
+
onEmit(logRecord) {
|
|
41
|
+
if (this.shutdownOnce !== undefined || this.buffer.length >= this.maxQueueSize)
|
|
42
|
+
return;
|
|
43
|
+
this.buffer.push(logRecord);
|
|
44
|
+
}
|
|
45
|
+
async forceFlush() {
|
|
46
|
+
if (this.shutdownOnce !== undefined)
|
|
47
|
+
return;
|
|
48
|
+
const deadlineAt = Date.now() + this.exportTimeoutMillis;
|
|
49
|
+
const drained = this.buffer;
|
|
50
|
+
this.buffer = [];
|
|
51
|
+
let firstError;
|
|
52
|
+
if (drained.length > 0) {
|
|
53
|
+
const promises = [];
|
|
54
|
+
for (let i = 0; i < drained.length; i += this.maxExportBatchSize) {
|
|
55
|
+
promises.push(this.exportBatch(drained.slice(i, i + this.maxExportBatchSize), deadlineAt));
|
|
56
|
+
}
|
|
57
|
+
const settled = await Promise.allSettled(promises);
|
|
58
|
+
for (const res of settled) {
|
|
59
|
+
if (res.status === "rejected" && firstError === undefined)
|
|
60
|
+
firstError = res.reason;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
await this.flushExporter(deadlineAt);
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
if (firstError === undefined)
|
|
68
|
+
firstError = err;
|
|
69
|
+
}
|
|
70
|
+
if (firstError !== undefined)
|
|
71
|
+
throw firstError;
|
|
72
|
+
}
|
|
73
|
+
shutdown() {
|
|
74
|
+
if (this.shutdownOnce !== undefined)
|
|
75
|
+
return this.shutdownOnce;
|
|
76
|
+
this.shutdownOnce = (async () => {
|
|
77
|
+
const deadlineAt = Date.now() + this.exportTimeoutMillis;
|
|
78
|
+
const drained = this.buffer;
|
|
79
|
+
this.buffer = [];
|
|
80
|
+
if (drained.length > 0) {
|
|
81
|
+
const promises = [];
|
|
82
|
+
for (let i = 0; i < drained.length; i += this.maxExportBatchSize) {
|
|
83
|
+
promises.push(this.exportBatch(drained.slice(i, i + this.maxExportBatchSize), deadlineAt));
|
|
84
|
+
}
|
|
85
|
+
await Promise.allSettled(promises);
|
|
86
|
+
}
|
|
87
|
+
await this.exporter.shutdown();
|
|
88
|
+
})();
|
|
89
|
+
return this.shutdownOnce;
|
|
90
|
+
}
|
|
91
|
+
flushExporter(deadlineAt) {
|
|
92
|
+
const fn = this.exporter.forceFlush;
|
|
93
|
+
if (typeof fn !== "function")
|
|
94
|
+
return Promise.resolve();
|
|
95
|
+
const remaining = deadlineAt - Date.now();
|
|
96
|
+
if (remaining <= 0 && this.exportTimeoutMillis > 0) {
|
|
97
|
+
return Promise.reject(new Error("Timeout"));
|
|
98
|
+
}
|
|
99
|
+
return new Promise((resolve, reject) => {
|
|
100
|
+
let settled = false;
|
|
101
|
+
const timer = setTimeout(() => {
|
|
102
|
+
if (settled)
|
|
103
|
+
return;
|
|
104
|
+
settled = true;
|
|
105
|
+
reject(new Error("Timeout"));
|
|
106
|
+
}, clampTimerMillis(remaining));
|
|
107
|
+
Promise.resolve()
|
|
108
|
+
.then(() => fn.call(this.exporter))
|
|
109
|
+
.then(() => {
|
|
110
|
+
if (settled)
|
|
111
|
+
return;
|
|
112
|
+
settled = true;
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
resolve();
|
|
115
|
+
}, (err) => {
|
|
116
|
+
if (settled)
|
|
117
|
+
return;
|
|
118
|
+
settled = true;
|
|
119
|
+
clearTimeout(timer);
|
|
120
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
exportBatch(batch, deadlineAt) {
|
|
125
|
+
const remaining = deadlineAt - Date.now();
|
|
126
|
+
return new Promise((resolve, reject) => {
|
|
127
|
+
let settled = false;
|
|
128
|
+
const timer = setTimeout(() => {
|
|
129
|
+
if (settled)
|
|
130
|
+
return;
|
|
131
|
+
settled = true;
|
|
132
|
+
reject(new Error("Timeout"));
|
|
133
|
+
}, clampTimerMillis(remaining));
|
|
134
|
+
context.with(suppressTracing(context.active()), () => {
|
|
135
|
+
try {
|
|
136
|
+
this.exporter.export(batch, (result) => {
|
|
137
|
+
if (settled)
|
|
138
|
+
return;
|
|
139
|
+
settled = true;
|
|
140
|
+
clearTimeout(timer);
|
|
141
|
+
if (result.code === ExportResultCode.SUCCESS)
|
|
142
|
+
resolve();
|
|
143
|
+
else
|
|
144
|
+
reject(result.error ?? new Error("IsolatedBatchLogRecordProcessor: log record export failed"));
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
catch (err) {
|
|
148
|
+
if (settled)
|
|
149
|
+
return;
|
|
150
|
+
settled = true;
|
|
151
|
+
clearTimeout(timer);
|
|
152
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The metric reader of a Worker. A periodic reader cannot work in a Worker: a timer runs only while
|
|
3
|
+
* an invocation is alive, and one armed in one invocation never fires once that invocation is
|
|
4
|
+
* gone. This reader has no timer. It collects and exports when the telemetry flushes, skipping
|
|
5
|
+
* unchanged CUMULATIVE snapshots (while always exporting DELTA snapshots and pending exemplars),
|
|
6
|
+
* and optionally throttling collections to at most once per intervalMillis unless the active flush
|
|
7
|
+
* forces metrics (for queue and scheduled handlers on mixed Workers).
|
|
8
|
+
*/
|
|
9
|
+
import type { ExemplarStore } from "@libo11y/core";
|
|
10
|
+
import { MetricReader, type PushMetricExporter } from "@opentelemetry/sdk-metrics";
|
|
11
|
+
/** Options for FlushMetricReader. */
|
|
12
|
+
export interface FlushMetricReaderOptions {
|
|
13
|
+
readonly exporter: PushMetricExporter;
|
|
14
|
+
/** Optional exemplar store so unchanged cumulative values with new pending exemplars still export. */
|
|
15
|
+
readonly exemplars?: ExemplarStore;
|
|
16
|
+
/** The least time between two exports, in milliseconds. 0 collects on every flush and exports on change. */
|
|
17
|
+
readonly intervalMillis: number;
|
|
18
|
+
/** The collection deadline, in milliseconds. */
|
|
19
|
+
readonly timeoutMillis: number;
|
|
20
|
+
/** The clock. Default Date.now. */
|
|
21
|
+
readonly now?: () => number;
|
|
22
|
+
}
|
|
23
|
+
/** A dirty-aware metric reader that exports on flush, optionally throttled, and on shutdown. */
|
|
24
|
+
export declare class FlushMetricReader extends MetricReader {
|
|
25
|
+
private readonly exporter;
|
|
26
|
+
private readonly exemplars;
|
|
27
|
+
private readonly intervalMillis;
|
|
28
|
+
private readonly timeoutMillis;
|
|
29
|
+
private readonly now;
|
|
30
|
+
private last;
|
|
31
|
+
private collectingSince;
|
|
32
|
+
private collectingToken;
|
|
33
|
+
private lastExportedKey;
|
|
34
|
+
private latestDispatchedKey;
|
|
35
|
+
private lastSuccessSeq;
|
|
36
|
+
private nextSeq;
|
|
37
|
+
private inFlightCount;
|
|
38
|
+
constructor(opts: FlushMetricReaderOptions);
|
|
39
|
+
/** Whether a flush now would collect: the interval has passed since the last export began. */
|
|
40
|
+
due(): boolean;
|
|
41
|
+
private isCollecting;
|
|
42
|
+
protected onForceFlush(): Promise<void>;
|
|
43
|
+
protected onShutdown(): Promise<void>;
|
|
44
|
+
private run;
|
|
45
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { hasPendingExemplars } from "@libo11y/core/internal";
|
|
2
|
+
import { ExportResultCode, globalErrorHandler } from "@opentelemetry/core";
|
|
3
|
+
import { AggregationTemporality, DataPointType, MetricReader, } from "@opentelemetry/sdk-metrics";
|
|
4
|
+
import { activeFlushContext } from "./flush.js";
|
|
5
|
+
function exportOnce(exporter, metrics) {
|
|
6
|
+
return new Promise((resolve) => {
|
|
7
|
+
try {
|
|
8
|
+
exporter.export(metrics, resolve);
|
|
9
|
+
}
|
|
10
|
+
catch (err) {
|
|
11
|
+
resolve({ code: ExportResultCode.FAILED, error: err instanceof Error ? err : new Error(String(err)) });
|
|
12
|
+
}
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
function hasAnyDataPoints(rm) {
|
|
16
|
+
for (const sm of rm.scopeMetrics) {
|
|
17
|
+
for (const metric of sm.metrics) {
|
|
18
|
+
if (metric.dataPoints.length > 0)
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
function hasDeltaPoints(rm) {
|
|
25
|
+
for (const sm of rm.scopeMetrics) {
|
|
26
|
+
for (const metric of sm.metrics) {
|
|
27
|
+
if (metric.aggregationTemporality === AggregationTemporality.DELTA && metric.dataPoints.length > 0) {
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
function formatNumber(n) {
|
|
35
|
+
if (n === undefined)
|
|
36
|
+
return "u";
|
|
37
|
+
if (Object.is(n, -0))
|
|
38
|
+
return "-0";
|
|
39
|
+
return String(n);
|
|
40
|
+
}
|
|
41
|
+
function canonicalAttributes(attrs) {
|
|
42
|
+
const keys = Object.keys(attrs)
|
|
43
|
+
.filter((k) => attrs[k] !== undefined)
|
|
44
|
+
.sort();
|
|
45
|
+
if (keys.length === 0)
|
|
46
|
+
return "";
|
|
47
|
+
return JSON.stringify(keys.map((k) => [k, attrs[k]]));
|
|
48
|
+
}
|
|
49
|
+
function canonicalValue(metric, value) {
|
|
50
|
+
switch (metric.dataPointType) {
|
|
51
|
+
case DataPointType.SUM:
|
|
52
|
+
case DataPointType.GAUGE:
|
|
53
|
+
return formatNumber(value);
|
|
54
|
+
case DataPointType.HISTOGRAM: {
|
|
55
|
+
const h = value;
|
|
56
|
+
return JSON.stringify([
|
|
57
|
+
h.count,
|
|
58
|
+
formatNumber(h.sum),
|
|
59
|
+
formatNumber(h.min),
|
|
60
|
+
formatNumber(h.max),
|
|
61
|
+
h.buckets.boundaries,
|
|
62
|
+
h.buckets.counts,
|
|
63
|
+
]);
|
|
64
|
+
}
|
|
65
|
+
case DataPointType.EXPONENTIAL_HISTOGRAM: {
|
|
66
|
+
const eh = value;
|
|
67
|
+
return JSON.stringify([
|
|
68
|
+
eh.count,
|
|
69
|
+
formatNumber(eh.sum),
|
|
70
|
+
formatNumber(eh.min),
|
|
71
|
+
formatNumber(eh.max),
|
|
72
|
+
eh.scale,
|
|
73
|
+
eh.zeroCount,
|
|
74
|
+
eh.positive.offset,
|
|
75
|
+
eh.positive.bucketCounts,
|
|
76
|
+
eh.negative.offset,
|
|
77
|
+
eh.negative.bucketCounts,
|
|
78
|
+
]);
|
|
79
|
+
}
|
|
80
|
+
default:
|
|
81
|
+
return JSON.stringify(value);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Deterministic canonical fingerprint of all CUMULATIVE data points in rm, independent of
|
|
86
|
+
* collection timestamps and insertion order.
|
|
87
|
+
*/
|
|
88
|
+
function fingerprintCumulative(rm) {
|
|
89
|
+
const entries = [];
|
|
90
|
+
for (const sm of rm.scopeMetrics) {
|
|
91
|
+
const scope = `${sm.scope.name}\u0000${sm.scope.version ?? ""}\u0000${sm.scope.schemaUrl ?? ""}`;
|
|
92
|
+
for (const metric of sm.metrics) {
|
|
93
|
+
if (metric.aggregationTemporality !== AggregationTemporality.CUMULATIVE)
|
|
94
|
+
continue;
|
|
95
|
+
if (metric.dataPoints.length === 0)
|
|
96
|
+
continue;
|
|
97
|
+
const monotonic = metric.dataPointType === DataPointType.SUM ? (metric.isMonotonic ? "1" : "0") : "";
|
|
98
|
+
const metricType = String(metric.descriptor.type ?? "");
|
|
99
|
+
const descriptor = `${metric.descriptor.name}\u0000${metricType}\u0000${metric.descriptor.unit}\u0000${metric.dataPointType}\u0000${monotonic}`;
|
|
100
|
+
const points = metric.dataPoints
|
|
101
|
+
.map((dp) => `${canonicalAttributes(dp.attributes)}=${canonicalValue(metric, dp.value)}`)
|
|
102
|
+
.sort();
|
|
103
|
+
entries.push(`${scope}\u0001${descriptor}\u0002${points.join("\u0003")}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
entries.sort();
|
|
107
|
+
return entries.join("\u0004");
|
|
108
|
+
}
|
|
109
|
+
/** A dirty-aware metric reader that exports on flush, optionally throttled, and on shutdown. */
|
|
110
|
+
export class FlushMetricReader extends MetricReader {
|
|
111
|
+
exporter;
|
|
112
|
+
exemplars;
|
|
113
|
+
intervalMillis;
|
|
114
|
+
timeoutMillis;
|
|
115
|
+
now;
|
|
116
|
+
last;
|
|
117
|
+
collectingSince;
|
|
118
|
+
collectingToken = 0;
|
|
119
|
+
lastExportedKey;
|
|
120
|
+
latestDispatchedKey;
|
|
121
|
+
lastSuccessSeq = 0;
|
|
122
|
+
nextSeq = 0;
|
|
123
|
+
inFlightCount = 0;
|
|
124
|
+
constructor(opts) {
|
|
125
|
+
const exporter = opts.exporter;
|
|
126
|
+
super({
|
|
127
|
+
...(exporter.selectAggregation === undefined
|
|
128
|
+
? {}
|
|
129
|
+
: { aggregationSelector: exporter.selectAggregation.bind(exporter) }),
|
|
130
|
+
...(exporter.selectAggregationTemporality === undefined
|
|
131
|
+
? {}
|
|
132
|
+
: { aggregationTemporalitySelector: exporter.selectAggregationTemporality.bind(exporter) }),
|
|
133
|
+
});
|
|
134
|
+
this.exporter = exporter;
|
|
135
|
+
this.exemplars = opts.exemplars;
|
|
136
|
+
this.intervalMillis = Math.max(0, Number.isFinite(opts.intervalMillis) ? opts.intervalMillis : 0);
|
|
137
|
+
this.timeoutMillis = opts.timeoutMillis;
|
|
138
|
+
this.now = opts.now ?? Date.now;
|
|
139
|
+
}
|
|
140
|
+
/** Whether a flush now would collect: the interval has passed since the last export began. */
|
|
141
|
+
due() {
|
|
142
|
+
if (this.last === undefined)
|
|
143
|
+
return true;
|
|
144
|
+
const elapsed = this.now() - this.last;
|
|
145
|
+
// A clock that went backwards is due, so a skewed clock cannot stop exports.
|
|
146
|
+
return elapsed < 0 || elapsed >= this.intervalMillis;
|
|
147
|
+
}
|
|
148
|
+
isCollecting() {
|
|
149
|
+
if (this.collectingSince === undefined)
|
|
150
|
+
return false;
|
|
151
|
+
const elapsed = this.now() - this.collectingSince;
|
|
152
|
+
const windowMillis = this.timeoutMillis > 0 ? this.timeoutMillis : this.intervalMillis;
|
|
153
|
+
// Match due(): a backwards clock or elapsed >= windowMillis releases a stale guard
|
|
154
|
+
// left behind if workerd cancelled an earlier invocation before finally ran.
|
|
155
|
+
if (elapsed < 0 || elapsed >= windowMillis) {
|
|
156
|
+
this.collectingSince = undefined;
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
async onForceFlush() {
|
|
162
|
+
const forced = activeFlushContext()?.forceMetrics === true;
|
|
163
|
+
const reserve = !forced && this.intervalMillis > 0;
|
|
164
|
+
if (reserve && (this.isCollecting() || !this.due()))
|
|
165
|
+
return;
|
|
166
|
+
const dispatched = await this.run(reserve);
|
|
167
|
+
if (dispatched)
|
|
168
|
+
await this.exporter.forceFlush();
|
|
169
|
+
}
|
|
170
|
+
async onShutdown() {
|
|
171
|
+
await this.run(false);
|
|
172
|
+
await this.exporter.shutdown();
|
|
173
|
+
}
|
|
174
|
+
// run collects once and exports when dirty. Two flushes never share one export promise: in
|
|
175
|
+
// workerd a promise belongs to the invocation that made it, so a flush that waited for another
|
|
176
|
+
// invocation's export could be left waiting when that invocation ends. Instead, inFlightCount
|
|
177
|
+
// and latestDispatchedKey are updated synchronously before awaiting export so concurrent
|
|
178
|
+
// read-only flushes never stampede, while intervening transitions such as 1 -> 2 -> 1 while 2 is
|
|
179
|
+
// in flight always dispatch.
|
|
180
|
+
async run(reserveCollection) {
|
|
181
|
+
let dispatched = false;
|
|
182
|
+
let myToken = 0;
|
|
183
|
+
if (reserveCollection) {
|
|
184
|
+
myToken = ++this.collectingToken;
|
|
185
|
+
this.collectingSince = this.now();
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
let resourceMetrics;
|
|
189
|
+
let key;
|
|
190
|
+
let trackCumulative;
|
|
191
|
+
let seq;
|
|
192
|
+
try {
|
|
193
|
+
const collected = await this.collect({ timeoutMillis: this.timeoutMillis });
|
|
194
|
+
resourceMetrics = collected.resourceMetrics;
|
|
195
|
+
if (!hasAnyDataPoints(resourceMetrics))
|
|
196
|
+
return false;
|
|
197
|
+
const hasDelta = hasDeltaPoints(resourceMetrics);
|
|
198
|
+
key = fingerprintCumulative(resourceMetrics);
|
|
199
|
+
const hasExemplars = this.exemplars !== undefined && hasPendingExemplars(this.exemplars, resourceMetrics);
|
|
200
|
+
if (!hasDelta && !hasExemplars) {
|
|
201
|
+
if ((this.inFlightCount === 0 && key === this.lastExportedKey) ||
|
|
202
|
+
(this.inFlightCount > 0 && key === this.latestDispatchedKey)) {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
trackCumulative = key !== "";
|
|
207
|
+
seq = ++this.nextSeq;
|
|
208
|
+
if (trackCumulative) {
|
|
209
|
+
this.inFlightCount += 1;
|
|
210
|
+
this.latestDispatchedKey = key;
|
|
211
|
+
}
|
|
212
|
+
this.last = this.now();
|
|
213
|
+
dispatched = true;
|
|
214
|
+
}
|
|
215
|
+
finally {
|
|
216
|
+
if (reserveCollection && this.collectingToken === myToken) {
|
|
217
|
+
this.collectingSince = undefined;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
let result;
|
|
221
|
+
try {
|
|
222
|
+
result = await exportOnce(this.exporter, resourceMetrics);
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
if (trackCumulative)
|
|
226
|
+
this.inFlightCount -= 1;
|
|
227
|
+
}
|
|
228
|
+
if (result.code === ExportResultCode.SUCCESS) {
|
|
229
|
+
if (trackCumulative && seq > this.lastSuccessSeq) {
|
|
230
|
+
this.lastSuccessSeq = seq;
|
|
231
|
+
this.lastExportedKey = key;
|
|
232
|
+
}
|
|
233
|
+
return true;
|
|
234
|
+
}
|
|
235
|
+
throw result.error ?? new Error("o11y: metric export failed");
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
globalErrorHandler(err);
|
|
239
|
+
return dispatched;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Workers Platform: OTEL_* from the Worker's env bindings and never from a process environment,
|
|
3
|
+
* the AsyncLocalStorage context, the Workers resource, OTLP/HTTP export over fetch, console lines
|
|
4
|
+
* through console.log and console.warn (Workers Logs), crypto.subtle for SHA-1 and
|
|
5
|
+
* crypto.randomUUID. No runtime metrics: an isolate has no process to measure. Flushes are
|
|
6
|
+
* isolated: a flush waits only for what it exports itself, never for another invocation's exports.
|
|
7
|
+
*/
|
|
8
|
+
import type { Platform } from "@libo11y/core";
|
|
9
|
+
import { type WorkersExporterOptions } from "./exporters.ts";
|
|
10
|
+
/**
|
|
11
|
+
* The default of WorkersPlatformOptions.metricsFlushIntervalMillis for setup() and
|
|
12
|
+
* createTelemetry(): 0 (flush changed metrics within each invocation; unchanged cumulative
|
|
13
|
+
* snapshots are skipped).
|
|
14
|
+
*/
|
|
15
|
+
export declare const DEFAULT_METRICS_FLUSH_INTERVAL_MILLIS = 0;
|
|
16
|
+
/**
|
|
17
|
+
* The default metricsFlushIntervalMillis applied by instrument() when HTTP RED metrics are
|
|
18
|
+
* enabled (serve !== false): 15 s.
|
|
19
|
+
*/
|
|
20
|
+
export declare const DEFAULT_INSTRUMENT_METRICS_FLUSH_INTERVAL_MILLIS = 15000;
|
|
21
|
+
/** Options for workersPlatform. */
|
|
22
|
+
export interface WorkersPlatformOptions {
|
|
23
|
+
/**
|
|
24
|
+
* The Worker's env bindings. Its string-valued OTEL_* keys are the standard variables; every
|
|
25
|
+
* other key is ignored. Never read in hermetic mode.
|
|
26
|
+
*/
|
|
27
|
+
readonly env?: Readonly<Record<string, unknown>>;
|
|
28
|
+
/** Where and how to export. Each field beats its OTEL_EXPORTER_OTLP_* variable. */
|
|
29
|
+
readonly exporter?: WorkersExporterOptions;
|
|
30
|
+
/**
|
|
31
|
+
* The least time between two metric exports of one isolate, in milliseconds. Traces and logs
|
|
32
|
+
* export on every flush; metrics export when changed (or on any DELTA data point) once this
|
|
33
|
+
* interval has passed since the last export. Default 0 for setup() (flush-on-change);
|
|
34
|
+
* instrument() defaults to 15000 when wrapping fetch with instrumentServe (while queue and
|
|
35
|
+
* scheduled flushes force changed metrics via forceMetrics: true).
|
|
36
|
+
*/
|
|
37
|
+
readonly metricsFlushIntervalMillis?: number;
|
|
38
|
+
}
|
|
39
|
+
/** A new Workers Platform for createTelemetryWith and setupWith. */
|
|
40
|
+
export declare function workersPlatform(opts?: WorkersPlatformOptions): Platform;
|
package/dist/platform.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { setLogProcessorFactory } from "@libo11y/core/internal";
|
|
2
|
+
import { createContextManager } from "./context.js";
|
|
3
|
+
import { otelEnv } from "./env.js";
|
|
4
|
+
import { buildExporters } from "./exporters.js";
|
|
5
|
+
import { IsolatedBatchLogRecordProcessor } from "./log-processor.js";
|
|
6
|
+
import { detectWorkersResource } from "./resource.js";
|
|
7
|
+
/**
|
|
8
|
+
* The default of WorkersPlatformOptions.metricsFlushIntervalMillis for setup() and
|
|
9
|
+
* createTelemetry(): 0 (flush changed metrics within each invocation; unchanged cumulative
|
|
10
|
+
* snapshots are skipped).
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_METRICS_FLUSH_INTERVAL_MILLIS = 0;
|
|
13
|
+
/**
|
|
14
|
+
* The default metricsFlushIntervalMillis applied by instrument() when HTTP RED metrics are
|
|
15
|
+
* enabled (serve !== false): 15 s.
|
|
16
|
+
*/
|
|
17
|
+
export const DEFAULT_INSTRUMENT_METRICS_FLUSH_INTERVAL_MILLIS = 15000;
|
|
18
|
+
/** A new Workers Platform for createTelemetryWith and setupWith. */
|
|
19
|
+
export function workersPlatform(opts = {}) {
|
|
20
|
+
const env = otelEnv(opts.env);
|
|
21
|
+
const interval = opts.metricsFlushIntervalMillis;
|
|
22
|
+
const metricsFlushIntervalMillis = typeof interval === "number" && Number.isFinite(interval) && interval >= 0
|
|
23
|
+
? interval
|
|
24
|
+
: DEFAULT_METRICS_FLUSH_INTERVAL_MILLIS;
|
|
25
|
+
// Bound now, before captureConsole patches the console, so a sink line never re-enters capture.
|
|
26
|
+
const log = console.log.bind(console);
|
|
27
|
+
const warn = console.warn.bind(console);
|
|
28
|
+
const platform = {
|
|
29
|
+
name: "workers",
|
|
30
|
+
env: () => env,
|
|
31
|
+
detectResource: (hermetic) => detectWorkersResource(hermetic, env),
|
|
32
|
+
contextManager: createContextManager,
|
|
33
|
+
buildExporters: (req) => buildExporters(req, { env, exporter: opts.exporter, metricsFlushIntervalMillis }),
|
|
34
|
+
writeConsoleLine: (line) => log(line),
|
|
35
|
+
writeDiagnosticLine: (line) => warn(line),
|
|
36
|
+
sha1: async (data) => new Uint8Array(await crypto.subtle.digest("SHA-1", data)),
|
|
37
|
+
randomUUID: () => crypto.randomUUID(),
|
|
38
|
+
console: globalThis.console,
|
|
39
|
+
// Each flush belongs to one invocation: workerd ties a promise to the invocation that made it.
|
|
40
|
+
isolatedFlushes: true,
|
|
41
|
+
};
|
|
42
|
+
setLogProcessorFactory(platform, (exporter, batch) => new IsolatedBatchLogRecordProcessor({ exporter, ...batch }));
|
|
43
|
+
return platform;
|
|
44
|
+
}
|