@libo11y/server 0.1.1 → 0.2.1

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.
@@ -1,4 +1,5 @@
1
1
  import { metrics, propagation, trace, } from "@opentelemetry/api";
2
+ import { globalErrorHandler } from "@opentelemetry/core";
2
3
  import { VERSION } from "./version.js";
3
4
  /** The instrumentation scope of the HTTP spans and metrics. */
4
5
  export const SCOPE = "@libo11y/server";
@@ -60,6 +61,69 @@ export function schemeOf(url) {
60
61
  export function errorConstructorName(err) {
61
62
  return err instanceof Error ? err.constructor.name : METHOD_OTHER;
62
63
  }
64
+ /** The message of a thrown value. It never throws, whatever was thrown. */
65
+ export function errorMessage(err) {
66
+ try {
67
+ return err instanceof Error ? err.message : String(err);
68
+ }
69
+ catch {
70
+ return "unknown error";
71
+ }
72
+ }
73
+ const CLASS_NAME = /^[A-Za-z_$][\w$]{0,63}$/;
74
+ /**
75
+ * The class of a thrown value, for a report: its constructor's name when that reads as a class
76
+ * name, "Error" for any other error, and the value's type for anything that is not an object. It
77
+ * never throws and never returns the value's own text.
78
+ */
79
+ export function errorClass(thrown) {
80
+ try {
81
+ if (thrown === null)
82
+ return "null";
83
+ if (typeof thrown !== "object")
84
+ return typeof thrown;
85
+ const name = thrown.constructor?.name;
86
+ if (typeof name === "string" && CLASS_NAME.test(name))
87
+ return name;
88
+ return thrown instanceof Error ? "Error" : "object";
89
+ }
90
+ catch {
91
+ return "unknown";
92
+ }
93
+ }
94
+ /**
95
+ * The key under which a telemetry handle from @libo11y/core carries its reporter: a function that
96
+ * writes one error through the handle's own rate-limited handler. A registered symbol, so it is
97
+ * found without importing core's internals, and on a handle made by another copy of core.
98
+ */
99
+ const REPORT_KEY = Symbol.for("libo11y.report");
100
+ /**
101
+ * Reports a failure of the instrumentation itself, which must never reach the request it wraps:
102
+ * a propagator that throws, a span that cannot start or end. It never throws.
103
+ *
104
+ * The report is an Error whose message is "o11y: <what>: <class of what was thrown>", with what
105
+ * was thrown on its cause. The message of what was thrown is left out: a propagator is handed the
106
+ * request's headers, and its error can quote them.
107
+ *
108
+ * With a telemetry the report goes through that handle's own handler, so it is written for a
109
+ * createTelemetry handle too, which installs nothing globally. Without one, or with something that
110
+ * is not a core handle, it goes to the OpenTelemetry global error handler, which setup makes
111
+ * libo11y's rate-limited one.
112
+ */
113
+ export function reportError(telemetry, what, err) {
114
+ const report = new Error(`o11y: ${what}: ${errorClass(err)}`, { cause: err });
115
+ try {
116
+ const own = telemetry?.[REPORT_KEY];
117
+ if (typeof own === "function") {
118
+ own.call(telemetry, report);
119
+ return;
120
+ }
121
+ }
122
+ catch {
123
+ // A handle whose reporter fails leaves the global handler.
124
+ }
125
+ globalErrorHandler(report);
126
+ }
63
127
  /** A thrown value as a span exception, for recordException. */
64
128
  export function asException(err) {
65
129
  return err instanceof Error ? err : String(err);
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The OTLP/HTTP transport of the server exporters: one POST per export, retried while the collector
3
+ * asks for it. It reimplements two things upstream does not export, the node transport and the
4
+ * retrying transport of @opentelemetry/otlp-exporter-base 0.301.1, and follows them in everything a
5
+ * collector or a diag logger sees: the request and its framing, gzip, the User-Agent, which
6
+ * statuses and network errors are retried, the backoff, Retry-After, the time a retry is given, the
7
+ * 4 MiB cap on a response body, and the diag messages about retries.
8
+ *
9
+ * It exists because upstream's cannot be stopped, and a transport that cannot be stopped keeps an
10
+ * exiting process alive. It differs from upstream in five ways, and only these:
11
+ *
12
+ * 1. The timeout covers the whole attempt: connecting, sending and reading the response. Upstream
13
+ * arms ClientRequest.setTimeout, an idle timeout that Node applies only once the socket has
14
+ * connected. So a connection that never completes had no timeout at all and held the process for
15
+ * as long as the operating system kept trying. The other side of this change is that a response
16
+ * which trickles in for longer than the timeout now fails, where upstream let it run as long as
17
+ * bytes kept coming.
18
+ * 2. abort() ends what is in flight: each request is destroyed, each wait between two retries is
19
+ * cancelled, and every later send fails at once. Upstream's shutdown() does nothing.
20
+ * 3. shutdown() also destroys the agent, which closes its idle keep-alive sockets.
21
+ * 4. Sends that start before the agent is built share one agent. Upstream builds one for each of
22
+ * them and keeps the last.
23
+ * 5. A wait before a retry that is longer than a timer can hold is clamped to the longest a timer
24
+ * holds, about 24.8 days. Upstream's fires after a millisecond.
25
+ *
26
+ * A gzip body is also compressed in one call where upstream streams it, which can change how the
27
+ * same bytes are split into chunks and nothing else.
28
+ *
29
+ * Unreferencing the socket would not do in place of destroying it: under Node a connection attempt
30
+ * in progress keeps the event loop alive even on an unreferenced socket.
31
+ *
32
+ * One thing abort() cannot end under Node: a name lookup in progress. Node cannot cancel
33
+ * getaddrinfo, so when the collector's host name does not resolve and the resolver does not answer,
34
+ * the export fails on time but the process stays alive until the resolver gives up.
35
+ *
36
+ * otlp-transport.test.ts pins each of these behaviours, and fails when the upstream files this one
37
+ * follows change, so an upgrade is checked against them again.
38
+ */
39
+ import type { Agent } from "node:http";
40
+ import { type IExporterTransport } from "@opentelemetry/otlp-exporter-base";
41
+ /** The version of @opentelemetry/otlp-exporter-base this transport follows, for the User-Agent. */
42
+ export declare const OTLP_EXPORTER_VERSION = "0.301.1";
43
+ /** The largest response body read. A larger one fails the export, whatever its status. */
44
+ export declare const MAX_RESPONSE_BODY_SIZE: number;
45
+ /** The longest delay a timer takes. Node and Bun treat anything larger as 1 ms. */
46
+ export declare const MAX_TIMER_MILLIS: number;
47
+ /**
48
+ * What the transport takes from an exporter's configuration, as upstream's convertLegacyHttpOptions
49
+ * gives it. The configuration's other two members, timeoutMillis and concurrencyLimit, go to
50
+ * upstream's export delegate. A test fails when upstream's configuration gains a member, so a new
51
+ * one is never ignored without a decision.
52
+ */
53
+ export interface HttpTransportParameters {
54
+ readonly url: string;
55
+ readonly headers: () => Promise<Record<string, string>>;
56
+ readonly compression: "gzip" | "none";
57
+ /** A prefix for the User-Agent header. */
58
+ readonly userAgent?: string | undefined;
59
+ /** Builds the agent for a protocol, "http:" or "https:": upstream's, which carries the certificates. */
60
+ readonly agentFactory: (protocol: string) => Agent | Promise<Agent>;
61
+ }
62
+ /**
63
+ * The clock, the timers and the random numbers the transport uses. A test replaces them to decide
64
+ * when time passes and how much jitter a retry gets.
65
+ */
66
+ export interface TransportTimers {
67
+ now(): number;
68
+ setTimeout(fn: () => void, ms: number): unknown;
69
+ clearTimeout(handle: unknown): void;
70
+ /** A number from 0 up to, not including, 1, drawn once for the jitter of each wait. */
71
+ random(): number;
72
+ }
73
+ /** A transport whose work in flight can be ended. */
74
+ export interface AbortableTransport extends IExporterTransport {
75
+ /**
76
+ * Ends every send in flight with a failure, and makes every later send fail at once. Nothing the
77
+ * transport started keeps the process alive afterwards, except a name lookup Node cannot cancel.
78
+ * Idempotent.
79
+ */
80
+ abort(): void;
81
+ }
82
+ /**
83
+ * The Retry-After header as upstream reads it: a number of seconds, or an HTTP date measured from
84
+ * now. Zero or fewer seconds is -1, a date in the past or one that does not parse is 0, and both
85
+ * mean at once.
86
+ */
87
+ export declare function retryAfterMillis(header: string | undefined, now: number): number | undefined;
88
+ /**
89
+ * Creates the transport for one exporter. Nothing is connected or loaded until the first send.
90
+ * timers is for tests, which decide when time passes.
91
+ */
92
+ export declare function createHttpTransport(params: HttpTransportParameters, timers?: TransportTimers): AbortableTransport;
@@ -0,0 +1,289 @@
1
+ import { gzip } from "node:zlib";
2
+ import { diag } from "@opentelemetry/api";
3
+ import { OTLPExporterError, } from "@opentelemetry/otlp-exporter-base";
4
+ /** The version of @opentelemetry/otlp-exporter-base this transport follows, for the User-Agent. */
5
+ export const OTLP_EXPORTER_VERSION = "0.301.1";
6
+ const DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${OTLP_EXPORTER_VERSION}`;
7
+ /** The largest response body read. A larger one fails the export, whatever its status. */
8
+ export const MAX_RESPONSE_BODY_SIZE = 4 * 1024 * 1024;
9
+ /** The longest delay a timer takes. Node and Bun treat anything larger as 1 ms. */
10
+ export const MAX_TIMER_MILLIS = 2 ** 31 - 1;
11
+ const MAX_ATTEMPTS = 5;
12
+ const INITIAL_BACKOFF = 1000;
13
+ const MAX_BACKOFF = 5000;
14
+ const BACKOFF_MULTIPLIER = 1.5;
15
+ const JITTER = 0.2;
16
+ const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
17
+ const RETRYABLE_NETWORK_ERRORS = new Set([
18
+ "ECONNRESET",
19
+ "ECONNREFUSED",
20
+ "EPIPE",
21
+ "ETIMEDOUT",
22
+ "EAI_AGAIN",
23
+ "ENOTFOUND",
24
+ "ENETUNREACH",
25
+ "EHOSTUNREACH",
26
+ ]);
27
+ const REAL_TIMERS = {
28
+ random: () => Math.random(),
29
+ now: () => Date.now(),
30
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
31
+ clearTimeout: (handle) => clearTimeout(handle),
32
+ };
33
+ function aborted() {
34
+ return { status: "failure", error: new Error("the export was aborted at shutdown") };
35
+ }
36
+ function asError(err) {
37
+ return err instanceof Error ? err : new Error(String(err));
38
+ }
39
+ function retryableNetworkError(error) {
40
+ const code = error.code;
41
+ return typeof code === "string" && RETRYABLE_NETWORK_ERRORS.has(code);
42
+ }
43
+ /**
44
+ * The Retry-After header as upstream reads it: a number of seconds, or an HTTP date measured from
45
+ * now. Zero or fewer seconds is -1, a date in the past or one that does not parse is 0, and both
46
+ * mean at once.
47
+ */
48
+ export function retryAfterMillis(header, now) {
49
+ if (header === undefined)
50
+ return undefined;
51
+ const seconds = Number.parseInt(header, 10);
52
+ if (Number.isInteger(seconds))
53
+ return seconds > 0 ? seconds * 1000 : -1;
54
+ const delay = new Date(header).getTime() - now;
55
+ if (delay >= 0)
56
+ return delay;
57
+ return 0;
58
+ }
59
+ // jitter is upstream's: a fifth either way, from a random number in [0, 1).
60
+ function jitter(random) {
61
+ return random * (2 * JITTER) - JITTER;
62
+ }
63
+ class HttpTransport {
64
+ params;
65
+ timers;
66
+ url;
67
+ io;
68
+ stopped = false;
69
+ /** Ends each attempt in flight with the response given. */
70
+ inFlight = new Set();
71
+ /** Ends each wait between two retries: true when the time passed, false when it was cut short. */
72
+ waiting = new Set();
73
+ constructor(params, timers) {
74
+ this.params = params;
75
+ this.timers = timers;
76
+ this.url = new URL(params.url);
77
+ }
78
+ // send is upstream's RetryingTransport.send, statement for statement, with the wait between two
79
+ // attempts made cancellable. A retry is given the time that was left when it was scheduled, as
80
+ // upstream gives it, so it can end later than the timeout by the length of the wait.
81
+ async send(data, timeoutMillis) {
82
+ let attempts = MAX_ATTEMPTS;
83
+ let nextBackoff = INITIAL_BACKOFF;
84
+ const deadline = this.timers.now() + timeoutMillis;
85
+ let result = await this.attempt(data, timeoutMillis);
86
+ while (result.status === "retryable" && attempts > 0) {
87
+ attempts--;
88
+ const backoff = Math.max(Math.min(nextBackoff * (1 + jitter(this.timers.random())), MAX_BACKOFF), 0);
89
+ nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;
90
+ const retryInMillis = result.retryInMillis ?? backoff;
91
+ const remainingTimeoutMillis = deadline - this.timers.now();
92
+ if (retryInMillis > remainingTimeoutMillis) {
93
+ diag.info(`Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(remainingTimeoutMillis)}ms, not retrying further.`);
94
+ return result;
95
+ }
96
+ diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`);
97
+ if (!(await this.wait(retryInMillis)))
98
+ return aborted();
99
+ result = await this.attempt(data, remainingTimeoutMillis);
100
+ }
101
+ if (result.status === "success") {
102
+ diag.verbose(`Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`);
103
+ }
104
+ else if (result.status === "retryable") {
105
+ diag.info(`Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`);
106
+ }
107
+ else {
108
+ diag.info(`Export failed with non-retryable error: ${result.error}`);
109
+ }
110
+ return result;
111
+ }
112
+ abort() {
113
+ this.stopped = true;
114
+ for (const end of [...this.inFlight])
115
+ end(aborted());
116
+ for (const wake of [...this.waiting])
117
+ wake(false);
118
+ }
119
+ shutdown() {
120
+ this.abort();
121
+ // The idle keep-alive sockets go too. The agent was never built if nothing was ever sent.
122
+ void this.io?.then(({ agent }) => agent.destroy(), () => { });
123
+ }
124
+ // arm sets a timer, clamped to what a timer can wait: a longer delay would fire after 1 ms.
125
+ arm(fn, ms) {
126
+ return this.timers.setTimeout(fn, Math.min(Math.max(ms, 0), MAX_TIMER_MILLIS));
127
+ }
128
+ // load builds the agent and loads the request function once. Sends that start together share
129
+ // one agent. A failure is not kept: the next send tries again, as upstream's does. The http
130
+ // modules are imported only here, as upstream does, so an HTTP instrumentation loaded later can
131
+ // still patch them.
132
+ load() {
133
+ if (this.io === undefined) {
134
+ const loading = (async () => {
135
+ const protocol = this.url.protocol;
136
+ const [agent, mod] = await Promise.all([
137
+ this.params.agentFactory(protocol),
138
+ protocol === "http:" ? import("node:http") : import("node:https"),
139
+ ]);
140
+ return { agent, request: mod.request };
141
+ })();
142
+ this.io = loading;
143
+ loading.catch(() => {
144
+ if (this.io === loading)
145
+ this.io = undefined;
146
+ });
147
+ }
148
+ return this.io;
149
+ }
150
+ // wait resolves true after ms, or false as soon as the transport is aborted.
151
+ wait(ms) {
152
+ if (this.stopped)
153
+ return Promise.resolve(false);
154
+ return new Promise((resolve) => {
155
+ const wake = (passed) => {
156
+ this.timers.clearTimeout(timer);
157
+ this.waiting.delete(wake);
158
+ resolve(passed);
159
+ };
160
+ const timer = this.arm(() => wake(true), ms);
161
+ this.waiting.add(wake);
162
+ });
163
+ }
164
+ // attempt makes one request and resolves with what became of it. It rejects only when the agent
165
+ // or the headers cannot be built, as upstream's does, and upstream's export delegate reports
166
+ // that rejection as a failed export.
167
+ async attempt(data, timeoutMillis) {
168
+ if (this.stopped)
169
+ return aborted();
170
+ const io = await this.load();
171
+ const headers = { ...(await this.params.headers()) };
172
+ if (this.stopped)
173
+ return aborted();
174
+ const userAgent = this.params.userAgent;
175
+ headers["User-Agent"] = userAgent ? `${userAgent} ${DEFAULT_USER_AGENT}` : DEFAULT_USER_AGENT;
176
+ const gzipped = this.params.compression === "gzip";
177
+ if (gzipped)
178
+ headers["Content-Encoding"] = "gzip";
179
+ return new Promise((resolve) => {
180
+ let settled = false;
181
+ let timer;
182
+ let req;
183
+ const settle = (response) => {
184
+ if (settled)
185
+ return;
186
+ settled = true;
187
+ this.timers.clearTimeout(timer);
188
+ this.inFlight.delete(end);
189
+ resolve(response);
190
+ };
191
+ // end settles the attempt and then destroys the request, whose own error is then ignored.
192
+ const end = (response) => {
193
+ settle(response);
194
+ req?.destroy();
195
+ };
196
+ this.inFlight.add(end);
197
+ // The timeout runs from here, so it also bounds a connection that never completes.
198
+ timer = this.arm(() => end({ status: "retryable", error: new Error("Request timed out") }), timeoutMillis);
199
+ try {
200
+ req = io.request(this.url, { method: "POST", headers, agent: io.agent }, (res) => {
201
+ const chunks = [];
202
+ let size = 0;
203
+ res.on("data", (chunk) => {
204
+ size += chunk.length;
205
+ if (size > MAX_RESPONSE_BODY_SIZE) {
206
+ settle({
207
+ status: "failure",
208
+ error: new Error(`OTLP export response body exceeded size limit of ${MAX_RESPONSE_BODY_SIZE} bytes`),
209
+ });
210
+ res.destroy();
211
+ return;
212
+ }
213
+ chunks.push(chunk);
214
+ });
215
+ const retryAfter = () => {
216
+ const retryInMillis = retryAfterMillis(res.headers["retry-after"], this.timers.now());
217
+ return retryInMillis === undefined ? {} : { retryInMillis };
218
+ };
219
+ res.on("end", () => {
220
+ const status = res.statusCode;
221
+ if (status && status <= 299) {
222
+ settle({ status: "success", data: Buffer.concat(chunks) });
223
+ }
224
+ else if (status && RETRYABLE_STATUSES.has(status)) {
225
+ settle({ status: "retryable", ...retryAfter() });
226
+ }
227
+ else {
228
+ settle({
229
+ status: "failure",
230
+ error: new OTLPExporterError(res.statusMessage, status, Buffer.concat(chunks).toString()),
231
+ });
232
+ }
233
+ });
234
+ // A response that breaks off after its status line: upstream counts a 2xx as delivered,
235
+ // retries a retryable status, and fails anything else.
236
+ res.on("error", (error) => {
237
+ const status = res.statusCode;
238
+ if (status && status <= 299) {
239
+ settle({ status: "success" });
240
+ }
241
+ else if (status && RETRYABLE_STATUSES.has(status)) {
242
+ settle({ status: "retryable", error, ...retryAfter() });
243
+ }
244
+ else {
245
+ settle({ status: "failure", error });
246
+ }
247
+ });
248
+ });
249
+ req.on("error", (error) => {
250
+ settle(retryableNetworkError(error) ? { status: "retryable", error } : { status: "failure", error });
251
+ });
252
+ // The body is written and then ended, as upstream's stream is. Node frames that as chunked,
253
+ // where ending with the data in one call would send a Content-Length. Bun buffers a request
254
+ // body whichever way it is written and sends a Content-Length. For a body that is not
255
+ // compressed, upstream's transport sends the same under Bun. For a gzip body it does not:
256
+ // upstream pipes a gzip stream, which Bun frames as chunked, and this transport compresses
257
+ // the body first, so Bun sends its length. A collector reads either.
258
+ const body = req;
259
+ const sendBody = (bytes) => {
260
+ body.write(bytes);
261
+ body.end();
262
+ };
263
+ if (gzipped) {
264
+ gzip(data, (error, compressed) => {
265
+ if (settled)
266
+ return;
267
+ if (error !== null)
268
+ end({ status: "failure", error });
269
+ else
270
+ sendBody(compressed);
271
+ });
272
+ }
273
+ else {
274
+ sendBody(data);
275
+ }
276
+ }
277
+ catch (err) {
278
+ end({ status: "failure", error: asError(err) });
279
+ }
280
+ });
281
+ }
282
+ }
283
+ /**
284
+ * Creates the transport for one exporter. Nothing is connected or loaded until the first send.
285
+ * timers is for tests, which decide when time passes.
286
+ */
287
+ export function createHttpTransport(params, timers = REAL_TIMERS) {
288
+ return new HttpTransport(params, timers);
289
+ }
package/dist/serve.d.ts CHANGED
@@ -19,6 +19,8 @@ export interface ServeOptions {
19
19
  * Resolves the route template of a request, such as "/projects/:id", for the span name,
20
20
  * http.route and the metric. A template that starts with a method and a space ("GET /x") names
21
21
  * the span verbatim, as a Go ServeMux pattern does. Without a route the span is named by method.
22
+ * A function that throws leaves the request unrouted, and is reported to the error handler by the
23
+ * class of what it threw, never with its message, which can quote the URL.
22
24
  */
23
25
  readonly route?: (req: Request) => string | undefined;
24
26
  /**
@@ -54,8 +56,9 @@ export interface ServeOptions {
54
56
  *
55
57
  * The default watches responses whose content type is text/html or text/event-stream, compared
56
58
  * case-insensitively without parameters: pages that stream as they render, and event streams.
57
- * A predicate that throws watches nothing. Responses to HEAD requests and with status 101, 204, 205
58
- * or 304 are never watched, since they carry no body.
59
+ * A predicate that throws watches nothing, and is reported to the error handler by the class of
60
+ * what it threw. Responses to HEAD requests and with status 101, 204, 205 or 304 are never
61
+ * watched, since they carry no body.
59
62
  */
60
63
  readonly watchBody?: (res: Response) => boolean;
61
64
  }
@@ -67,6 +70,11 @@ export interface ServeOptions {
67
70
  * is passed through a wrapper that ends the span when the body finishes; that wrapper is a stream,
68
71
  * so a body of known length is sent chunked. Any other response ends the span when the handler
69
72
  * returns and is passed on untouched.
73
+ *
74
+ * The telemetry never fails the request. A propagator that throws on extract leaves the request
75
+ * without the inbound context, a span that cannot start leaves it uninstrumented, and a span that
76
+ * cannot end changes nothing the caller sees. Each is reported to the error handler, and the handler
77
+ * runs exactly once either way. Only the handler's own error reaches the caller.
70
78
  */
71
79
  export declare function instrumentServe<A extends unknown[]>(handler: (req: Request, ...rest: A) => Response | Promise<Response>, opts?: ServeOptions): (req: Request, ...rest: A) => Promise<Response>;
72
80
  /**