@libo11y/server 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/dist/fetch.d.ts DELETED
@@ -1,35 +0,0 @@
1
- /**
2
- * instrumentFetch: client instrumentation for fetch, the counterpart of Go's o11yhttp.NewTransport.
3
- * It wraps a fetch function and returns a new one; it never patches globalThis.fetch, and it works
4
- * on Bun, whose fetch publishes none of the undici diagnostics channels Node's instrumentation reads.
5
- */
6
- import type { Telemetry } from "@libo11y/core";
7
- /** Options for {@link instrumentFetch}. */
8
- export interface FetchOptions {
9
- /** The telemetry whose providers and propagator to use. Without it, the globals setup installs. */
10
- readonly telemetry?: Telemetry;
11
- /**
12
- * Decides per destination whether the trace context and baggage are injected. Every destination
13
- * gets them by default; return false for third parties that should not see internal trace IDs.
14
- * A predicate that throws is taken as false and reported to the error handler by the class of
15
- * what it threw, never with its message, which can quote the URL.
16
- */
17
- readonly propagate?: (url: URL) => boolean;
18
- /** The peer.service attribute: the logical name of the service called. */
19
- readonly peerService?: string;
20
- }
21
- /**
22
- * Wraps fetchImpl (default: globalThis.fetch as it is now) with a CLIENT span per request, named by
23
- * method, and the http.client.request.duration histogram, recorded in the span's context so its
24
- * exemplar carries the trace. Its url.full drops the URL's credentials and redacts the values of
25
- * the presigned-URL query keys semconv names. The span ends when the response headers arrive, or when the request
26
- * fails. 4xx and 5xx responses and failures mark the span failed. The trace context is injected
27
- * into a copy of the request headers; the caller's Request and init are never changed. A URL that
28
- * cannot be parsed is passed to fetchImpl uninstrumented, so its own error surfaces.
29
- *
30
- * The telemetry never fails the request. A span that cannot start leaves the request
31
- * uninstrumented, a propagator that throws leaves it without the injected context, and a span that
32
- * cannot end changes nothing the caller sees. Each is reported to the error handler. Only fetchImpl
33
- * itself, or headers it would reject, make the returned promise reject.
34
- */
35
- export declare function instrumentFetch(fetchImpl?: typeof fetch, opts?: FetchOptions): typeof fetch;
package/dist/fetch.js DELETED
@@ -1,150 +0,0 @@
1
- import { context, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
2
- import { asException, HEADERS_SETTER, instrumentResolver, methodAttributes, methodName, normalizeMethod, reportError, serverAttributes, urlFull, } 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
- /** Injects ctx into headers. A propagator that throws is reported, and false is returned. */
18
- function inject(telemetry, propagator, ctx, headers) {
19
- try {
20
- propagator.inject(ctx, headers, HEADERS_SETTER);
21
- return true;
22
- }
23
- catch (err) {
24
- reportError(telemetry, "instrumentFetch: injecting the trace context failed, the request is sent without it", err);
25
- return false;
26
- }
27
- }
28
- /**
29
- * Wraps fetchImpl (default: globalThis.fetch as it is now) with a CLIENT span per request, named by
30
- * method, and the http.client.request.duration histogram, recorded in the span's context so its
31
- * exemplar carries the trace. Its url.full drops the URL's credentials and redacts the values of
32
- * the presigned-URL query keys semconv names. The span ends when the response headers arrive, or when the request
33
- * fails. 4xx and 5xx responses and failures mark the span failed. The trace context is injected
34
- * into a copy of the request headers; the caller's Request and init are never changed. A URL that
35
- * cannot be parsed is passed to fetchImpl uninstrumented, so its own error surfaces.
36
- *
37
- * The telemetry never fails the request. A span that cannot start leaves the request
38
- * uninstrumented, a propagator that throws leaves it without the injected context, and a span that
39
- * cannot end changes nothing the caller sees. Each is reported to the error handler. Only fetchImpl
40
- * itself, or headers it would reject, make the returned promise reject.
41
- */
42
- export function instrumentFetch(fetchImpl = globalThis.fetch, opts = {}) {
43
- const base = fetchImpl;
44
- const instruments = instrumentResolver(opts.telemetry, "http.client.request.duration", "Duration of HTTP client requests.");
45
- // begin resolves the instruments and starts the client span. Whatever it throws comes from the
46
- // telemetry, never from the request.
47
- const begin = (url, rawMethod) => {
48
- const { tracer, histogram, propagator } = instruments();
49
- const raw = sentMethod(rawMethod);
50
- const { method } = normalizeMethod(raw);
51
- const server = serverAttributes(url);
52
- const attributes = {
53
- ...methodAttributes(raw),
54
- ...server,
55
- "url.full": urlFull(url),
56
- ...(opts.peerService === undefined ? {} : { "peer.service": opts.peerService }),
57
- };
58
- const parent = context.active();
59
- const span = tracer.startSpan(methodName(method), { kind: SpanKind.CLIENT, attributes }, parent);
60
- return { span, spanContext: trace.setSpan(parent, span), histogram, propagator, method, server };
61
- };
62
- const traced = async (input, init) => {
63
- const request = input instanceof Request ? input : undefined;
64
- let url;
65
- try {
66
- url = new URL(request?.url ?? String(input));
67
- }
68
- catch {
69
- return base(input, init);
70
- }
71
- const start = performance.now();
72
- let begun;
73
- try {
74
- begun = begin(url, init?.method ?? request?.method ?? "GET");
75
- }
76
- catch (err) {
77
- reportError(opts.telemetry, "instrumentFetch: starting the request's telemetry failed, the request is not instrumented", err);
78
- return base(input, init);
79
- }
80
- const { span, spanContext, histogram, propagator, method, server } = begun;
81
- let propagate = true;
82
- try {
83
- propagate = opts.propagate?.(url) ?? true;
84
- }
85
- catch (err) {
86
- propagate = false;
87
- // By class only: the predicate is handed the URL, and its error can quote it.
88
- reportError(opts.telemetry, "instrumentFetch: the propagate option failed, the context is not sent", err);
89
- }
90
- const end = (response, failure) => {
91
- // The status is read here, inside finish's guard: a fetchImpl may resolve with something
92
- // that is not a Response, and that is the caller's to deal with, not a reason to throw.
93
- const read = response?.status;
94
- const status = typeof read === "number" ? read : undefined;
95
- const errorType = failure !== undefined
96
- ? errorName(failure.error)
97
- : status !== undefined && status >= 400
98
- ? String(status)
99
- : undefined;
100
- if (status !== undefined)
101
- span.setAttribute("http.response.status_code", status);
102
- if (errorType !== undefined) {
103
- span.setAttribute("error.type", errorType);
104
- span.setStatus({ code: SpanStatusCode.ERROR });
105
- }
106
- if (failure !== undefined)
107
- span.recordException(asException(failure.error));
108
- histogram.record((performance.now() - start) / 1000, {
109
- "http.request.method": method,
110
- ...server,
111
- ...(status === undefined ? {} : { "http.response.status_code": status }),
112
- ...(errorType === undefined ? {} : { "error.type": errorType }),
113
- }, trace.setSpan(ROOT_CONTEXT, span));
114
- span.end();
115
- };
116
- // finish guards end, so a throw from a span processor or an instrument never replaces the
117
- // response or fetch's own error.
118
- const finish = (response, failure) => {
119
- try {
120
- end(response, failure);
121
- }
122
- catch (err) {
123
- reportError(opts.telemetry, "instrumentFetch: ending the request's telemetry failed", err);
124
- }
125
- };
126
- let res;
127
- try {
128
- let args = [input, init];
129
- if (propagate) {
130
- // fetch takes init's headers over the Request's, so the copy starts from the same source.
131
- // Headers fetch would reject throw here instead, and fail the request the same way.
132
- const headers = new Headers(init?.headers ?? request?.headers);
133
- // A copy the propagator only half filled is not sent: the request keeps its own headers.
134
- if (inject(opts.telemetry, propagator, spanContext, headers))
135
- args = [input, { ...init, headers }];
136
- }
137
- res = await context.with(spanContext, () => base(...args));
138
- }
139
- catch (err) {
140
- finish(undefined, { error: err });
141
- throw err;
142
- }
143
- finish(res);
144
- return res;
145
- };
146
- const preconnect = base.preconnect;
147
- if (typeof preconnect === "function")
148
- Object.assign(traced, { preconnect: preconnect.bind(base) });
149
- return traced;
150
- }
package/dist/glob.d.ts DELETED
@@ -1,14 +0,0 @@
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 DELETED
@@ -1,177 +0,0 @@
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
- }
@@ -1,78 +0,0 @@
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, resolving the tracer, meter and propagator from a Telemetry or the globals, and
5
- * reporting a failure of the instrumentation itself.
6
- */
7
- import type { Telemetry } from "@libo11y/core";
8
- import { type Attributes, type Histogram, type TextMapGetter, type TextMapPropagator, type TextMapSetter, type Tracer } from "@opentelemetry/api";
9
- /** The instrumentation scope of the HTTP spans and metrics. */
10
- export declare const SCOPE = "@libo11y/server";
11
- /** The stable HTTP semconv duration buckets, in seconds, which otelhttp also uses. */
12
- export declare const DURATION_BUCKETS: readonly number[];
13
- /**
14
- * Maps a request method onto the semantic-convention set as Go's o11yhttp does: a known method
15
- * passes, a known method in another case is upper-cased, anything else is "_OTHER". original is set
16
- * when http.request.method_original must be recorded: the method was not already in normalized
17
- * form. An empty method is "_OTHER" with no original.
18
- */
19
- export declare function normalizeMethod(method: string): {
20
- method: string;
21
- original?: string;
22
- };
23
- /** The span name for a normalized method: semconv names spans of unknown methods "HTTP". */
24
- export declare function methodName(method: string): string;
25
- /** The method and, when normalization changed it, the original, as span attributes. */
26
- export declare function methodAttributes(raw: string): Attributes;
27
- /** server.address and server.port of a URL: the host without IPv6 brackets, and the port or the scheme default. */
28
- export declare function serverAttributes(url: URL): Attributes;
29
- /**
30
- * The url.full of a request URL: credentials removed, and the values of the presigned-URL query
31
- * keys semconv names (AWSAccessKeyId, Signature, sig, X-Goog-Signature) replaced by REDACTED.
32
- */
33
- export declare function urlFull(url: URL): string;
34
- /** The URL scheme without its colon. */
35
- export declare function schemeOf(url: URL): string;
36
- /** The error.type of a thrown value: its constructor name for an Error, else "_OTHER". */
37
- export declare function errorConstructorName(err: unknown): string;
38
- /** The message of a thrown value. It never throws, whatever was thrown. */
39
- export declare function errorMessage(err: unknown): string;
40
- /**
41
- * The class of a thrown value, for a report: its constructor's name when that reads as a class
42
- * name, "Error" for any other error, and the value's type for anything that is not an object. It
43
- * never throws and never returns the value's own text.
44
- */
45
- export declare function errorClass(thrown: unknown): string;
46
- /**
47
- * Reports a failure of the instrumentation itself, which must never reach the request it wraps:
48
- * a propagator that throws, a span that cannot start or end. It never throws.
49
- *
50
- * The report is an Error whose message is "o11y: <what>: <class of what was thrown>", with what
51
- * was thrown on its cause. The message of what was thrown is left out: a propagator is handed the
52
- * request's headers, and its error can quote them.
53
- *
54
- * With a telemetry the report goes through that handle's own handler, so it is written for a
55
- * createTelemetry handle too, which installs nothing globally. Without one, or with something that
56
- * is not a core handle, it goes to the OpenTelemetry global error handler, which setup makes
57
- * libo11y's rate-limited one.
58
- */
59
- export declare function reportError(telemetry: Telemetry | undefined, what: string, err: unknown): void;
60
- /** A thrown value as a span exception, for recordException. */
61
- export declare function asException(err: unknown): Error | string;
62
- /** Reads a Headers carrier for extraction. */
63
- export declare const HEADERS_GETTER: TextMapGetter<Headers>;
64
- /** Writes a Headers carrier for injection. */
65
- export declare const HEADERS_SETTER: TextMapSetter<Headers>;
66
- /** The tracer, the duration histogram and the propagator one request uses. */
67
- export interface HttpInstruments {
68
- readonly tracer: Tracer;
69
- readonly histogram: Histogram;
70
- readonly propagator: TextMapPropagator;
71
- }
72
- /**
73
- * Returns a function that resolves the instruments for each request: from telemetry when given,
74
- * else from the global providers and propagator. The global ones are looked up per request, so
75
- * telemetry installed by setup after the wrapper was built, or again after a shutdown, is used;
76
- * the instruments are rebuilt only when a provider changes.
77
- */
78
- export declare function instrumentResolver(telemetry: Telemetry | undefined, histogramName: string, description: string): () => HttpInstruments;
@@ -1,215 +0,0 @@
1
- import { metrics, propagation, trace, } from "@opentelemetry/api";
2
- import { globalErrorHandler } from "@opentelemetry/core";
3
- import { VERSION } from "./version.js";
4
- /** The instrumentation scope of the HTTP spans and metrics. */
5
- export const SCOPE = "@libo11y/server";
6
- /** The stable HTTP semconv duration buckets, in seconds, which otelhttp also uses. */
7
- export const DURATION_BUCKETS = [
8
- 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,
9
- ];
10
- const METHOD_OTHER = "_OTHER";
11
- // The semantic-convention method set otelhttp keeps (methodLookup in otelhttp v0.72.0).
12
- const KNOWN_METHODS = new Set([
13
- "CONNECT",
14
- "DELETE",
15
- "GET",
16
- "HEAD",
17
- "OPTIONS",
18
- "PATCH",
19
- "POST",
20
- "PUT",
21
- "TRACE",
22
- ]);
23
- /**
24
- * Maps a request method onto the semantic-convention set as Go's o11yhttp does: a known method
25
- * passes, a known method in another case is upper-cased, anything else is "_OTHER". original is set
26
- * when http.request.method_original must be recorded: the method was not already in normalized
27
- * form. An empty method is "_OTHER" with no original.
28
- */
29
- export function normalizeMethod(method) {
30
- if (method === "")
31
- return { method: METHOD_OTHER };
32
- if (KNOWN_METHODS.has(method))
33
- return { method };
34
- const upper = method.toUpperCase();
35
- if (KNOWN_METHODS.has(upper))
36
- return { method: upper, original: method };
37
- return { method: METHOD_OTHER, original: method };
38
- }
39
- /** The span name for a normalized method: semconv names spans of unknown methods "HTTP". */
40
- export function methodName(method) {
41
- return method === METHOD_OTHER ? "HTTP" : method;
42
- }
43
- /** The method and, when normalization changed it, the original, as span attributes. */
44
- export function methodAttributes(raw) {
45
- const { method, original } = normalizeMethod(raw);
46
- return original === undefined
47
- ? { "http.request.method": method }
48
- : { "http.request.method": method, "http.request.method_original": original };
49
- }
50
- /** server.address and server.port of a URL: the host without IPv6 brackets, and the port or the scheme default. */
51
- export function serverAttributes(url) {
52
- const host = url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname;
53
- const port = url.port !== "" ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
54
- return { "server.address": host, "server.port": port };
55
- }
56
- // The query keys whose values semconv says url.full SHOULD redact by default (presigned URLs). The
57
- // same set and matching as redactQuery in @libo11y/web's http-common.ts, which mirrors this file.
58
- const REDACTED_QUERY_KEYS = new Set([
59
- "AWSAccessKeyId",
60
- "Signature",
61
- "sig",
62
- "X-Goog-Signature",
63
- ]);
64
- /** search with the value of each REDACTED_QUERY_KEYS parameter replaced by REDACTED, the rest as is. */
65
- function redactQuery(search) {
66
- if (search.length <= 1)
67
- return search;
68
- const parts = search.slice(1).split("&");
69
- let changed = false;
70
- for (const [i, part] of parts.entries()) {
71
- const eq = part.indexOf("=");
72
- if (eq < 0)
73
- continue;
74
- let key;
75
- try {
76
- key = decodeURIComponent(part.slice(0, eq).replaceAll("+", " "));
77
- }
78
- catch {
79
- // A key that is not valid percent-encoding is none of the redacted keys.
80
- continue;
81
- }
82
- if (REDACTED_QUERY_KEYS.has(key)) {
83
- parts[i] = `${part.slice(0, eq)}=REDACTED`;
84
- changed = true;
85
- }
86
- }
87
- return changed ? `?${parts.join("&")}` : search;
88
- }
89
- /**
90
- * The url.full of a request URL: credentials removed, and the values of the presigned-URL query
91
- * keys semconv names (AWSAccessKeyId, Signature, sig, X-Goog-Signature) replaced by REDACTED.
92
- */
93
- export function urlFull(url) {
94
- const full = new URL(url);
95
- full.username = "";
96
- full.password = "";
97
- const search = redactQuery(full.search);
98
- if (search !== full.search)
99
- full.search = search;
100
- return full.href;
101
- }
102
- /** The URL scheme without its colon. */
103
- export function schemeOf(url) {
104
- return url.protocol.slice(0, -1);
105
- }
106
- /** The error.type of a thrown value: its constructor name for an Error, else "_OTHER". */
107
- export function errorConstructorName(err) {
108
- return err instanceof Error ? err.constructor.name : METHOD_OTHER;
109
- }
110
- /** The message of a thrown value. It never throws, whatever was thrown. */
111
- export function errorMessage(err) {
112
- try {
113
- return err instanceof Error ? err.message : String(err);
114
- }
115
- catch {
116
- return "unknown error";
117
- }
118
- }
119
- const CLASS_NAME = /^[A-Za-z_$][\w$]{0,63}$/;
120
- /**
121
- * The class of a thrown value, for a report: its constructor's name when that reads as a class
122
- * name, "Error" for any other error, and the value's type for anything that is not an object. It
123
- * never throws and never returns the value's own text.
124
- */
125
- export function errorClass(thrown) {
126
- try {
127
- if (thrown === null)
128
- return "null";
129
- if (typeof thrown !== "object")
130
- return typeof thrown;
131
- const name = thrown.constructor?.name;
132
- if (typeof name === "string" && CLASS_NAME.test(name))
133
- return name;
134
- return thrown instanceof Error ? "Error" : "object";
135
- }
136
- catch {
137
- return "unknown";
138
- }
139
- }
140
- /**
141
- * The key under which a telemetry handle from @libo11y/core carries its reporter: a function that
142
- * writes one error through the handle's own rate-limited handler. A registered symbol, so it is
143
- * found without importing core's internals, and on a handle made by another copy of core.
144
- */
145
- const REPORT_KEY = Symbol.for("libo11y.report");
146
- /**
147
- * Reports a failure of the instrumentation itself, which must never reach the request it wraps:
148
- * a propagator that throws, a span that cannot start or end. It never throws.
149
- *
150
- * The report is an Error whose message is "o11y: <what>: <class of what was thrown>", with what
151
- * was thrown on its cause. The message of what was thrown is left out: a propagator is handed the
152
- * request's headers, and its error can quote them.
153
- *
154
- * With a telemetry the report goes through that handle's own handler, so it is written for a
155
- * createTelemetry handle too, which installs nothing globally. Without one, or with something that
156
- * is not a core handle, it goes to the OpenTelemetry global error handler, which setup makes
157
- * libo11y's rate-limited one.
158
- */
159
- export function reportError(telemetry, what, err) {
160
- const report = new Error(`o11y: ${what}: ${errorClass(err)}`, { cause: err });
161
- try {
162
- const own = telemetry?.[REPORT_KEY];
163
- if (typeof own === "function") {
164
- own.call(telemetry, report);
165
- return;
166
- }
167
- }
168
- catch {
169
- // A handle whose reporter fails leaves the global handler.
170
- }
171
- globalErrorHandler(report);
172
- }
173
- /** A thrown value as a span exception, for recordException. */
174
- export function asException(err) {
175
- return err instanceof Error ? err : String(err);
176
- }
177
- /** Reads a Headers carrier for extraction. */
178
- export const HEADERS_GETTER = {
179
- get: (carrier, key) => carrier.get(key) ?? undefined,
180
- keys: (carrier) => [...carrier.keys()],
181
- };
182
- /** Writes a Headers carrier for injection. */
183
- export const HEADERS_SETTER = {
184
- set: (carrier, key, value) => carrier.set(key, value),
185
- };
186
- /**
187
- * Returns a function that resolves the instruments for each request: from telemetry when given,
188
- * else from the global providers and propagator. The global ones are looked up per request, so
189
- * telemetry installed by setup after the wrapper was built, or again after a shutdown, is used;
190
- * the instruments are rebuilt only when a provider changes.
191
- */
192
- export function instrumentResolver(telemetry, histogramName, description) {
193
- let cached;
194
- return () => {
195
- const tp = telemetry?.tracerProvider ?? trace.getTracerProvider();
196
- const mp = telemetry?.meterProvider ?? metrics.getMeterProvider();
197
- if (cached === undefined || cached.tp !== tp || cached.mp !== mp) {
198
- const histogram = mp.getMeter(SCOPE, VERSION).createHistogram(histogramName, {
199
- unit: "s",
200
- description,
201
- advice: { explicitBucketBoundaries: [...DURATION_BUCKETS] },
202
- });
203
- cached = {
204
- tp,
205
- mp,
206
- instruments: {
207
- tracer: tp.getTracer(SCOPE, VERSION),
208
- histogram,
209
- propagator: telemetry?.propagator ?? propagation,
210
- },
211
- };
212
- }
213
- return cached.instruments;
214
- };
215
- }