@libo11y/server 0.1.2 → 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.
package/dist/serve.js CHANGED
@@ -12,9 +12,9 @@
12
12
  */
13
13
  import { startRecord } from "@libo11y/core";
14
14
  import { ATTR_DURATION, ATTR_OUTCOME, EVENT_REQUEST_SUMMARY, OUTCOME_VALUE_FAILURE, OUTCOME_VALUE_SUCCESS, } from "@libo11y/spec";
15
- import { context, createContextKey, diag, isSpanContextValid, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
15
+ import { context, createContextKey, isSpanContextValid, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
16
16
  import { matchesAny } from "./glob.js";
17
- import { asException, errorConstructorName, HEADERS_GETTER, instrumentResolver, methodName, normalizeMethod, schemeOf, serverAttributes, } from "./http-common.js";
17
+ import { asException, errorConstructorName, errorMessage, HEADERS_GETTER, instrumentResolver, methodName, normalizeMethod, reportError, schemeOf, serverAttributes, } from "./http-common.js";
18
18
  /**
19
19
  * Wraps a fetch-style handler with server instrumentation. Extra handler arguments, such as
20
20
  * Bun.serve's server, pass through. The handler runs inside the server span's context, so spans and
@@ -23,6 +23,11 @@ import { asException, errorConstructorName, HEADERS_GETTER, instrumentResolver,
23
23
  * is passed through a wrapper that ends the span when the body finishes; that wrapper is a stream,
24
24
  * so a body of known length is sent chunked. Any other response ends the span when the handler
25
25
  * returns and is passed on untouched.
26
+ *
27
+ * The telemetry never fails the request. A propagator that throws on extract leaves the request
28
+ * without the inbound context, a span that cannot start leaves it uninstrumented, and a span that
29
+ * cannot end changes nothing the caller sees. Each is reported to the error handler, and the handler
30
+ * runs exactly once either way. Only the handler's own error reaches the caller.
26
31
  */
27
32
  export function instrumentServe(handler, opts = {}) {
28
33
  const instruments = instrumentResolver(opts.telemetry, "http.server.request.duration", "Duration of HTTP server requests.");
@@ -33,16 +38,19 @@ export function instrumentServe(handler, opts = {}) {
33
38
  return watch(res);
34
39
  }
35
40
  catch (err) {
36
- diag.warn(`libo11y: instrumentServe: watchBody threw, the body is not watched: ${errorMessage(err)}`);
41
+ // By class only, as every report is: the predicate is handed the response, and its error
42
+ // can quote a header.
43
+ reportError(opts.telemetry, "instrumentServe: the watchBody option failed, the body is not watched", err);
37
44
  return false;
38
45
  }
39
46
  };
40
47
  const summaryTelemetry = opts.canonicalLine === true ? opts.telemetry : undefined;
41
- return async (req, ...rest) => {
48
+ // begin extracts the inbound context and starts the server span, or returns undefined for an
49
+ // ignored path. Whatever it throws comes from the telemetry, never from the handler.
50
+ const begin = (req) => {
42
51
  const url = new URL(req.url);
43
52
  if (ignore.length > 0 && matchesAny(ignore, decodedPath(url.pathname)))
44
- return handler(req, ...rest);
45
- const start = performance.now();
53
+ return undefined;
46
54
  const { tracer, histogram, propagator } = instruments();
47
55
  const { method, original } = normalizeMethod(req.method);
48
56
  let resolved;
@@ -50,12 +58,19 @@ export function instrumentServe(handler, opts = {}) {
50
58
  resolved = opts.route?.(req);
51
59
  }
52
60
  catch (err) {
53
- diag.warn(`libo11y: instrumentServe: route threw, the request is unrouted: ${errorMessage(err)}`);
61
+ // By class only: the function is handed the request, and its error can quote the URL.
62
+ reportError(opts.telemetry, "instrumentServe: the route option failed, the request is unrouted", err);
54
63
  }
55
64
  const route = resolved === "" ? undefined : resolved;
56
65
  const startRoute = route === undefined ? undefined : routeOnly(route);
57
66
  const scheme = schemeOf(url);
58
- const extracted = propagator.extract(context.active(), req.headers, HEADERS_GETTER);
67
+ let extracted = context.active();
68
+ try {
69
+ extracted = propagator.extract(extracted, req.headers, HEADERS_GETTER);
70
+ }
71
+ catch (err) {
72
+ reportError(opts.telemetry, "instrumentServe: extracting the inbound context failed, it is ignored", err);
73
+ }
59
74
  const attributes = {
60
75
  "http.request.method": method,
61
76
  ...(original === undefined ? {} : { "http.request.method_original": original }),
@@ -83,6 +98,48 @@ export function instrumentServe(handler, opts = {}) {
83
98
  if (summaryTelemetry !== undefined) {
84
99
  ({ context: handlerContext, record } = startRecord(handlerContext));
85
100
  }
101
+ return { span, histogram, method, original, scheme, startRoute, routeSlot, handlerContext, record };
102
+ };
103
+ // respond ends the request, or arranges for the response body to end it, and returns the response
104
+ // to send.
105
+ const respond = (req, res, span, finish) => {
106
+ // Headers first: Bun fills in the implicit content-type of a Blob, Bun.file, FormData or
107
+ // URLSearchParams body only when headers is read before body or bodyUsed.
108
+ const resHeaders = res.headers;
109
+ const status = res.status;
110
+ const timing = opts.serverTiming === true && isHtml(resHeaders.get("content-type")) ? serverTiming(span) : undefined;
111
+ // A HEAD response or a bodiless status sends no body, and Bun neither reads nor cancels one it was
112
+ // given. An unwatched body is sent as it is, keeping its length and Bun's sendfile path. Either
113
+ // way the request ends now and the response goes out as the handler returned it.
114
+ if (req.method.toUpperCase() === "HEAD" ||
115
+ BODILESS_STATUSES.has(status) ||
116
+ !shouldWatch(res) ||
117
+ res.bodyUsed ||
118
+ res.body === null) {
119
+ finish({ status });
120
+ return timing === undefined ? res : withServerTiming(res, resHeaders, timing);
121
+ }
122
+ let headers = resHeaders;
123
+ if (timing !== undefined) {
124
+ headers = new Headers(resHeaders);
125
+ headers.append("server-timing", timing);
126
+ }
127
+ const body = watchBody(res.body, (failure) => finish(failure === undefined ? { status } : { status, failure }));
128
+ return rebuild(res, body, headers);
129
+ };
130
+ return async (req, ...rest) => {
131
+ const start = performance.now();
132
+ let begun;
133
+ try {
134
+ begun = begin(req);
135
+ }
136
+ catch (err) {
137
+ reportError(opts.telemetry, "instrumentServe: starting the request's telemetry failed, the request is not instrumented", err);
138
+ }
139
+ // An ignored path, or telemetry that could not start: the handler runs as if unwrapped.
140
+ if (begun === undefined)
141
+ return handler(req, ...rest);
142
+ const { span, histogram, method, original, scheme, startRoute, routeSlot, handlerContext, record } = begun;
86
143
  // The context the end is reported in, captured now: the body may finish where none is active.
87
144
  const spanContext = handlerContext;
88
145
  // end reports the outcome once; finish guards it, so a throw from a span processor or an
@@ -141,7 +198,7 @@ export function instrumentServe(handler, opts = {}) {
141
198
  end(outcome);
142
199
  }
143
200
  catch (err) {
144
- diag.error(`libo11y: instrumentServe: ending the request threw: ${errorMessage(err)}`);
201
+ reportError(opts.telemetry, "instrumentServe: ending the request's telemetry failed", err);
145
202
  }
146
203
  };
147
204
  let res;
@@ -158,31 +215,28 @@ export function instrumentServe(handler, opts = {}) {
158
215
  finish({ status: 101 });
159
216
  return res;
160
217
  }
161
- // Headers first: Bun fills in the implicit content-type of a Blob, Bun.file, FormData or
162
- // URLSearchParams body only when headers is read before body or bodyUsed.
163
- const resHeaders = res.headers;
164
- const status = res.status;
165
- const timing = opts.serverTiming === true && isHtml(resHeaders.get("content-type")) ? serverTiming(span) : undefined;
166
- // A HEAD response or a bodiless status sends no body, and Bun neither reads nor cancels one it was
167
- // given. An unwatched body is sent as it is, keeping its length and Bun's sendfile path. Either
168
- // way the request ends now and the response goes out as the handler returned it.
169
- if (req.method.toUpperCase() === "HEAD" ||
170
- BODILESS_STATUSES.has(status) ||
171
- !shouldWatch(res) ||
172
- res.bodyUsed ||
173
- res.body === null) {
174
- finish({ status });
175
- return timing === undefined ? res : withServerTiming(res, resHeaders, timing);
218
+ try {
219
+ return respond(req, res, span, finish);
176
220
  }
177
- let headers = resHeaders;
178
- if (timing !== undefined) {
179
- headers = new Headers(resHeaders);
180
- headers.append("server-timing", timing);
221
+ catch (err) {
222
+ // Nothing of the handler's runs in respond, so this is the telemetry failing on a response it
223
+ // could not read, such as a value that is not a Response. The caller gets what the handler made.
224
+ reportError(opts.telemetry, "instrumentServe: reading the response failed, it is returned as the handler made it", err);
225
+ finish({ status: statusOf(res) });
226
+ return res;
181
227
  }
182
- const body = watchBody(res.body, (failure) => finish(failure === undefined ? { status } : { status, failure }));
183
- return rebuild(res, body, headers);
184
228
  };
185
229
  }
230
+ /** The status of whatever a handler resolved with, or 500 when it has none to read. */
231
+ function statusOf(res) {
232
+ try {
233
+ const status = res?.status;
234
+ return typeof status === "number" ? status : 500;
235
+ }
236
+ catch {
237
+ return 500;
238
+ }
239
+ }
186
240
  // The statuses whose responses never carry a body: 101 has none, and the Fetch standard calls
187
241
  // 204, 205 and 304 null body statuses.
188
242
  const BODILESS_STATUSES = new Set([101, 204, 205, 304]);
@@ -247,9 +301,6 @@ function serverTiming(span) {
247
301
  const flags = (sc.traceFlags & 0xff).toString(16).padStart(2, "0");
248
302
  return `traceparent;desc="00-${sc.traceId}-${sc.spanId}-${flags}"`;
249
303
  }
250
- function errorMessage(err) {
251
- return err instanceof Error ? err.message : String(err);
252
- }
253
304
  // rebuild makes a new Response: upstream responses, such as fetch's, have immutable headers.
254
305
  function rebuild(res, body, headers) {
255
306
  return new Response(body, { status: res.status, statusText: res.statusText, headers });
package/dist/signals.d.ts CHANGED
@@ -2,6 +2,11 @@
2
2
  * Shutting down on a termination signal (Go ShutdownOnSignals). One listener per signal is
3
3
  * registered with once; the first signal removes the others, so a second signal gets the runtime's
4
4
  * default handling and ends the process. The process is never exited here.
5
+ *
6
+ * beforeShutdown and the telemetry shutdown share one deadline, and together never take longer
7
+ * than it. beforeShutdown may use nine tenths of the deadline. The shutdown gets whatever is left
8
+ * of the whole, which is then never less than a tenth, so the buffered telemetry has a chance to
9
+ * leave even when beforeShutdown used all it was allowed.
5
10
  */
6
11
  import type { SignalReport, Telemetry } from "@libo11y/core";
7
12
  /** Where signals come from: process, or a test's emitter. */
@@ -9,23 +14,34 @@ export interface SignalSource {
9
14
  once(signal: string, listener: () => void): unknown;
10
15
  removeListener(signal: string, listener: () => void): unknown;
11
16
  }
17
+ /** The clock and timers shutdownOnSignals uses. A test replaces them to decide when time passes. */
18
+ export interface SignalClock {
19
+ now(): number;
20
+ setTimeout(fn: () => void, ms: number): unknown;
21
+ clearTimeout(handle: unknown): void;
22
+ }
12
23
  /** Options for shutdownOnSignals. */
13
24
  export interface ShutdownOnSignalsOptions {
14
25
  /** The signal names to wait for. Default ["SIGINT", "SIGTERM"]. */
15
26
  readonly signals?: readonly string[];
16
- /** The shutdown deadline, which also bounds beforeShutdown. Default: shutdown's own, 5000 ms. */
27
+ /**
28
+ * The one deadline for beforeShutdown and the telemetry shutdown together, in milliseconds.
29
+ * Default 5000, shutdown's own. A negative value is 0 and anything past 2147483647 is that. A
30
+ * string that reads as a finite number is taken as that number, and any other value that is not
31
+ * a number is the default.
32
+ */
17
33
  readonly timeoutMillis?: number;
18
34
  /**
19
35
  * Runs after the signal and before the telemetry shuts down, to stop what still makes telemetry:
20
36
  * typically the server, so requests in flight finish and their spans and metrics are exported.
21
- * It gets the same deadline as the shutdown, timeoutMillis, and the shutdown runs when it
22
- * settles or the deadline passes. A throw, a rejection or the deadline passing is reported in
23
- * the shutdown report as a "lifecycle" error, never thrown.
37
+ * It may take nine tenths of timeoutMillis. The shutdown runs when it settles or that time has
38
+ * passed, with what is left of timeoutMillis. A throw, a rejection or running out of time is
39
+ * reported in the shutdown report as a "lifecycle" error, never thrown.
24
40
  */
25
41
  readonly beforeShutdown?: () => Promise<void> | void;
26
42
  }
27
- /** shutdownOnSignals with the signals taken from source. */
28
- export declare function shutdownOnSignalsWith(source: SignalSource, telemetry: Telemetry, opts?: ShutdownOnSignalsOptions): Promise<SignalReport>;
43
+ /** shutdownOnSignals with the signals taken from source. clock is for tests. */
44
+ export declare function shutdownOnSignalsWith(source: SignalSource, telemetry: Telemetry, opts?: ShutdownOnSignalsOptions, clock?: SignalClock): Promise<SignalReport>;
29
45
  /**
30
46
  * Resolves with the shutdown report once the process receives one of opts.signals (default SIGINT
31
47
  * and SIGTERM). Until then each of those signals has a listener, which replaces the runtime's
package/dist/signals.js CHANGED
@@ -1,9 +1,26 @@
1
+ const REAL_CLOCK = {
2
+ now: () => performance.now(),
3
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
4
+ clearTimeout: (handle) => clearTimeout(handle),
5
+ };
1
6
  const DEFAULT_SIGNALS = ["SIGINT", "SIGTERM"];
2
7
  const DEFAULT_TIMEOUT_MILLIS = 5000;
3
8
  /** The longest delay a timer takes: setTimeout treats anything larger as 1 ms. */
4
9
  const MAX_TIMEOUT_MILLIS = 2 ** 31 - 1;
5
- /** shutdownOnSignals with the signals taken from source. */
6
- export function shutdownOnSignalsWith(source, telemetry, opts = {}) {
10
+ /** The share of the deadline beforeShutdown may use. The rest is the telemetry shutdown's. */
11
+ const BEFORE_SHUTDOWN_SHARE = 0.9;
12
+ // deadlineOf reads a deadline as Telemetry.shutdown does. A number is clamped to what a timer can
13
+ // wait: negative is 0, and Infinity or anything past the timer maximum is the maximum. A string
14
+ // that reads as a finite number is that number. NaN, any other string and any other value are the
15
+ // default.
16
+ function deadlineOf(given) {
17
+ const ms = typeof given === "string" && given.trim() !== "" ? Number(given) : given;
18
+ if (typeof ms !== "number" || Number.isNaN(ms))
19
+ return DEFAULT_TIMEOUT_MILLIS;
20
+ return Math.min(Math.max(ms, 0), MAX_TIMEOUT_MILLIS);
21
+ }
22
+ /** shutdownOnSignals with the signals taken from source. clock is for tests. */
23
+ export function shutdownOnSignalsWith(source, telemetry, opts = {}, clock = REAL_CLOCK) {
7
24
  const signals = opts.signals ?? DEFAULT_SIGNALS;
8
25
  return new Promise((resolve) => {
9
26
  const listeners = new Map();
@@ -18,20 +35,27 @@ export function shutdownOnSignalsWith(source, telemetry, opts = {}) {
18
35
  source.once(signal, listener);
19
36
  }
20
37
  }).then(async () => {
21
- const before = opts.beforeShutdown === undefined
22
- ? undefined
23
- : await runBefore(opts.beforeShutdown, opts.timeoutMillis ?? DEFAULT_TIMEOUT_MILLIS);
24
- const report = await telemetry.shutdown(opts.timeoutMillis === undefined ? {} : { timeoutMillis: opts.timeoutMillis });
38
+ if (opts.beforeShutdown === undefined) {
39
+ return telemetry.shutdown(opts.timeoutMillis === undefined ? {} : { timeoutMillis: opts.timeoutMillis });
40
+ }
41
+ const deadline = deadlineOf(opts.timeoutMillis);
42
+ const allowed = deadline * BEFORE_SHUTDOWN_SHARE;
43
+ const started = clock.now();
44
+ const before = await runBefore(opts.beforeShutdown, allowed, clock);
45
+ // A timer can fire late. beforeShutdown is charged what it was allowed at most, so the
46
+ // shutdown always has its tenth.
47
+ const used = Math.min(Math.max(clock.now() - started, 0), allowed);
48
+ const report = await telemetry.shutdown({ timeoutMillis: deadline - used });
25
49
  if (before === undefined)
26
50
  return report;
27
51
  return { ok: false, errors: [{ signal: "lifecycle", error: before.error }, ...report.errors] };
28
52
  });
29
53
  }
30
54
  /** Runs fn within ms, and returns what went wrong, if anything. */
31
- async function runBefore(fn, ms) {
55
+ async function runBefore(fn, ms, clock) {
32
56
  let timer;
33
57
  const expired = new Promise((resolve) => {
34
- timer = setTimeout(() => resolve({ error: new Error("o11y: beforeShutdown: deadline exceeded") }), Number.isNaN(ms) ? DEFAULT_TIMEOUT_MILLIS : Math.min(Math.max(ms, 0), MAX_TIMEOUT_MILLIS));
58
+ timer = clock.setTimeout(() => resolve({ error: new Error("o11y: beforeShutdown: deadline exceeded") }), ms);
35
59
  });
36
60
  const ran = Promise.resolve()
37
61
  .then(fn)
@@ -44,7 +68,7 @@ async function runBefore(fn, ms) {
44
68
  return await Promise.race([ran, expired]);
45
69
  }
46
70
  finally {
47
- clearTimeout(timer);
71
+ clock.clearTimeout(timer);
48
72
  }
49
73
  }
50
74
  /**
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The @libo11y/server package version. scripts/release.ts keeps it equal to package.json. */
2
- export declare const VERSION = "0.1.2";
2
+ export declare const VERSION = "0.2.1";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The @libo11y/server package version. scripts/release.ts keeps it equal to package.json. */
2
- export const VERSION = "0.1.2";
2
+ export const VERSION = "0.2.1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libo11y/server",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "description": "The libo11y server platform for TypeScript on Bun and Node: AsyncLocalStorage context, resource detection, OTLP exporters from OTEL_* with exemplars, setup, registry loading, signal handling, runtime metrics, and instrumentServe and instrumentFetch for HTTP.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -17,16 +17,12 @@
17
17
  "directory": "ts/packages/server"
18
18
  },
19
19
  "dependencies": {
20
- "@libo11y/core": "0.1.2",
21
- "@libo11y/spec": "0.1.2",
20
+ "@libo11y/core": "0.2.1",
21
+ "@libo11y/spec": "0.2.1",
22
22
  "@opentelemetry/api": "1.10.0",
23
23
  "@opentelemetry/context-async-hooks": "3.1.1",
24
24
  "@opentelemetry/core": "3.1.1",
25
- "@opentelemetry/exporter-logs-otlp-http": "0.301.1",
26
- "@opentelemetry/exporter-logs-otlp-proto": "0.301.1",
27
25
  "@opentelemetry/exporter-metrics-otlp-http": "0.301.1",
28
- "@opentelemetry/exporter-trace-otlp-http": "0.301.1",
29
- "@opentelemetry/exporter-trace-otlp-proto": "0.301.1",
30
26
  "@opentelemetry/instrumentation": "0.301.1",
31
27
  "@opentelemetry/instrumentation-runtime-node": "0.38.0",
32
28
  "@opentelemetry/otlp-exporter-base": "0.301.1",
@@ -38,7 +34,7 @@
38
34
  "@opentelemetry/sdk-trace": "3.1.1"
39
35
  },
40
36
  "devDependencies": {
41
- "@libo11y/test": "0.1.2"
37
+ "@libo11y/test": "0.2.1"
42
38
  },
43
39
  "files": [
44
40
  "dist",