@libo11y/workers 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +114 -50
- package/dist/adapters.d.ts +102 -0
- package/dist/adapters.js +282 -0
- package/dist/env.d.ts +0 -6
- package/dist/env.js +2 -18
- package/dist/exporters.d.ts +16 -18
- package/dist/exporters.js +206 -95
- package/dist/flush.d.ts +25 -10
- package/dist/flush.js +32 -5
- package/dist/index.d.ts +12 -8
- package/dist/index.js +10 -6
- package/dist/instrument.d.ts +28 -33
- package/dist/instrument.js +35 -77
- package/dist/log-processor.d.ts +23 -0
- package/dist/log-processor.js +157 -0
- package/dist/metric-reader.d.ts +23 -3
- package/dist/metric-reader.js +189 -30
- package/dist/platform.d.ts +15 -4
- package/dist/platform.js +16 -3
- package/dist/rum-proxy.d.ts +69 -0
- package/dist/rum-proxy.js +174 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +6 -7
package/dist/index.js
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The libo11y platform for Cloudflare Workers and Durable Objects (workerd): setup memoized per
|
|
3
|
-
* isolate, OTLP/HTTP export over fetch or a binding's fetch, the
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* isolate, OTLP/HTTP export with bounded retry over fetch or a binding's fetch, the
|
|
4
|
+
* AsyncLocalStorage context, dirty-aware snapshot-diffing metrics exported on flush, flushing
|
|
5
|
+
* through waitUntil, composable Workers/DO/alarm/scheduled/queue tracing primitives, and the
|
|
6
|
+
* authenticated RUM gateway proxy helper. Needs the nodejs_compat (or nodejs_als) flag for
|
|
7
|
+
* node:async_hooks.
|
|
6
8
|
*/
|
|
7
9
|
export { O11yError, } from "@libo11y/core";
|
|
8
|
-
export { instrumentFetch, instrumentServe, setRoute, } from "@libo11y/
|
|
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";
|
|
9
12
|
export { createContextManager } from "./context.js";
|
|
10
13
|
export { scheduleFlush } from "./flush.js";
|
|
11
|
-
export { instrument
|
|
12
|
-
export { DEFAULT_METRICS_FLUSH_INTERVAL_MILLIS, workersPlatform, } from "./platform.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";
|
|
13
17
|
export { createTelemetry, setup } from "./setup.js";
|
|
14
18
|
export { VERSION } from "./version.js";
|
package/dist/instrument.d.ts
CHANGED
|
@@ -1,46 +1,38 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* instrument: a thin wrapper for a
|
|
3
|
-
*
|
|
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
4
|
*
|
|
5
|
-
* - fetch runs through instrumentServe from @libo11y/
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* - queue gets a CONSUMER span "process <queue>"
|
|
9
|
-
*
|
|
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.
|
|
10
12
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
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.
|
|
14
18
|
*
|
|
15
19
|
* The telemetry never fails an invocation: when setup fails, the handler runs without telemetry
|
|
16
20
|
* and the failure is written once per isolate to console.warn.
|
|
17
21
|
*/
|
|
18
|
-
import type {
|
|
19
|
-
import { type ServeOptions } from "@libo11y/
|
|
20
|
-
import { type
|
|
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";
|
|
21
26
|
import { type WorkersOptions } from "./setup.ts";
|
|
22
|
-
|
|
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
|
-
}
|
|
27
|
+
export type { WorkerMessageBatch, WorkerScheduledController } from "./adapters.ts";
|
|
36
28
|
/**
|
|
37
29
|
* The handlers instrument wraps, as a Worker's default export declares them. Every member is
|
|
38
30
|
* optional; members it does not know pass through.
|
|
39
31
|
*/
|
|
40
32
|
export interface WorkerHandler<Env> {
|
|
41
|
-
/** An HTTP request: a SERVER span through instrumentServe
|
|
33
|
+
/** An HTTP request: a SERVER span through instrumentServe unless `serve: false`. */
|
|
42
34
|
fetch?(request: Request, env: Env, ctx: WaitUntil): Response | Promise<Response>;
|
|
43
|
-
/** A queue batch: a CONSUMER span "process <queue>". */
|
|
35
|
+
/** A queue batch: a CONSUMER span "process <queue>" with extracted carrier links. */
|
|
44
36
|
queue?(batch: WorkerMessageBatch, env: Env, ctx: WaitUntil): void | Promise<void>;
|
|
45
37
|
/** A Cron Trigger: a SERVER span "scheduled <cron>". */
|
|
46
38
|
scheduled?(controller: WorkerScheduledController, env: Env, ctx: WaitUntil): void | Promise<void>;
|
|
@@ -58,10 +50,13 @@ export interface InstrumentOptions<Env> {
|
|
|
58
50
|
* It beats options.
|
|
59
51
|
*/
|
|
60
52
|
readonly telemetry?: (env: Env) => Telemetry | Promise<Telemetry>;
|
|
61
|
-
/**
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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;
|
|
65
60
|
}
|
|
66
61
|
/**
|
|
67
62
|
* Wraps a Worker's handler object: fetch, queue and scheduled run inside spans and flush through
|
package/dist/instrument.js
CHANGED
|
@@ -1,61 +1,8 @@
|
|
|
1
|
-
import { instrumentServe } from "@libo11y/
|
|
2
|
-
import {
|
|
1
|
+
import { instrumentServe } from "@libo11y/core/edge";
|
|
2
|
+
import { traceQueueBatch, traceScheduled, } from "./adapters.js";
|
|
3
3
|
import { scheduleFlush } from "./flush.js";
|
|
4
|
+
import { DEFAULT_INSTRUMENT_METRICS_FLUSH_INTERVAL_MILLIS } from "./platform.js";
|
|
4
5
|
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
6
|
/**
|
|
60
7
|
* Wraps a Worker's handler object: fetch, queue and scheduled run inside spans and flush through
|
|
61
8
|
* waitUntil after every invocation. The result is a new plain object with the handler's own
|
|
@@ -71,11 +18,16 @@ async function inSpan(telemetry, name, kind, attributes, fn) {
|
|
|
71
18
|
export function instrument(handler, opts) {
|
|
72
19
|
let warned = false;
|
|
73
20
|
const served = new WeakMap();
|
|
21
|
+
const usesInstrumentServe = handler.fetch !== undefined && opts.serve !== false;
|
|
74
22
|
const telemetryFor = async (env) => {
|
|
75
23
|
try {
|
|
76
24
|
if (opts.telemetry !== undefined)
|
|
77
25
|
return await opts.telemetry(env);
|
|
78
|
-
|
|
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);
|
|
79
31
|
}
|
|
80
32
|
catch (err) {
|
|
81
33
|
if (!warned) {
|
|
@@ -94,13 +46,22 @@ export function instrument(handler, opts) {
|
|
|
94
46
|
const fetchHandler = handler.fetch;
|
|
95
47
|
if (fetchHandler !== undefined) {
|
|
96
48
|
const run = (request, env, ctx) => fetchHandler.call(handler, request, env, ctx);
|
|
49
|
+
const serveOptions = opts.serve;
|
|
97
50
|
wrapped.fetch = async (request, env, ctx) => {
|
|
98
51
|
const telemetry = await telemetryFor(env);
|
|
99
52
|
if (telemetry === undefined)
|
|
100
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
|
+
}
|
|
101
62
|
let serve = served.get(telemetry);
|
|
102
63
|
if (serve === undefined) {
|
|
103
|
-
serve = instrumentServe(run, { ...
|
|
64
|
+
serve = instrumentServe(run, { ...serveOptions, telemetry });
|
|
104
65
|
served.set(telemetry, serve);
|
|
105
66
|
}
|
|
106
67
|
try {
|
|
@@ -113,44 +74,41 @@ export function instrument(handler, opts) {
|
|
|
113
74
|
}
|
|
114
75
|
const queueHandler = handler.queue;
|
|
115
76
|
if (queueHandler !== undefined) {
|
|
77
|
+
const queueFlush = {
|
|
78
|
+
...opts.flush,
|
|
79
|
+
forceMetrics: opts.flush?.forceMetrics ?? true,
|
|
80
|
+
};
|
|
116
81
|
wrapped.queue = async (batch, env, ctx) => {
|
|
117
82
|
const telemetry = await telemetryFor(env);
|
|
118
83
|
if (telemetry === undefined)
|
|
119
84
|
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
85
|
try {
|
|
129
|
-
return await
|
|
86
|
+
return await traceQueueBatch(batch, () => queueHandler.call(handler, batch, env, ctx), {
|
|
87
|
+
telemetry,
|
|
88
|
+
});
|
|
130
89
|
}
|
|
131
90
|
finally {
|
|
132
|
-
scheduleFlush(ctx, telemetry,
|
|
91
|
+
scheduleFlush(ctx, telemetry, queueFlush);
|
|
133
92
|
}
|
|
134
93
|
};
|
|
135
94
|
}
|
|
136
95
|
const scheduledHandler = handler.scheduled;
|
|
137
96
|
if (scheduledHandler !== undefined) {
|
|
97
|
+
const scheduledFlush = {
|
|
98
|
+
...opts.flush,
|
|
99
|
+
forceMetrics: opts.flush?.forceMetrics ?? true,
|
|
100
|
+
};
|
|
138
101
|
wrapped.scheduled = async (controller, env, ctx) => {
|
|
139
102
|
const telemetry = await telemetryFor(env);
|
|
140
103
|
if (telemetry === undefined)
|
|
141
104
|
return scheduledHandler.call(handler, controller, env, ctx);
|
|
142
|
-
const attributes = { "faas.trigger": "timer", "faas.cron": controller.cron };
|
|
143
105
|
try {
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
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));
|
|
106
|
+
return await traceScheduled(controller, () => scheduledHandler.call(handler, controller, env, ctx), {
|
|
107
|
+
telemetry,
|
|
108
|
+
});
|
|
151
109
|
}
|
|
152
110
|
finally {
|
|
153
|
-
scheduleFlush(ctx, telemetry,
|
|
111
|
+
scheduleFlush(ctx, telemetry, scheduledFlush);
|
|
154
112
|
}
|
|
155
113
|
};
|
|
156
114
|
}
|
|
@@ -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
|
+
}
|
package/dist/metric-reader.d.ts
CHANGED
|
@@ -1,24 +1,44 @@
|
|
|
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";
|
|
1
10
|
import { MetricReader, type PushMetricExporter } from "@opentelemetry/sdk-metrics";
|
|
2
11
|
/** Options for FlushMetricReader. */
|
|
3
12
|
export interface FlushMetricReaderOptions {
|
|
4
13
|
readonly exporter: PushMetricExporter;
|
|
5
|
-
/**
|
|
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. */
|
|
6
17
|
readonly intervalMillis: number;
|
|
7
18
|
/** The collection deadline, in milliseconds. */
|
|
8
19
|
readonly timeoutMillis: number;
|
|
9
20
|
/** The clock. Default Date.now. */
|
|
10
21
|
readonly now?: () => number;
|
|
11
22
|
}
|
|
12
|
-
/** A metric reader that exports on flush, throttled, and on shutdown. */
|
|
23
|
+
/** A dirty-aware metric reader that exports on flush, optionally throttled, and on shutdown. */
|
|
13
24
|
export declare class FlushMetricReader extends MetricReader {
|
|
14
25
|
private readonly exporter;
|
|
26
|
+
private readonly exemplars;
|
|
15
27
|
private readonly intervalMillis;
|
|
16
28
|
private readonly timeoutMillis;
|
|
17
29
|
private readonly now;
|
|
18
30
|
private last;
|
|
31
|
+
private collectingSince;
|
|
32
|
+
private collectingToken;
|
|
33
|
+
private lastExportedKey;
|
|
34
|
+
private latestDispatchedKey;
|
|
35
|
+
private lastSuccessSeq;
|
|
36
|
+
private nextSeq;
|
|
37
|
+
private inFlightCount;
|
|
19
38
|
constructor(opts: FlushMetricReaderOptions);
|
|
20
|
-
/** Whether a flush now would
|
|
39
|
+
/** Whether a flush now would collect: the interval has passed since the last export began. */
|
|
21
40
|
due(): boolean;
|
|
41
|
+
private isCollecting;
|
|
22
42
|
protected onForceFlush(): Promise<void>;
|
|
23
43
|
protected onShutdown(): Promise<void>;
|
|
24
44
|
private run;
|