@libo11y/server 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/dist/fetch.js ADDED
@@ -0,0 +1,107 @@
1
+ import { context, diag, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
2
+ import { asException, HEADERS_SETTER, instrumentResolver, methodAttributes, methodName, normalizeMethod, serverAttributes, } from "./http-common.js";
3
+ // The methods the Fetch standard upper-cases whatever case they are given in.
4
+ const FETCH_NORMALIZED = new Set(["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]);
5
+ /** The method fetch sends for raw: the Fetch standard upper-cases six methods in any case. */
6
+ function sentMethod(raw) {
7
+ const upper = raw.toUpperCase();
8
+ return FETCH_NORMALIZED.has(upper) ? upper : raw;
9
+ }
10
+ /** The error.type of a failed fetch: the error's name, such as TypeError or AbortError. */
11
+ function errorName(err) {
12
+ if (typeof err === "object" && err !== null && typeof err.name === "string") {
13
+ return err.name;
14
+ }
15
+ return "_OTHER";
16
+ }
17
+ /**
18
+ * Wraps fetchImpl (default: globalThis.fetch as it is now) with a CLIENT span per request, named by
19
+ * method, and the http.client.request.duration histogram, recorded in the span's context so its
20
+ * exemplar carries the trace. The span ends when the response headers arrive, or when the request
21
+ * fails. 4xx and 5xx responses and failures mark the span failed. The trace context is injected
22
+ * into a copy of the request headers; the caller's Request and init are never changed. A URL that
23
+ * cannot be parsed is passed to fetchImpl uninstrumented, so its own error surfaces.
24
+ */
25
+ export function instrumentFetch(fetchImpl = globalThis.fetch, opts = {}) {
26
+ const base = fetchImpl;
27
+ const instruments = instrumentResolver(opts.telemetry, "http.client.request.duration", "Duration of HTTP client requests.");
28
+ const traced = async (input, init) => {
29
+ const request = input instanceof Request ? input : undefined;
30
+ let url;
31
+ try {
32
+ url = new URL(request?.url ?? String(input));
33
+ }
34
+ catch {
35
+ return base(input, init);
36
+ }
37
+ const start = performance.now();
38
+ const { tracer, histogram, propagator } = instruments();
39
+ const raw = sentMethod(init?.method ?? request?.method ?? "GET");
40
+ const { method } = normalizeMethod(raw);
41
+ const server = serverAttributes(url);
42
+ const full = new URL(url);
43
+ full.username = "";
44
+ full.password = "";
45
+ const attributes = {
46
+ ...methodAttributes(raw),
47
+ ...server,
48
+ "url.full": full.href,
49
+ ...(opts.peerService === undefined ? {} : { "peer.service": opts.peerService }),
50
+ };
51
+ const parent = context.active();
52
+ const span = tracer.startSpan(methodName(method), { kind: SpanKind.CLIENT, attributes }, parent);
53
+ const spanContext = trace.setSpan(parent, span);
54
+ let propagate = true;
55
+ try {
56
+ propagate = opts.propagate?.(url) ?? true;
57
+ }
58
+ catch (err) {
59
+ propagate = false;
60
+ diag.warn(`libo11y: instrumentFetch: propagate threw, the context is not sent: ${String(err)}`);
61
+ }
62
+ const finish = (status, failure) => {
63
+ const errorType = failure !== undefined
64
+ ? errorName(failure.error)
65
+ : status !== undefined && status >= 400
66
+ ? String(status)
67
+ : undefined;
68
+ if (status !== undefined)
69
+ span.setAttribute("http.response.status_code", status);
70
+ if (errorType !== undefined) {
71
+ span.setAttribute("error.type", errorType);
72
+ span.setStatus({ code: SpanStatusCode.ERROR });
73
+ }
74
+ if (failure !== undefined)
75
+ span.recordException(asException(failure.error));
76
+ histogram.record((performance.now() - start) / 1000, {
77
+ "http.request.method": method,
78
+ ...server,
79
+ ...(status === undefined ? {} : { "http.response.status_code": status }),
80
+ ...(errorType === undefined ? {} : { "error.type": errorType }),
81
+ }, trace.setSpan(ROOT_CONTEXT, span));
82
+ span.end();
83
+ };
84
+ let res;
85
+ try {
86
+ let args = [input, init];
87
+ if (propagate) {
88
+ // fetch takes init's headers over the Request's, so the copy starts from the same source.
89
+ // Headers fetch would reject throw here instead, and fail the request the same way.
90
+ const headers = new Headers(init?.headers ?? request?.headers);
91
+ propagator.inject(spanContext, headers, HEADERS_SETTER);
92
+ args = [input, { ...init, headers }];
93
+ }
94
+ res = await context.with(spanContext, () => base(...args));
95
+ }
96
+ catch (err) {
97
+ finish(undefined, { error: err });
98
+ throw err;
99
+ }
100
+ finish(res.status);
101
+ return res;
102
+ };
103
+ const preconnect = base.preconnect;
104
+ if (typeof preconnect === "function")
105
+ Object.assign(traced, { preconnect: preconnect.bind(base) });
106
+ return traced;
107
+ }
package/dist/glob.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Go's path.Match, ported for ignorePaths: shell patterns over slash-separated paths, where '*'
3
+ * matches any run of non-slash characters, '?' one non-slash character, '[...]' a character class
4
+ * (negated with '^', ranges with '-') and '\' escapes the next character. The pattern must match
5
+ * the whole name. Like Go, a malformed pattern is reported even when the match already failed.
6
+ */
7
+ /** Thrown for a malformed pattern, as Go returns path.ErrBadPattern. */
8
+ export declare class BadPatternError extends Error {
9
+ constructor();
10
+ }
11
+ /** Reports whether name matches the shell pattern. Throws BadPatternError for a malformed one. */
12
+ export declare function pathMatch(pattern: string, name: string): boolean;
13
+ /** Whether path matches any pattern. A malformed pattern never matches, as in Go's WithIgnorePaths. */
14
+ export declare function matchesAny(patterns: readonly string[], path: string): boolean;
package/dist/glob.js ADDED
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Go's path.Match, ported for ignorePaths: shell patterns over slash-separated paths, where '*'
3
+ * matches any run of non-slash characters, '?' one non-slash character, '[...]' a character class
4
+ * (negated with '^', ranges with '-') and '\' escapes the next character. The pattern must match
5
+ * the whole name. Like Go, a malformed pattern is reported even when the match already failed.
6
+ */
7
+ /** Thrown for a malformed pattern, as Go returns path.ErrBadPattern. */
8
+ export class BadPatternError extends Error {
9
+ constructor() {
10
+ super("syntax error in pattern");
11
+ this.name = "BadPatternError";
12
+ }
13
+ }
14
+ /** Reports whether name matches the shell pattern. Throws BadPatternError for a malformed one. */
15
+ export function pathMatch(pattern, name) {
16
+ let p = Array.from(pattern);
17
+ let n = Array.from(name);
18
+ chunks: while (p.length > 0) {
19
+ const { star, chunk, rest } = scanChunk(p);
20
+ p = rest;
21
+ if (star && chunk.length === 0) {
22
+ // A trailing star matches the rest of the name unless it has a slash.
23
+ return !n.includes("/");
24
+ }
25
+ const here = matchChunk(chunk, n);
26
+ // The last chunk must exhaust the name, or the star may still find a later match.
27
+ if (here !== undefined && (here.length === 0 || p.length > 0)) {
28
+ n = here;
29
+ continue;
30
+ }
31
+ if (star) {
32
+ // Look for a match after skipping i+1 characters; a star never skips a slash.
33
+ for (let i = 0; i < n.length && n[i] !== "/"; i++) {
34
+ const t = matchChunk(chunk, n.slice(i + 1));
35
+ if (t !== undefined) {
36
+ if (p.length === 0 && t.length > 0)
37
+ continue;
38
+ n = t;
39
+ continue chunks;
40
+ }
41
+ }
42
+ }
43
+ // Before reporting no match, check that the rest of the pattern is well formed.
44
+ while (p.length > 0) {
45
+ const next = scanChunk(p);
46
+ p = next.rest;
47
+ matchChunk(next.chunk, []);
48
+ }
49
+ return false;
50
+ }
51
+ return n.length === 0;
52
+ }
53
+ // scanChunk splits off the next run of non-star pattern characters, with any stars before it.
54
+ function scanChunk(pattern) {
55
+ let i = 0;
56
+ while (i < pattern.length && pattern[i] === "*")
57
+ i++;
58
+ const star = i > 0;
59
+ const p = pattern.slice(i);
60
+ let inRange = false;
61
+ for (let j = 0; j < p.length; j++) {
62
+ switch (p[j]) {
63
+ case "\\":
64
+ // A trailing backslash is reported by matchChunk.
65
+ if (j + 1 < p.length)
66
+ j++;
67
+ break;
68
+ case "[":
69
+ inRange = true;
70
+ break;
71
+ case "]":
72
+ inRange = false;
73
+ break;
74
+ case "*":
75
+ if (!inRange)
76
+ return { star, chunk: p.slice(0, j), rest: p.slice(j) };
77
+ break;
78
+ }
79
+ }
80
+ return { star, chunk: p, rest: [] };
81
+ }
82
+ // matchChunk matches a star-free chunk against the start of s and returns what is left of s, or
83
+ // undefined when it does not match. After a mismatch it keeps reading the chunk, so a malformed
84
+ // pattern still throws.
85
+ function matchChunk(chunkIn, sIn) {
86
+ let chunk = chunkIn;
87
+ let s = sIn;
88
+ let failed = false;
89
+ while (chunk.length > 0) {
90
+ failed ||= s.length === 0;
91
+ const c = chunk[0];
92
+ if (c === "[") {
93
+ let r = -1;
94
+ if (!failed) {
95
+ r = s[0].codePointAt(0);
96
+ s = s.slice(1);
97
+ }
98
+ chunk = chunk.slice(1);
99
+ let negated = false;
100
+ if (chunk[0] === "^") {
101
+ negated = true;
102
+ chunk = chunk.slice(1);
103
+ }
104
+ let match = false;
105
+ let ranges = 0;
106
+ for (;;) {
107
+ if (chunk[0] === "]" && ranges > 0) {
108
+ chunk = chunk.slice(1);
109
+ break;
110
+ }
111
+ const lo = getEsc(chunk);
112
+ chunk = lo.rest;
113
+ let hi = lo.r;
114
+ if (chunk[0] === "-") {
115
+ const h = getEsc(chunk.slice(1));
116
+ chunk = h.rest;
117
+ hi = h.r;
118
+ }
119
+ match ||= lo.r <= r && r <= hi;
120
+ ranges++;
121
+ }
122
+ failed ||= match === negated;
123
+ continue;
124
+ }
125
+ if (c === "?") {
126
+ if (!failed) {
127
+ failed = s[0] === "/";
128
+ s = s.slice(1);
129
+ }
130
+ chunk = chunk.slice(1);
131
+ continue;
132
+ }
133
+ let literal = c;
134
+ if (c === "\\") {
135
+ chunk = chunk.slice(1);
136
+ if (chunk.length === 0)
137
+ throw new BadPatternError();
138
+ literal = chunk[0];
139
+ }
140
+ if (!failed) {
141
+ failed = literal !== s[0];
142
+ s = s.slice(1);
143
+ }
144
+ chunk = chunk.slice(1);
145
+ }
146
+ return failed ? undefined : s;
147
+ }
148
+ // getEsc reads one possibly escaped character of a character class.
149
+ function getEsc(chunkIn) {
150
+ let chunk = chunkIn;
151
+ if (chunk.length === 0 || chunk[0] === "-" || chunk[0] === "]")
152
+ throw new BadPatternError();
153
+ if (chunk[0] === "\\") {
154
+ chunk = chunk.slice(1);
155
+ if (chunk.length === 0)
156
+ throw new BadPatternError();
157
+ }
158
+ const r = chunk[0].codePointAt(0);
159
+ const rest = chunk.slice(1);
160
+ if (rest.length === 0)
161
+ throw new BadPatternError();
162
+ return { r, rest };
163
+ }
164
+ /** Whether path matches any pattern. A malformed pattern never matches, as in Go's WithIgnorePaths. */
165
+ export function matchesAny(patterns, path) {
166
+ for (const pattern of patterns) {
167
+ try {
168
+ if (pathMatch(pattern, path))
169
+ return true;
170
+ }
171
+ catch (err) {
172
+ if (!(err instanceof BadPatternError))
173
+ throw err;
174
+ }
175
+ }
176
+ return false;
177
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * What instrumentServe and instrumentFetch share: the semantic-convention method set and its
3
+ * normalization (Go o11yhttp's normalizeMethod), the duration histograms, the Headers carrier, URL
4
+ * attributes, and resolving the tracer, meter and propagator from a Telemetry or the globals.
5
+ */
6
+ import type { Telemetry } from "@libo11y/core";
7
+ import { type Attributes, type Histogram, type TextMapGetter, type TextMapPropagator, type TextMapSetter, type Tracer } from "@opentelemetry/api";
8
+ /** The instrumentation scope of the HTTP spans and metrics. */
9
+ export declare const SCOPE = "@libo11y/server";
10
+ /** The stable HTTP semconv duration buckets, in seconds, which otelhttp also uses. */
11
+ export declare const DURATION_BUCKETS: readonly number[];
12
+ /**
13
+ * Maps a request method onto the semantic-convention set as Go's o11yhttp does: a known method
14
+ * passes, a known method in another case is upper-cased, anything else is "_OTHER". original is set
15
+ * when http.request.method_original must be recorded: the method was not already in normalized
16
+ * form. An empty method is "_OTHER" with no original.
17
+ */
18
+ export declare function normalizeMethod(method: string): {
19
+ method: string;
20
+ original?: string;
21
+ };
22
+ /** The span name for a normalized method: semconv names spans of unknown methods "HTTP". */
23
+ export declare function methodName(method: string): string;
24
+ /** The method and, when normalization changed it, the original, as span attributes. */
25
+ export declare function methodAttributes(raw: string): Attributes;
26
+ /** server.address and server.port of a URL: the host without IPv6 brackets, and the port or the scheme default. */
27
+ export declare function serverAttributes(url: URL): Attributes;
28
+ /** The URL scheme without its colon. */
29
+ export declare function schemeOf(url: URL): string;
30
+ /** The error.type of a thrown value: its constructor name for an Error, else "_OTHER". */
31
+ export declare function errorConstructorName(err: unknown): string;
32
+ /** A thrown value as a span exception, for recordException. */
33
+ export declare function asException(err: unknown): Error | string;
34
+ /** Reads a Headers carrier for extraction. */
35
+ export declare const HEADERS_GETTER: TextMapGetter<Headers>;
36
+ /** Writes a Headers carrier for injection. */
37
+ export declare const HEADERS_SETTER: TextMapSetter<Headers>;
38
+ /** The tracer, the duration histogram and the propagator one request uses. */
39
+ export interface HttpInstruments {
40
+ readonly tracer: Tracer;
41
+ readonly histogram: Histogram;
42
+ readonly propagator: TextMapPropagator;
43
+ }
44
+ /**
45
+ * Returns a function that resolves the instruments for each request: from telemetry when given,
46
+ * else from the global providers and propagator. The global ones are looked up per request, so
47
+ * telemetry installed by setup after the wrapper was built, or again after a shutdown, is used;
48
+ * the instruments are rebuilt only when a provider changes.
49
+ */
50
+ export declare function instrumentResolver(telemetry: Telemetry | undefined, histogramName: string, description: string): () => HttpInstruments;
@@ -0,0 +1,105 @@
1
+ import { metrics, propagation, trace, } from "@opentelemetry/api";
2
+ import { VERSION } from "./version.js";
3
+ /** The instrumentation scope of the HTTP spans and metrics. */
4
+ export const SCOPE = "@libo11y/server";
5
+ /** The stable HTTP semconv duration buckets, in seconds, which otelhttp also uses. */
6
+ export const DURATION_BUCKETS = [
7
+ 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10,
8
+ ];
9
+ const METHOD_OTHER = "_OTHER";
10
+ // The semantic-convention method set otelhttp keeps (methodLookup in otelhttp v0.72.0).
11
+ const KNOWN_METHODS = new Set([
12
+ "CONNECT",
13
+ "DELETE",
14
+ "GET",
15
+ "HEAD",
16
+ "OPTIONS",
17
+ "PATCH",
18
+ "POST",
19
+ "PUT",
20
+ "TRACE",
21
+ ]);
22
+ /**
23
+ * Maps a request method onto the semantic-convention set as Go's o11yhttp does: a known method
24
+ * passes, a known method in another case is upper-cased, anything else is "_OTHER". original is set
25
+ * when http.request.method_original must be recorded: the method was not already in normalized
26
+ * form. An empty method is "_OTHER" with no original.
27
+ */
28
+ export function normalizeMethod(method) {
29
+ if (method === "")
30
+ return { method: METHOD_OTHER };
31
+ if (KNOWN_METHODS.has(method))
32
+ return { method };
33
+ const upper = method.toUpperCase();
34
+ if (KNOWN_METHODS.has(upper))
35
+ return { method: upper, original: method };
36
+ return { method: METHOD_OTHER, original: method };
37
+ }
38
+ /** The span name for a normalized method: semconv names spans of unknown methods "HTTP". */
39
+ export function methodName(method) {
40
+ return method === METHOD_OTHER ? "HTTP" : method;
41
+ }
42
+ /** The method and, when normalization changed it, the original, as span attributes. */
43
+ export function methodAttributes(raw) {
44
+ const { method, original } = normalizeMethod(raw);
45
+ return original === undefined
46
+ ? { "http.request.method": method }
47
+ : { "http.request.method": method, "http.request.method_original": original };
48
+ }
49
+ /** server.address and server.port of a URL: the host without IPv6 brackets, and the port or the scheme default. */
50
+ export function serverAttributes(url) {
51
+ const host = url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname;
52
+ const port = url.port !== "" ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
53
+ return { "server.address": host, "server.port": port };
54
+ }
55
+ /** The URL scheme without its colon. */
56
+ export function schemeOf(url) {
57
+ return url.protocol.slice(0, -1);
58
+ }
59
+ /** The error.type of a thrown value: its constructor name for an Error, else "_OTHER". */
60
+ export function errorConstructorName(err) {
61
+ return err instanceof Error ? err.constructor.name : METHOD_OTHER;
62
+ }
63
+ /** A thrown value as a span exception, for recordException. */
64
+ export function asException(err) {
65
+ return err instanceof Error ? err : String(err);
66
+ }
67
+ /** Reads a Headers carrier for extraction. */
68
+ export const HEADERS_GETTER = {
69
+ get: (carrier, key) => carrier.get(key) ?? undefined,
70
+ keys: (carrier) => [...carrier.keys()],
71
+ };
72
+ /** Writes a Headers carrier for injection. */
73
+ export const HEADERS_SETTER = {
74
+ set: (carrier, key, value) => carrier.set(key, value),
75
+ };
76
+ /**
77
+ * Returns a function that resolves the instruments for each request: from telemetry when given,
78
+ * else from the global providers and propagator. The global ones are looked up per request, so
79
+ * telemetry installed by setup after the wrapper was built, or again after a shutdown, is used;
80
+ * the instruments are rebuilt only when a provider changes.
81
+ */
82
+ export function instrumentResolver(telemetry, histogramName, description) {
83
+ let cached;
84
+ return () => {
85
+ const tp = telemetry?.tracerProvider ?? trace.getTracerProvider();
86
+ const mp = telemetry?.meterProvider ?? metrics.getMeterProvider();
87
+ if (cached === undefined || cached.tp !== tp || cached.mp !== mp) {
88
+ const histogram = mp.getMeter(SCOPE, VERSION).createHistogram(histogramName, {
89
+ unit: "s",
90
+ description,
91
+ advice: { explicitBucketBoundaries: [...DURATION_BUCKETS] },
92
+ });
93
+ cached = {
94
+ tp,
95
+ mp,
96
+ instruments: {
97
+ tracer: tp.getTracer(SCOPE, VERSION),
98
+ histogram,
99
+ propagator: telemetry?.propagator ?? propagation,
100
+ },
101
+ };
102
+ }
103
+ return cached.instruments;
104
+ };
105
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The libo11y server platform for Bun and Node: AsyncLocalStorage context, resource detection, OTLP
3
+ * exporters built from OTEL_* with exemplars, setup, application registry loading, signal handling,
4
+ * runtime metrics, and HTTP server and client instrumentation.
5
+ */
6
+ export { type LifecycleOptions, type Logger, O11yError, type O11yErrorCode, type SignalReport, type Telemetry, type TelemetryOptions, } from "@libo11y/core";
7
+ export { createContextManager } from "./context.ts";
8
+ export { type FetchOptions, instrumentFetch } from "./fetch.ts";
9
+ export { OtlpProtobufMetricsSerializer } from "./otlp-proto-metrics.ts";
10
+ export { serverPlatform } from "./platform.ts";
11
+ export { loadAppRegistry } from "./registry.ts";
12
+ export { instrumentServe, type ServeOptions, setRoute } from "./serve.ts";
13
+ export { createTelemetry, setup } from "./setup.ts";
14
+ export { type ShutdownOnSignalsOptions, shutdownOnSignals } from "./signals.ts";
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The libo11y server platform for Bun and Node: AsyncLocalStorage context, resource detection, OTLP
3
+ * exporters built from OTEL_* with exemplars, setup, application registry loading, signal handling,
4
+ * runtime metrics, and HTTP server and client instrumentation.
5
+ */
6
+ export { O11yError, } from "@libo11y/core";
7
+ export { createContextManager } from "./context.js";
8
+ export { instrumentFetch } from "./fetch.js";
9
+ export { OtlpProtobufMetricsSerializer } from "./otlp-proto-metrics.js";
10
+ export { serverPlatform } from "./platform.js";
11
+ export { loadAppRegistry } from "./registry.js";
12
+ export { instrumentServe, setRoute } from "./serve.js";
13
+ export { createTelemetry, setup } from "./setup.js";
14
+ export { shutdownOnSignals } from "./signals.js";
@@ -0,0 +1,21 @@
1
+ /**
2
+ * OTLP/protobuf metrics with exemplars. Upstream's ProtobufMetricsSerializer writes no exemplars, so
3
+ * this is a dependency-free encoder of opentelemetry-proto's ExportMetricsServiceRequest. It writes
4
+ * every field upstream writes, in upstream's order, so a collection without exemplars encodes to
5
+ * upstream's bytes exactly, and adds each data point's exemplars (NumberDataPoint field 5,
6
+ * HistogramDataPoint field 8, ExponentialHistogramDataPoint field 11).
7
+ *
8
+ * It walks the SDK's ResourceMetrics rather than the OTLP/JSON object core's JSON serializer builds,
9
+ * because JSON has no NaN or Infinity: a NaN gauge or an empty exponential histogram's infinite
10
+ * bounds would come back as null.
11
+ */
12
+ import { type ResourceMetricsWithExemplars } from "@libo11y/core";
13
+ import { type IExportMetricsServiceResponse, type ISerializer } from "@opentelemetry/otlp-transformer";
14
+ import { type ResourceMetrics } from "@opentelemetry/sdk-metrics";
15
+ /**
16
+ * Encodes an ExportMetricsServiceRequest holding each collection in order, with the exemplars
17
+ * ExemplarStore.attach gave its data points.
18
+ */
19
+ export declare function encodeMetricsRequest(collections: readonly ResourceMetricsWithExemplars[]): Uint8Array;
20
+ /** OTLP/protobuf metrics with exemplars, for upstream's OTLP HTTP export delegate. */
21
+ export declare const OtlpProtobufMetricsSerializer: ISerializer<ResourceMetrics | ResourceMetricsWithExemplars, IExportMetricsServiceResponse>;