@libo11y/test 0.0.0-stage → 0.1.2
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 +120 -2
- package/dist/assertions.d.ts +47 -0
- package/dist/assertions.js +170 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/otlp-schema.d.ts +20 -0
- package/dist/otlp-schema.js +294 -0
- package/dist/protowire.d.ts +68 -0
- package/dist/protowire.js +299 -0
- package/dist/recorder.d.ts +94 -0
- package/dist/recorder.js +301 -0
- package/dist/sink.d.ts +48 -0
- package/dist/sink.js +199 -0
- package/package.json +38 -4
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The recorder: a hermetic libo11y telemetry over in-memory signals, as Go's o11ytest.Start builds.
|
|
3
|
+
* It never installs a provider globally. The one global it may touch is the OpenTelemetry context
|
|
4
|
+
* manager, which OTel JS keeps process-wide: without one no span is ever active, so the recorder
|
|
5
|
+
* installs an AsyncLocalStorageContextManager when none is registered, leaves any existing one, and
|
|
6
|
+
* removes its own when the last recorder holding it shuts down.
|
|
7
|
+
*/
|
|
8
|
+
import { type LogLevel, type ResourceMetricsWithExemplars, type Telemetry, type TelemetryOptions } from "@libo11y/core";
|
|
9
|
+
import { type Attributes } from "@opentelemetry/api";
|
|
10
|
+
import { type ReadableSpan } from "@opentelemetry/sdk-trace";
|
|
11
|
+
/** The options createRecorder takes: any TelemetryOptions except the signal plumbing it owns. */
|
|
12
|
+
export interface RecorderOptions extends Omit<TelemetryOptions, "spanExporter" | "spanProcessor" | "metricReader" | "logExporter" | "logProcessor" | "logExport" | "hermetic"> {
|
|
13
|
+
}
|
|
14
|
+
/** One log record as the OTLP leg emitted it, after classification. */
|
|
15
|
+
export interface RecordedLog {
|
|
16
|
+
readonly body: string;
|
|
17
|
+
readonly level: LogLevel;
|
|
18
|
+
readonly severityNumber: number;
|
|
19
|
+
/** The classified attributes. Groups are nested maps, as the OTLP leg carries them. */
|
|
20
|
+
readonly attributes: Readonly<Record<string, unknown>>;
|
|
21
|
+
/** Lowercase hex, present when the record was emitted inside a valid span context. */
|
|
22
|
+
readonly traceId?: string;
|
|
23
|
+
readonly spanId?: string;
|
|
24
|
+
/** The event.name attribute, for records emitted as events. */
|
|
25
|
+
readonly eventName?: string;
|
|
26
|
+
}
|
|
27
|
+
/** One exemplar in harness form. */
|
|
28
|
+
export interface RecordedExemplar {
|
|
29
|
+
/** Lowercase hex, present when the measurement ran inside a valid span context. */
|
|
30
|
+
readonly traceId?: string;
|
|
31
|
+
readonly spanId?: string;
|
|
32
|
+
readonly value: number;
|
|
33
|
+
/** The measurement's attributes that the data point does not carry. */
|
|
34
|
+
readonly filteredAttributes: Attributes;
|
|
35
|
+
}
|
|
36
|
+
/** The telemetry a recorder captured. */
|
|
37
|
+
export interface Recorder {
|
|
38
|
+
/** The hermetic telemetry under the harness. Inject its providers or logger into the code under test. */
|
|
39
|
+
readonly telemetry: Telemetry;
|
|
40
|
+
/** Every span ended so far, in end order, already redacted. */
|
|
41
|
+
spans(): readonly ReadableSpan[];
|
|
42
|
+
/** Every log record the OTLP leg emitted so far, in emission order, already classified. */
|
|
43
|
+
logs(): readonly RecordedLog[];
|
|
44
|
+
/**
|
|
45
|
+
* Collects every instrument through the manual reader, with exemplars attached. A collection
|
|
46
|
+
* consumes the exemplar store's samples, so each point also keeps the exemplars earlier
|
|
47
|
+
* collections attached to it. Rejects after shutdown.
|
|
48
|
+
*/
|
|
49
|
+
metrics(): Promise<ResourceMetricsWithExemplars>;
|
|
50
|
+
/** The names of every instrument with recorded data. */
|
|
51
|
+
metricNames(): Promise<readonly string[]>;
|
|
52
|
+
/** The exemplars on the named instrument, across all its data points. */
|
|
53
|
+
exemplars(instrument: string): Promise<readonly RecordedExemplar[]>;
|
|
54
|
+
/**
|
|
55
|
+
* Throws AssertionError if the code under test broke the libo11y specification: a tier-0 resource
|
|
56
|
+
* key missing, a secret-classified attribute counted on o11y.schema.violations or visible in a
|
|
57
|
+
* log or span attribute, or a registered event lacking an attribute its contract requires. It
|
|
58
|
+
* flushes first. Call it before shutdown: it collects metrics.
|
|
59
|
+
*/
|
|
60
|
+
assertConforms(): Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* Throws AssertionError unless every log recorded inside a span carries that span's trace ID.
|
|
63
|
+
* Records emitted outside any span are ignored.
|
|
64
|
+
*/
|
|
65
|
+
assertCorrelated(): void;
|
|
66
|
+
/**
|
|
67
|
+
* Throws AssertionError unless the correlation triangle closes: a recorded span, a log carrying
|
|
68
|
+
* its trace and span IDs, and an exemplar on metric carrying the same trace ID.
|
|
69
|
+
*/
|
|
70
|
+
assertTriangle(opts: {
|
|
71
|
+
readonly metric: string;
|
|
72
|
+
}): Promise<void>;
|
|
73
|
+
/** Shuts the telemetry down. Idempotent. What was recorded stays readable. */
|
|
74
|
+
shutdown(): Promise<void>;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Installs an AsyncLocalStorageContextManager as the global context manager unless a working one is
|
|
78
|
+
* already registered. The probe asks the active manager to carry a context through context.with.
|
|
79
|
+
* The installs are reference counted: the first recorder to install the manager owns it, every
|
|
80
|
+
* recorder created while it is the global holds it, and the returned release drops the hold. When
|
|
81
|
+
* the last hold goes and the manager is still the global one, context.disable() removes it, so
|
|
82
|
+
* recorders leak no global across test files that share a process. A manager registered by
|
|
83
|
+
* anyone else is never touched, and the release is a no-op.
|
|
84
|
+
*/
|
|
85
|
+
export declare function ensureContextManager(): () => void;
|
|
86
|
+
/** The level of an OTLP severity number: 1 to 4 is trace, 5 to 8 debug, and so on up to fatal. */
|
|
87
|
+
export declare function levelOf(severityNumber: number): LogLevel;
|
|
88
|
+
/**
|
|
89
|
+
* Builds a hermetic telemetry that records every signal in memory (Go o11ytest.Start). Defaults:
|
|
90
|
+
* service name "test", environment "test", debug level, no console, no runtime metrics, no startup
|
|
91
|
+
* summary, every span sampled and trace-based exemplars. OTEL_* variables have no effect. Caller
|
|
92
|
+
* options win over the defaults, except the injected span, metric and log plumbing.
|
|
93
|
+
*/
|
|
94
|
+
export declare function createRecorder(options?: RecorderOptions): Promise<Recorder>;
|
package/dist/recorder.js
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The recorder: a hermetic libo11y telemetry over in-memory signals, as Go's o11ytest.Start builds.
|
|
3
|
+
* It never installs a provider globally. The one global it may touch is the OpenTelemetry context
|
|
4
|
+
* manager, which OTel JS keeps process-wide: without one no span is ever active, so the recorder
|
|
5
|
+
* installs an AsyncLocalStorageContextManager when none is registered, leaves any existing one, and
|
|
6
|
+
* removes its own when the last recorder holding it shuts down.
|
|
7
|
+
*/
|
|
8
|
+
import { createTelemetryWith, exemplarsOf, } from "@libo11y/core";
|
|
9
|
+
import { createTestPlatform, exemplarStoreOf } from "@libo11y/core/testing";
|
|
10
|
+
import { context, createContextKey, isSpanContextValid, ROOT_CONTEXT, trace, } from "@opentelemetry/api";
|
|
11
|
+
import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
|
|
12
|
+
import { MetricReader } from "@opentelemetry/sdk-metrics";
|
|
13
|
+
import { AlwaysOnSampler, SimpleSpanProcessor, } from "@opentelemetry/sdk-trace";
|
|
14
|
+
import { conformanceProblems, correlationProblems, fail, triangleProblems, } from "./assertions.js";
|
|
15
|
+
const PROBE = createContextKey("libo11y.test.context-probe");
|
|
16
|
+
/** The manager recorders installed and how many live recorders hold it. */
|
|
17
|
+
let owned;
|
|
18
|
+
/** Whether manager is the global one: only then does its own with change context.active(). */
|
|
19
|
+
function isGlobalManager(manager) {
|
|
20
|
+
const ctx = ROOT_CONTEXT.setValue(PROBE, manager);
|
|
21
|
+
return manager.with(ctx, () => context.active() === ctx);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Installs an AsyncLocalStorageContextManager as the global context manager unless a working one is
|
|
25
|
+
* already registered. The probe asks the active manager to carry a context through context.with.
|
|
26
|
+
* The installs are reference counted: the first recorder to install the manager owns it, every
|
|
27
|
+
* recorder created while it is the global holds it, and the returned release drops the hold. When
|
|
28
|
+
* the last hold goes and the manager is still the global one, context.disable() removes it, so
|
|
29
|
+
* recorders leak no global across test files that share a process. A manager registered by
|
|
30
|
+
* anyone else is never touched, and the release is a no-op.
|
|
31
|
+
*/
|
|
32
|
+
export function ensureContextManager() {
|
|
33
|
+
const ctx = ROOT_CONTEXT.setValue(PROBE, true);
|
|
34
|
+
if (owned !== undefined && isGlobalManager(owned.manager)) {
|
|
35
|
+
owned.holders++;
|
|
36
|
+
return releaser(owned);
|
|
37
|
+
}
|
|
38
|
+
if (context.with(ctx, () => context.active() === ctx))
|
|
39
|
+
return () => { };
|
|
40
|
+
const manager = new AsyncLocalStorageContextManager().enable();
|
|
41
|
+
if (!context.setGlobalContextManager(manager)) {
|
|
42
|
+
manager.disable();
|
|
43
|
+
return () => { };
|
|
44
|
+
}
|
|
45
|
+
owned = { manager, holders: 1 };
|
|
46
|
+
return releaser(owned);
|
|
47
|
+
}
|
|
48
|
+
function releaser(hold) {
|
|
49
|
+
let released = false;
|
|
50
|
+
return () => {
|
|
51
|
+
if (released)
|
|
52
|
+
return;
|
|
53
|
+
released = true;
|
|
54
|
+
hold.holders--;
|
|
55
|
+
if (hold.holders > 0)
|
|
56
|
+
return;
|
|
57
|
+
if (owned === hold)
|
|
58
|
+
owned = undefined;
|
|
59
|
+
if (isGlobalManager(hold.manager))
|
|
60
|
+
context.disable();
|
|
61
|
+
else
|
|
62
|
+
hold.manager.disable();
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** A span exporter that keeps every span it is given, even after shutdown. */
|
|
66
|
+
class SpanRecording {
|
|
67
|
+
spans = [];
|
|
68
|
+
export(spans, resultCallback) {
|
|
69
|
+
this.spans.push(...spans);
|
|
70
|
+
resultCallback({ code: 0 });
|
|
71
|
+
}
|
|
72
|
+
async shutdown() { }
|
|
73
|
+
async forceFlush() { }
|
|
74
|
+
}
|
|
75
|
+
const LEVELS = ["trace", "debug", "info", "warn", "error", "fatal"];
|
|
76
|
+
/** The level of an OTLP severity number: 1 to 4 is trace, 5 to 8 debug, and so on up to fatal. */
|
|
77
|
+
export function levelOf(severityNumber) {
|
|
78
|
+
const i = Math.floor((severityNumber - 1) / 4);
|
|
79
|
+
return LEVELS[Math.min(Math.max(i, 0), LEVELS.length - 1)];
|
|
80
|
+
}
|
|
81
|
+
/** A log record processor that snapshots each record, classified, as it is emitted. */
|
|
82
|
+
class LogRecording {
|
|
83
|
+
logs = [];
|
|
84
|
+
/**
|
|
85
|
+
* onEmit runs synchronously in the emitter's stack, so context.active() is the caller's real
|
|
86
|
+
* active context, whatever context the emitter passed. That span is the reference
|
|
87
|
+
* assertCorrelated checks the record's trace ID against: a record emitted with ROOT_CONTEXT or a
|
|
88
|
+
* stale context while a span is active is caught.
|
|
89
|
+
*/
|
|
90
|
+
onEmit(record) {
|
|
91
|
+
const severityNumber = record.severityNumber ?? 0;
|
|
92
|
+
const attributes = { ...record.attributes };
|
|
93
|
+
const eventName = record.eventName ?? attributes["event.name"];
|
|
94
|
+
const sc = record.spanContext;
|
|
95
|
+
const log = {
|
|
96
|
+
body: typeof record.body === "string" ? record.body : String(record.body ?? ""),
|
|
97
|
+
level: levelOf(severityNumber),
|
|
98
|
+
severityNumber,
|
|
99
|
+
attributes,
|
|
100
|
+
...(sc === undefined ? {} : { traceId: sc.traceId, spanId: sc.spanId }),
|
|
101
|
+
...(typeof eventName === "string" ? { eventName } : {}),
|
|
102
|
+
};
|
|
103
|
+
const active = trace.getSpanContext(context.active());
|
|
104
|
+
this.logs.push({ log, active: active !== undefined && isSpanContextValid(active) ? active : undefined });
|
|
105
|
+
}
|
|
106
|
+
async forceFlush() { }
|
|
107
|
+
async shutdown() { }
|
|
108
|
+
}
|
|
109
|
+
/** A metric reader whose collect the recorder calls on demand. */
|
|
110
|
+
class ManualReader extends MetricReader {
|
|
111
|
+
async onShutdown() { }
|
|
112
|
+
async onForceFlush() { }
|
|
113
|
+
}
|
|
114
|
+
const INJECTED = [
|
|
115
|
+
"spanExporter",
|
|
116
|
+
"spanProcessor",
|
|
117
|
+
"metricReader",
|
|
118
|
+
"logExporter",
|
|
119
|
+
"logProcessor",
|
|
120
|
+
"logExport",
|
|
121
|
+
"hermetic",
|
|
122
|
+
];
|
|
123
|
+
function seriesKey(scope, metric, attributes) {
|
|
124
|
+
const attrs = Object.keys(attributes)
|
|
125
|
+
.sort()
|
|
126
|
+
.map((k) => [k, attributes[k]]);
|
|
127
|
+
return JSON.stringify([scope, metric, attrs]);
|
|
128
|
+
}
|
|
129
|
+
function exemplarKey(e) {
|
|
130
|
+
return `${e.timeUnixNano}\u0000${e.traceId ?? ""}\u0000${e.spanId ?? ""}\u0000${e.value}`;
|
|
131
|
+
}
|
|
132
|
+
class RecorderImpl {
|
|
133
|
+
telemetry;
|
|
134
|
+
spanRecording;
|
|
135
|
+
logRecording;
|
|
136
|
+
reader;
|
|
137
|
+
/** The exemplars each series has carried, so a collection does not lose what an earlier one attached. */
|
|
138
|
+
seen = new Map();
|
|
139
|
+
releaseContext;
|
|
140
|
+
closing;
|
|
141
|
+
constructor(telemetry, spans, logs, reader, releaseContext) {
|
|
142
|
+
this.telemetry = telemetry;
|
|
143
|
+
this.releaseContext = releaseContext;
|
|
144
|
+
this.spanRecording = spans;
|
|
145
|
+
this.logRecording = logs;
|
|
146
|
+
this.reader = reader;
|
|
147
|
+
}
|
|
148
|
+
spans() {
|
|
149
|
+
return [...this.spanRecording.spans];
|
|
150
|
+
}
|
|
151
|
+
logs() {
|
|
152
|
+
return this.logRecording.logs.map((c) => c.log);
|
|
153
|
+
}
|
|
154
|
+
async metrics() {
|
|
155
|
+
let collected;
|
|
156
|
+
try {
|
|
157
|
+
collected = await this.reader.collect();
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
throw new Error(`o11ytest: collecting metrics: ${err instanceof Error ? err.message : String(err)}`, {
|
|
161
|
+
cause: err,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
if (collected.errors.length > 0) {
|
|
165
|
+
throw new Error(`o11ytest: collecting metrics: ${collected.errors.map(String).join("; ")}`, {
|
|
166
|
+
cause: collected.errors[0],
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
return this.remember(exemplarStoreOf(this.telemetry).attach(collected.resourceMetrics));
|
|
170
|
+
}
|
|
171
|
+
// remember merges each point's newly attached exemplars with those its series carried before.
|
|
172
|
+
remember(rm) {
|
|
173
|
+
const scopeMetrics = rm.scopeMetrics.map((sm) => {
|
|
174
|
+
const scope = `${sm.scope.name}\u0000${sm.scope.version ?? ""}`;
|
|
175
|
+
const metrics = sm.metrics.map((metric) => {
|
|
176
|
+
const dataPoints = metric.dataPoints.map((point) => {
|
|
177
|
+
const key = seriesKey(scope, metric.descriptor.name, point.attributes);
|
|
178
|
+
const known = this.seen.get(key) ?? [];
|
|
179
|
+
const keys = new Set(known.map(exemplarKey));
|
|
180
|
+
const merged = [...known, ...exemplarsOf(point).filter((e) => !keys.has(exemplarKey(e)))];
|
|
181
|
+
if (merged.length === 0)
|
|
182
|
+
return point;
|
|
183
|
+
this.seen.set(key, merged);
|
|
184
|
+
return { ...point, exemplars: merged };
|
|
185
|
+
});
|
|
186
|
+
return { ...metric, dataPoints };
|
|
187
|
+
});
|
|
188
|
+
return { ...sm, metrics };
|
|
189
|
+
});
|
|
190
|
+
return { ...rm, scopeMetrics };
|
|
191
|
+
}
|
|
192
|
+
async metricNames() {
|
|
193
|
+
const rm = await this.metrics();
|
|
194
|
+
return rm.scopeMetrics.flatMap((sm) => sm.metrics.map((m) => m.descriptor.name));
|
|
195
|
+
}
|
|
196
|
+
async exemplars(instrument) {
|
|
197
|
+
const rm = await this.metrics();
|
|
198
|
+
const out = [];
|
|
199
|
+
for (const sm of rm.scopeMetrics) {
|
|
200
|
+
for (const metric of sm.metrics) {
|
|
201
|
+
if (metric.descriptor.name !== instrument)
|
|
202
|
+
continue;
|
|
203
|
+
for (const point of metric.dataPoints) {
|
|
204
|
+
for (const e of exemplarsOf(point)) {
|
|
205
|
+
out.push({
|
|
206
|
+
...(e.traceId === undefined ? {} : { traceId: e.traceId }),
|
|
207
|
+
...(e.spanId === undefined ? {} : { spanId: e.spanId }),
|
|
208
|
+
value: e.value,
|
|
209
|
+
filteredAttributes: e.filteredAttributes,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return out;
|
|
216
|
+
}
|
|
217
|
+
async assertConforms() {
|
|
218
|
+
const preflight = [];
|
|
219
|
+
const flushed = await this.telemetry.forceFlush();
|
|
220
|
+
for (const { error } of flushed.errors) {
|
|
221
|
+
preflight.push(`o11ytest: flushing before conformance checks: ${String(error)}`);
|
|
222
|
+
}
|
|
223
|
+
let metrics;
|
|
224
|
+
try {
|
|
225
|
+
metrics = await this.metrics();
|
|
226
|
+
}
|
|
227
|
+
catch (err) {
|
|
228
|
+
preflight.push(err instanceof Error ? err.message : String(err));
|
|
229
|
+
}
|
|
230
|
+
const problems = conformanceProblems({
|
|
231
|
+
resource: this.telemetry.resource.attributes,
|
|
232
|
+
preflight,
|
|
233
|
+
...(metrics === undefined ? {} : { metrics }),
|
|
234
|
+
logs: this.logs(),
|
|
235
|
+
spans: this.spans(),
|
|
236
|
+
});
|
|
237
|
+
if (problems.length > 0)
|
|
238
|
+
fail(problems);
|
|
239
|
+
}
|
|
240
|
+
assertCorrelated() {
|
|
241
|
+
const problems = correlationProblems(this.logRecording.logs);
|
|
242
|
+
if (problems.length > 0)
|
|
243
|
+
fail(problems);
|
|
244
|
+
}
|
|
245
|
+
async assertTriangle(opts) {
|
|
246
|
+
const problems = triangleProblems(opts.metric, this.spans(), this.logs(), await this.exemplars(opts.metric));
|
|
247
|
+
if (problems.length > 0)
|
|
248
|
+
fail(problems);
|
|
249
|
+
}
|
|
250
|
+
shutdown() {
|
|
251
|
+
// The hold is released however the shutdown settles, so a rejection cannot leak the manager.
|
|
252
|
+
this.closing ??= this.telemetry
|
|
253
|
+
.shutdown()
|
|
254
|
+
.finally(() => this.releaseContext())
|
|
255
|
+
.then((report) => {
|
|
256
|
+
if (report.ok)
|
|
257
|
+
return;
|
|
258
|
+
const detail = report.errors.map(({ signal, error }) => `${signal}: ${String(error)}`).join("; ");
|
|
259
|
+
throw new Error(`o11ytest: shutdown: ${detail}`);
|
|
260
|
+
});
|
|
261
|
+
return this.closing;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Builds a hermetic telemetry that records every signal in memory (Go o11ytest.Start). Defaults:
|
|
266
|
+
* service name "test", environment "test", debug level, no console, no runtime metrics, no startup
|
|
267
|
+
* summary, every span sampled and trace-based exemplars. OTEL_* variables have no effect. Caller
|
|
268
|
+
* options win over the defaults, except the injected span, metric and log plumbing.
|
|
269
|
+
*/
|
|
270
|
+
export async function createRecorder(options = {}) {
|
|
271
|
+
const releaseContext = ensureContextManager();
|
|
272
|
+
const spans = new SpanRecording();
|
|
273
|
+
const logs = new LogRecording();
|
|
274
|
+
const reader = new ManualReader();
|
|
275
|
+
const caller = { ...options };
|
|
276
|
+
for (const key of INJECTED)
|
|
277
|
+
delete caller[key];
|
|
278
|
+
let telemetry;
|
|
279
|
+
try {
|
|
280
|
+
telemetry = await createTelemetryWith({
|
|
281
|
+
serviceName: "test",
|
|
282
|
+
environment: "test",
|
|
283
|
+
logLevel: "debug",
|
|
284
|
+
console: false,
|
|
285
|
+
runtimeMetrics: false,
|
|
286
|
+
startupSummary: false,
|
|
287
|
+
sampler: new AlwaysOnSampler(),
|
|
288
|
+
exemplarFilter: "trace_based",
|
|
289
|
+
...caller,
|
|
290
|
+
hermetic: true,
|
|
291
|
+
spanProcessor: new SimpleSpanProcessor({ exporter: spans }),
|
|
292
|
+
metricReader: reader,
|
|
293
|
+
logProcessor: logs,
|
|
294
|
+
}, createTestPlatform({ contextManager: () => new AsyncLocalStorageContextManager() }));
|
|
295
|
+
}
|
|
296
|
+
catch (err) {
|
|
297
|
+
releaseContext();
|
|
298
|
+
throw err;
|
|
299
|
+
}
|
|
300
|
+
return new RecorderImpl(telemetry, spans, logs, reader, releaseContext);
|
|
301
|
+
}
|
package/dist/sink.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type OtlpSignal } from "./otlp-schema.ts";
|
|
2
|
+
/** One request the sink received on a signal path. */
|
|
3
|
+
export interface OtlpRequestInfo {
|
|
4
|
+
readonly path: string;
|
|
5
|
+
/** The media type, without parameters. */
|
|
6
|
+
readonly contentType: string;
|
|
7
|
+
/** The Content-Encoding header, when present. */
|
|
8
|
+
readonly encoding: string | undefined;
|
|
9
|
+
/** The body's length as received, before inflating. */
|
|
10
|
+
readonly bytes: number;
|
|
11
|
+
}
|
|
12
|
+
/** Options for startOtlpSink. */
|
|
13
|
+
export interface OtlpSinkOptions {
|
|
14
|
+
/** The status every signal request gets, to simulate 429 or 503. Default 200. Only 200 stores. */
|
|
15
|
+
readonly status?: number;
|
|
16
|
+
/** A Retry-After header sent with every signal request's response. */
|
|
17
|
+
readonly retryAfter?: string;
|
|
18
|
+
}
|
|
19
|
+
/** A running OTLP/HTTP sink. */
|
|
20
|
+
export interface OtlpSink {
|
|
21
|
+
/** The base URL, http://127.0.0.1:<port>, for OTEL_EXPORTER_OTLP_ENDPOINT. */
|
|
22
|
+
readonly url: string;
|
|
23
|
+
/** Each accepted ExportTraceServiceRequest, decoded into OTLP/JSON shape, in arrival order. */
|
|
24
|
+
traces(): readonly unknown[];
|
|
25
|
+
/** Each accepted ExportMetricsServiceRequest, decoded into OTLP/JSON shape, in arrival order. */
|
|
26
|
+
metrics(): readonly unknown[];
|
|
27
|
+
/** Each accepted ExportLogsServiceRequest, decoded into OTLP/JSON shape, in arrival order. */
|
|
28
|
+
logs(): readonly unknown[];
|
|
29
|
+
/** Every request to a signal path, whatever its outcome, in arrival order. */
|
|
30
|
+
requests(): readonly OtlpRequestInfo[];
|
|
31
|
+
/** Resolves once signal has count accepted requests (default 1); rejects after timeoutMillis (default 5000). */
|
|
32
|
+
waitFor(signal: OtlpSignal, count?: number, timeoutMillis?: number): Promise<void>;
|
|
33
|
+
/** Stops the server, drops open connections and rejects pending waitFor calls. Idempotent. */
|
|
34
|
+
close(): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
/** The default cap on a request body as received: 32 MiB. */
|
|
37
|
+
export declare const MAX_BODY_BYTES: number;
|
|
38
|
+
/** The default cap on a gzip body once inflated: 32 MiB. */
|
|
39
|
+
export declare const MAX_INFLATED_BYTES: number;
|
|
40
|
+
/** Size limits for a sink. Internal: startOtlpSink uses the 32 MiB defaults. */
|
|
41
|
+
export interface SinkLimits {
|
|
42
|
+
readonly maxBodyBytes: number;
|
|
43
|
+
readonly maxInflatedBytes: number;
|
|
44
|
+
}
|
|
45
|
+
/** Starts an OTLP/HTTP sink on 127.0.0.1 at a free port. Bodies are capped at 32 MiB, inflated or not. */
|
|
46
|
+
export declare function startOtlpSink(opts?: OtlpSinkOptions): Promise<OtlpSink>;
|
|
47
|
+
/** startOtlpSink with explicit size limits. Internal: not exported from the package. */
|
|
48
|
+
export declare function startOtlpSinkWithLimits(opts: OtlpSinkOptions, limits: SinkLimits): Promise<OtlpSink>;
|
package/dist/sink.js
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An in-process OTLP/HTTP sink for tests: a node:http server on 127.0.0.1 that accepts
|
|
3
|
+
* POST /v1/traces, /v1/metrics and /v1/logs as application/json or application/x-protobuf, plain
|
|
4
|
+
* or gzip-encoded, and keeps each request decoded into its OTLP/JSON shape. It works on Bun and Node.
|
|
5
|
+
*/
|
|
6
|
+
import { createServer } from "node:http";
|
|
7
|
+
import { gunzipSync } from "node:zlib";
|
|
8
|
+
import { decodeOtlpProtobuf } from "./otlp-schema.js";
|
|
9
|
+
const PATHS = {
|
|
10
|
+
"/v1/traces": "traces",
|
|
11
|
+
"/v1/metrics": "metrics",
|
|
12
|
+
"/v1/logs": "logs",
|
|
13
|
+
};
|
|
14
|
+
const PROTOBUF_TYPES = new Set(["application/x-protobuf", "application/protobuf"]);
|
|
15
|
+
const JSON_TYPE = "application/json";
|
|
16
|
+
class HttpError extends Error {
|
|
17
|
+
status;
|
|
18
|
+
constructor(status, message) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.status = status;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** The default cap on a request body as received: 32 MiB. */
|
|
24
|
+
export const MAX_BODY_BYTES = 32 * 1024 * 1024;
|
|
25
|
+
/** The default cap on a gzip body once inflated: 32 MiB. */
|
|
26
|
+
export const MAX_INFLATED_BYTES = 32 * 1024 * 1024;
|
|
27
|
+
// readBody collects the body, counting into seen. Past limit it stops collecting and rejects with
|
|
28
|
+
// 413; the rest of the body is discarded unread.
|
|
29
|
+
function readBody(req, limit, seen) {
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
const chunks = [];
|
|
32
|
+
const onData = (chunk) => {
|
|
33
|
+
seen.bytes += chunk.length;
|
|
34
|
+
if (seen.bytes > limit) {
|
|
35
|
+
req.off("data", onData);
|
|
36
|
+
req.resume();
|
|
37
|
+
reject(new HttpError(413, `o11ytest: sink: body exceeds ${limit} bytes`));
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
chunks.push(chunk);
|
|
41
|
+
};
|
|
42
|
+
req.on("data", onData);
|
|
43
|
+
req.on("end", () => resolve(Buffer.concat(chunks)));
|
|
44
|
+
req.on("error", reject);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
function inflate(raw, limit) {
|
|
48
|
+
try {
|
|
49
|
+
return gunzipSync(raw, { maxOutputLength: limit });
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
if (err instanceof RangeError || err.code === "ERR_BUFFER_TOO_LARGE") {
|
|
53
|
+
throw new HttpError(413, `o11ytest: sink: inflated body exceeds ${limit} bytes`);
|
|
54
|
+
}
|
|
55
|
+
throw new HttpError(400, `o11ytest: sink: inflating: ${err instanceof Error ? err.message : String(err)}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function decode(signal, contentType, body) {
|
|
59
|
+
let value;
|
|
60
|
+
try {
|
|
61
|
+
value =
|
|
62
|
+
contentType === JSON_TYPE
|
|
63
|
+
? JSON.parse(new TextDecoder().decode(body))
|
|
64
|
+
: decodeOtlpProtobuf(signal, body);
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
throw new HttpError(400, `o11ytest: sink: decoding ${signal}: ${err instanceof Error ? err.message : String(err)}`);
|
|
68
|
+
}
|
|
69
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
70
|
+
throw new HttpError(400, `o11ytest: sink: decoding ${signal}: the JSON body is not an object`);
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
/** Starts an OTLP/HTTP sink on 127.0.0.1 at a free port. Bodies are capped at 32 MiB, inflated or not. */
|
|
75
|
+
export function startOtlpSink(opts = {}) {
|
|
76
|
+
return startOtlpSinkWithLimits(opts, {
|
|
77
|
+
maxBodyBytes: MAX_BODY_BYTES,
|
|
78
|
+
maxInflatedBytes: MAX_INFLATED_BYTES,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/** startOtlpSink with explicit size limits. Internal: not exported from the package. */
|
|
82
|
+
export async function startOtlpSinkWithLimits(opts, limits) {
|
|
83
|
+
const status = opts.status ?? 200;
|
|
84
|
+
const received = { traces: [], metrics: [], logs: [] };
|
|
85
|
+
const requests = [];
|
|
86
|
+
let waiters = [];
|
|
87
|
+
let closed = false;
|
|
88
|
+
const settle = () => {
|
|
89
|
+
waiters = waiters.filter((w) => {
|
|
90
|
+
if (received[w.signal].length < w.count)
|
|
91
|
+
return true;
|
|
92
|
+
w.resolve();
|
|
93
|
+
return false;
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
const closedError = (signal, count) => new Error(`o11ytest: sink: closed while waiting for ${count} ${signal} request(s); received ${received[signal].length}`);
|
|
97
|
+
const handle = async (req, res) => {
|
|
98
|
+
const path = (req.url ?? "").split("?")[0] ?? "";
|
|
99
|
+
const signal = PATHS[path];
|
|
100
|
+
if (signal === undefined)
|
|
101
|
+
throw new HttpError(404, `o11ytest: sink: no such path ${path}`);
|
|
102
|
+
if (req.method !== "POST")
|
|
103
|
+
throw new HttpError(405, `o11ytest: sink: ${req.method ?? ""} not allowed`);
|
|
104
|
+
const contentType = (req.headers["content-type"] ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
|
|
105
|
+
const encoding = req.headers["content-encoding"]?.trim().toLowerCase();
|
|
106
|
+
const seen = { bytes: 0 };
|
|
107
|
+
let raw;
|
|
108
|
+
try {
|
|
109
|
+
raw = await readBody(req, limits.maxBodyBytes, seen);
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
requests.push({ path, contentType, encoding, bytes: seen.bytes });
|
|
113
|
+
}
|
|
114
|
+
if (contentType !== JSON_TYPE && !PROTOBUF_TYPES.has(contentType)) {
|
|
115
|
+
throw new HttpError(415, `o11ytest: sink: unsupported content type ${contentType}`);
|
|
116
|
+
}
|
|
117
|
+
if (encoding !== undefined && encoding !== "gzip" && encoding !== "identity") {
|
|
118
|
+
throw new HttpError(415, `o11ytest: sink: unsupported content encoding ${encoding}`);
|
|
119
|
+
}
|
|
120
|
+
if (opts.retryAfter !== undefined)
|
|
121
|
+
res.setHeader("retry-after", opts.retryAfter);
|
|
122
|
+
if (status !== 200) {
|
|
123
|
+
res.writeHead(status, { "content-type": contentType, "content-length": "0" }).end();
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const body = encoding === "gzip" ? inflate(raw, limits.maxInflatedBytes) : raw;
|
|
127
|
+
received[signal].push(decode(signal, contentType, body));
|
|
128
|
+
res.writeHead(200, { "content-type": contentType, "content-length": "0" }).end();
|
|
129
|
+
settle();
|
|
130
|
+
};
|
|
131
|
+
const server = createServer((req, res) => {
|
|
132
|
+
handle(req, res).catch((err) => {
|
|
133
|
+
const code = err instanceof HttpError ? err.status : 500;
|
|
134
|
+
const text = err instanceof Error ? err.message : String(err);
|
|
135
|
+
if (!res.headersSent) {
|
|
136
|
+
res.writeHead(code, {
|
|
137
|
+
"content-type": "text/plain; charset=utf-8",
|
|
138
|
+
// A body cut off at the limit leaves unread bytes on the connection.
|
|
139
|
+
...(code === 413 ? { connection: "close" } : {}),
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
res.end(text);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
await new Promise((resolve, reject) => {
|
|
146
|
+
server.once("error", reject);
|
|
147
|
+
server.listen(0, "127.0.0.1", () => {
|
|
148
|
+
server.off("error", reject);
|
|
149
|
+
resolve();
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
const { port } = server.address();
|
|
153
|
+
let closing;
|
|
154
|
+
return {
|
|
155
|
+
url: `http://127.0.0.1:${port}`,
|
|
156
|
+
traces: () => [...received.traces],
|
|
157
|
+
metrics: () => [...received.metrics],
|
|
158
|
+
logs: () => [...received.logs],
|
|
159
|
+
requests: () => [...requests],
|
|
160
|
+
waitFor(signal, count = 1, timeoutMillis = 5000) {
|
|
161
|
+
if (received[signal].length >= count)
|
|
162
|
+
return Promise.resolve();
|
|
163
|
+
if (closed)
|
|
164
|
+
return Promise.reject(closedError(signal, count));
|
|
165
|
+
return new Promise((resolve, reject) => {
|
|
166
|
+
const timer = setTimeout(() => {
|
|
167
|
+
waiters = waiters.filter((w) => w !== waiter);
|
|
168
|
+
reject(new Error(`o11ytest: sink: timed out after ${timeoutMillis} ms waiting for ${count} ${signal} request(s); ` +
|
|
169
|
+
`received ${received[signal].length}`));
|
|
170
|
+
}, timeoutMillis);
|
|
171
|
+
timer.unref?.();
|
|
172
|
+
const waiter = {
|
|
173
|
+
signal,
|
|
174
|
+
count,
|
|
175
|
+
resolve: () => {
|
|
176
|
+
clearTimeout(timer);
|
|
177
|
+
resolve();
|
|
178
|
+
},
|
|
179
|
+
reject: (err) => {
|
|
180
|
+
clearTimeout(timer);
|
|
181
|
+
reject(err);
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
waiters.push(waiter);
|
|
185
|
+
});
|
|
186
|
+
},
|
|
187
|
+
close() {
|
|
188
|
+
closed = true;
|
|
189
|
+
for (const w of waiters)
|
|
190
|
+
w.reject(closedError(w.signal, w.count));
|
|
191
|
+
waiters = [];
|
|
192
|
+
closing ??= new Promise((resolve) => {
|
|
193
|
+
server.close(() => resolve());
|
|
194
|
+
server.closeAllConnections();
|
|
195
|
+
});
|
|
196
|
+
return closing;
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|