@libo11y/server 0.4.0 → 0.7.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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @libo11y/server
2
2
 
3
3
  The libo11y server platform for TypeScript on Bun 1.3.13 and Node 24. It
4
- binds [`@libo11y/core`](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/core) to a server runtime with an
4
+ binds [`@libo11y/core`](https://github.com/libo11y/libo11y/tree/main/ts/packages/core) to a server runtime with an
5
5
  `AsyncLocalStorage` context manager, resource detection, OTLP exporters
6
6
  built from the `OTEL_*` variables, a protobuf metric serializer that
7
7
  carries exemplars, runtime metrics, application registry loading and
@@ -12,6 +12,10 @@ servers and clients.
12
12
  npm install @libo11y/server
13
13
  ```
14
14
 
15
+ `@opentelemetry/api` is a peer dependency. npm 7 and later and Bun install
16
+ it automatically. If your application already depends on it, use a version
17
+ that satisfies `>=1.10.0 <1.11.0`.
18
+
15
19
  ## Quick start
16
20
 
17
21
  ```ts
@@ -63,17 +67,19 @@ An option outside the closed set of values it takes, such as
63
67
  `createTelemetry` with `O11yError` code `INVALID_OPTION`.
64
68
 
65
69
  Both take the `TelemetryOptions` that the
66
- [core README](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/core#options) lists. `OTEL_SDK_DISABLED=true`
67
- turns off every export, injected exporters included, and runtime metrics.
68
- The logger still writes to the console.
70
+ [core README](https://github.com/libo11y/libo11y/tree/main/ts/packages/core#options) lists. `OTEL_SDK_DISABLED=true`
71
+ turns off every export, injected exporters, readers and processors included,
72
+ and runtime metrics. The tracer provider is a no-op provider so no spans are
73
+ recorded while propagation and console log correlation keep working, and a
74
+ value other than `true` or `false` warns once and leaves the SDK enabled.
69
75
 
70
76
  This package re-exports the core types an application needs most:
71
77
  `Telemetry`, `TelemetryOptions`, `Logger`, `SignalReport`,
72
78
  `LifecycleOptions`, `O11yError` and `O11yErrorCode`.
73
79
 
74
80
  The repository has two complete examples:
75
- [`examples/bun-server`](https://github.com/jamesainslie/libo11y/tree/main/ts/examples/bun-server) and
76
- [`examples/node-server`](https://github.com/jamesainslie/libo11y/tree/main/ts/examples/node-server), a `node:http` server
81
+ [`examples/bun-server`](https://github.com/libo11y/libo11y/tree/main/ts/examples/bun-server) and
82
+ [`examples/node-server`](https://github.com/libo11y/libo11y/tree/main/ts/examples/node-server), a `node:http` server
77
83
  with a `Request` and `Response` adapter.
78
84
 
79
85
  ## HTTP servers
@@ -108,15 +114,15 @@ which `setup` makes libo11y's. A report names the step that failed and
108
114
  the class of the error, and never the error's message, because a
109
115
  propagator is handed the request's headers and its error can quote them.
110
116
 
111
- | Option | Effect |
112
- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
113
- | `telemetry` | the telemetry whose providers and propagator to use. Default: the globals `setup` installs |
114
- | `route` | resolves the route template of a request, such as `/projects/:id`, for the span name, `http.route` and the metric. A template that starts with a method and a space, such as `GET /x`, names the span verbatim |
115
- | `publicEndpoint` | an internet-facing server. Inbound trace context starts a new root span linked to it, instead of becoming its parent. Baggage is still extracted |
116
- | `ignorePaths` | URL paths to leave uninstrumented, as Go `path.Match` patterns such as `/healthz` or `/debug/*`, matched against the decoded path as Go matches them |
117
- | `serverTiming` | adds `Server-Timing: traceparent;desc="00-<trace>-<span>-<flags>"` to `text/html` responses, so the page can join the server's trace |
118
- | `canonicalLine` | emits one `o11y.request.summary` event per request with the request's wide record. It needs `telemetry` |
119
- | `watchBody` | `watchBody(res)` decides which responses end the span when the body finishes. Default: `text/html` and `text/event-stream` bodies. Other responses end the span when the handler returns, and keep their `Content-Length` and sendfile |
117
+ | Option | Effect |
118
+ | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
119
+ | `telemetry` | the telemetry whose providers and propagator to use. Default: the globals `setup` installs |
120
+ | `route` | resolves the route template of a request, such as `/projects/:id`, for the span name, `http.route` and the metric. A leading method prefix such as `GET /x` is stripped, and the span is named `<METHOD> <route>` using the normalized request method (`HTTP` for non-standard methods) |
121
+ | `publicEndpoint` | an internet-facing server. Inbound trace context starts a new root span linked to it, instead of becoming its parent. Baggage is still extracted |
122
+ | `ignorePaths` | URL paths to leave uninstrumented, as Go `path.Match` patterns such as `/healthz` or `/debug/*`, matched against the decoded path as Go matches them |
123
+ | `serverTiming` | adds `Server-Timing: traceparent;desc="00-<trace>-<span>-<flags>"` to `text/html` responses, so the page can join the server's trace. A span without a valid span context, as with no tracer provider set up, adds no entry |
124
+ | `canonicalLine` | emits one `o11y.request.summary` event per request with the request's wide record. It needs `telemetry` |
125
+ | `watchBody` | `watchBody(res)` decides which responses end the span when the body finishes. Default: `text/html` and `text/event-stream` bodies. Other responses end the span when the handler returns, and keep their `Content-Length` and sendfile |
120
126
 
121
127
  A framework that routes inside its own handler, such as TanStack Start,
122
128
  calls `setRoute(route)` from inside the handler. It sets `http.route` and
@@ -131,6 +137,11 @@ none of the diagnostics channels that Node's upstream instrumentation
131
137
  reads. Each request gets a CLIENT span named by method and the
132
138
  `http.client.request.duration` histogram. The span ends when the response
133
139
  headers arrive. A 4xx or 5xx response or a failed request marks it failed.
140
+ The span's `url.full` attribute is the request URL without its user name
141
+ and password. The values of the query keys that the OpenTelemetry HTTP
142
+ semantic conventions name for presigned URLs, `AWSAccessKeyId`,
143
+ `Signature`, `sig` and `X-Goog-Signature`, are replaced by `REDACTED`. The
144
+ keys match case-sensitively, and every other query value is kept as sent.
134
145
  The trace context goes into a copy of the request headers, and the caller's
135
146
  `Request` and `init` are never changed.
136
147
 
@@ -290,7 +301,7 @@ list applied in order. Unset or empty, it leaves the default,
290
301
  `setup` and `createTelemetry` with `O11yError` code
291
302
  `UNSUPPORTED_PROPAGATOR`. Pass a propagator for it through the
292
303
  `propagators` option. The
293
- [core README](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/core#options)
304
+ [core README](https://github.com/libo11y/libo11y/tree/main/ts/packages/core#options)
294
305
  has the details.
295
306
 
296
307
  ## Resource
@@ -353,6 +364,6 @@ Node 24 keeps the context in both of the last two cases.
353
364
 
354
365
  ## Parity
355
366
 
356
- [docs/PARITY.md](https://github.com/jamesainslie/libo11y/blob/main/docs/PARITY.md)
367
+ [docs/PARITY.md](https://github.com/libo11y/libo11y/blob/main/docs/PARITY.md)
357
368
  lists where the TypeScript packages match Go and where they differ, with
358
369
  the reasons.
package/dist/fetch.d.ts CHANGED
@@ -21,7 +21,8 @@ export interface FetchOptions {
21
21
  /**
22
22
  * Wraps fetchImpl (default: globalThis.fetch as it is now) with a CLIENT span per request, named by
23
23
  * method, and the http.client.request.duration histogram, recorded in the span's context so its
24
- * exemplar carries the trace. The span ends when the response headers arrive, or when the request
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
25
26
  * fails. 4xx and 5xx responses and failures mark the span failed. The trace context is injected
26
27
  * into a copy of the request headers; the caller's Request and init are never changed. A URL that
27
28
  * cannot be parsed is passed to fetchImpl uninstrumented, so its own error surfaces.
package/dist/fetch.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { context, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
2
- import { asException, HEADERS_SETTER, instrumentResolver, methodAttributes, methodName, normalizeMethod, reportError, serverAttributes, } from "./http-common.js";
2
+ import { asException, HEADERS_SETTER, instrumentResolver, methodAttributes, methodName, normalizeMethod, reportError, serverAttributes, urlFull, } from "./http-common.js";
3
3
  // The methods the Fetch standard upper-cases whatever case they are given in.
4
4
  const FETCH_NORMALIZED = new Set(["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]);
5
5
  /** The method fetch sends for raw: the Fetch standard upper-cases six methods in any case. */
@@ -28,7 +28,8 @@ function inject(telemetry, propagator, ctx, headers) {
28
28
  /**
29
29
  * Wraps fetchImpl (default: globalThis.fetch as it is now) with a CLIENT span per request, named by
30
30
  * method, and the http.client.request.duration histogram, recorded in the span's context so its
31
- * exemplar carries the trace. The span ends when the response headers arrive, or when the request
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
32
33
  * fails. 4xx and 5xx responses and failures mark the span failed. The trace context is injected
33
34
  * into a copy of the request headers; the caller's Request and init are never changed. A URL that
34
35
  * cannot be parsed is passed to fetchImpl uninstrumented, so its own error surfaces.
@@ -48,13 +49,10 @@ export function instrumentFetch(fetchImpl = globalThis.fetch, opts = {}) {
48
49
  const raw = sentMethod(rawMethod);
49
50
  const { method } = normalizeMethod(raw);
50
51
  const server = serverAttributes(url);
51
- const full = new URL(url);
52
- full.username = "";
53
- full.password = "";
54
52
  const attributes = {
55
53
  ...methodAttributes(raw),
56
54
  ...server,
57
- "url.full": full.href,
55
+ "url.full": urlFull(url),
58
56
  ...(opts.peerService === undefined ? {} : { "peer.service": opts.peerService }),
59
57
  };
60
58
  const parent = context.active();
@@ -26,6 +26,11 @@ export declare function methodName(method: string): string;
26
26
  export declare function methodAttributes(raw: string): Attributes;
27
27
  /** server.address and server.port of a URL: the host without IPv6 brackets, and the port or the scheme default. */
28
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;
29
34
  /** The URL scheme without its colon. */
30
35
  export declare function schemeOf(url: URL): string;
31
36
  /** The error.type of a thrown value: its constructor name for an Error, else "_OTHER". */
@@ -53,6 +53,52 @@ export function serverAttributes(url) {
53
53
  const port = url.port !== "" ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
54
54
  return { "server.address": host, "server.port": port };
55
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
+ }
56
102
  /** The URL scheme without its colon. */
57
103
  export function schemeOf(url) {
58
104
  return url.protocol.slice(0, -1);
package/dist/serve.d.ts CHANGED
@@ -17,8 +17,8 @@ export interface ServeOptions {
17
17
  readonly telemetry?: Telemetry;
18
18
  /**
19
19
  * Resolves the route template of a request, such as "/projects/:id", for the span name,
20
- * http.route and the metric. A template that starts with a method and a space ("GET /x") names
21
- * the span verbatim, as a Go ServeMux pattern does. Without a route the span is named by method.
20
+ * http.route and the metric. A method prefix such as "GET /x" is removed from the template.
21
+ * The span name uses the normalized request method followed by the route when present.
22
22
  * A function that throws leaves the request unrouted, and is reported to the error handler by the
23
23
  * class of what it threw, never with its message, which can quote the URL.
24
24
  */
@@ -37,7 +37,8 @@ export interface ServeOptions {
37
37
  readonly ignorePaths?: readonly string[];
38
38
  /**
39
39
  * Adds `Server-Timing: traceparent;desc="00-<trace>-<span>-<flags>"` to text/html responses, so
40
- * the page can join the server's trace. It works whether or not the body is watched (see
40
+ * the page can join the server's trace. A span without a valid span context, as from a no-op or
41
+ * disabled tracer provider, adds no entry. It works whether or not the body is watched (see
41
42
  * watchBody); the headers of an unwatched response are changed in place when they are mutable.
42
43
  */
43
44
  readonly serverTiming?: boolean;
@@ -81,7 +82,7 @@ export declare function instrumentServe<A extends unknown[]>(handler: (req: Requ
81
82
  * Sets the route template of the server request being handled, such as "/projects/:id", for
82
83
  * frameworks that route inside the handler, as TanStack Start does. It is the counterpart of Go
83
84
  * reading r.Pattern after the ServeMux has run. When the request ends, the route set last names
84
- * the span ("<METHOD> <route>", or the route verbatim when it starts with a method and a space)
85
+ * the span using the normalized request method and the route template
85
86
  * and is the http.route of the span, the duration metric and the summary, in place of the one
86
87
  * ServeOptions.route resolved. The span starts under the name ServeOptions.route gives, so a
87
88
  * sampler sees that one.
package/dist/serve.js CHANGED
@@ -61,8 +61,7 @@ export function instrumentServe(handler, opts = {}) {
61
61
  // By class only: the function is handed the request, and its error can quote the URL.
62
62
  reportError(opts.telemetry, "instrumentServe: the route option failed, the request is unrouted", err);
63
63
  }
64
- const route = resolved === "" ? undefined : resolved;
65
- const startRoute = route === undefined ? undefined : routeOnly(route);
64
+ const startRoute = routeOnly(resolved);
66
65
  const scheme = schemeOf(url);
67
66
  let extracted = context.active();
68
67
  try {
@@ -91,7 +90,7 @@ export function instrumentServe(handler, opts = {}) {
91
90
  spanOptions.links = [{ context: inbound }];
92
91
  }
93
92
  }
94
- const span = tracer.startSpan(spanName(method, route), spanOptions, extracted);
93
+ const span = tracer.startSpan(spanName(method, startRoute), spanOptions, extracted);
95
94
  const routeSlot = { open: true };
96
95
  let handlerContext = trace.setSpan(extracted, span).setValue(ROUTE_KEY, routeSlot);
97
96
  let record;
@@ -147,8 +146,8 @@ export function instrumentServe(handler, opts = {}) {
147
146
  const end = (outcome) => {
148
147
  let httpRoute = startRoute;
149
148
  if (routeSlot.route !== undefined) {
150
- httpRoute = routeOnly(routeSlot.route);
151
- span.updateName(spanName(method, routeSlot.route));
149
+ httpRoute = routeSlot.route;
150
+ span.updateName(spanName(method, httpRoute));
152
151
  span.setAttribute("http.route", httpRoute);
153
152
  }
154
153
  const failure = outcome.failure;
@@ -245,7 +244,7 @@ const ROUTE_KEY = createContextKey("libo11y.server.route");
245
244
  * Sets the route template of the server request being handled, such as "/projects/:id", for
246
245
  * frameworks that route inside the handler, as TanStack Start does. It is the counterpart of Go
247
246
  * reading r.Pattern after the ServeMux has run. When the request ends, the route set last names
248
- * the span ("<METHOD> <route>", or the route verbatim when it starts with a method and a space)
247
+ * the span using the normalized request method and the route template
249
248
  * and is the http.route of the span, the duration metric and the summary, in place of the one
250
249
  * ServeOptions.route resolved. The span starts under the name ServeOptions.route gives, so a
251
250
  * sampler sees that one.
@@ -255,23 +254,23 @@ const ROUTE_KEY = createContextKey("libo11y.server.route");
255
254
  * an empty route, it does nothing.
256
255
  */
257
256
  export function setRoute(route) {
258
- if (route === "")
257
+ const template = routeOnly(route);
258
+ if (template === undefined)
259
259
  return;
260
260
  const slot = context.active().getValue(ROUTE_KEY);
261
261
  if (slot?.open === true)
262
- slot.route = route;
262
+ slot.route = template;
263
263
  }
264
264
  function spanName(method, route) {
265
- if (route === undefined || route === "")
266
- return methodName(method);
267
- if (route.includes(" "))
268
- return route;
269
- return `${methodName(method)} ${route}`;
265
+ const name = methodName(method);
266
+ return route === undefined ? name : `${name} ${route}`;
270
267
  }
271
- // routeOnly strips a leading method from a route template ("GET /users/:id" -> "/users/:id").
268
+ // Like Go's ServeMux, a route pattern can have a method and host before the path.
272
269
  function routeOnly(route) {
273
- const space = route.indexOf(" ");
274
- return space < 0 ? route : route.slice(space + 1);
270
+ if (route === undefined)
271
+ return undefined;
272
+ const pathStart = route.indexOf("/");
273
+ return pathStart >= 0 ? route.slice(pathStart).trimEnd() : undefined;
275
274
  }
276
275
  /**
277
276
  * The percent-decoded path, as Go's URL.Path, which ignorePaths match against. A malformed escape
@@ -296,8 +295,12 @@ function watchesByDefault(res) {
296
295
  const type = mediaType(res.headers.get("content-type"));
297
296
  return type === "text/html" || type === "text/event-stream";
298
297
  }
298
+ /** The Server-Timing traceparent entry for span, or undefined when its span context is not valid. */
299
299
  function serverTiming(span) {
300
300
  const sc = span.spanContext();
301
+ // A no-op or disabled provider hands out the all-zero span context, which joins no trace.
302
+ if (!isSpanContextValid(sc))
303
+ return undefined;
301
304
  const flags = (sc.traceFlags & 0xff).toString(16).padStart(2, "0");
302
305
  return `traceparent;desc="00-${sc.traceId}-${sc.spanId}-${flags}"`;
303
306
  }
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.4.0";
2
+ export declare const VERSION = "0.7.0";
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.4.0";
2
+ export const VERSION = "0.7.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libo11y/server",
3
- "version": "0.4.0",
3
+ "version": "0.7.0",
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",
@@ -13,17 +13,15 @@
13
13
  },
14
14
  "repository": {
15
15
  "type": "git",
16
- "url": "git+https://github.com/jamesainslie/libo11y.git",
16
+ "url": "git+https://github.com/libo11y/libo11y.git",
17
17
  "directory": "ts/packages/server"
18
18
  },
19
19
  "dependencies": {
20
- "@libo11y/core": "0.4.0",
21
- "@libo11y/spec": "0.4.0",
22
- "@opentelemetry/api": "1.10.0",
20
+ "@libo11y/core": "0.7.0",
21
+ "@libo11y/spec": "0.7.0",
23
22
  "@opentelemetry/context-async-hooks": "3.1.1",
24
23
  "@opentelemetry/core": "3.1.1",
25
24
  "@opentelemetry/exporter-metrics-otlp-http": "0.301.1",
26
- "@opentelemetry/instrumentation": "0.301.1",
27
25
  "@opentelemetry/instrumentation-runtime-node": "0.38.0",
28
26
  "@opentelemetry/otlp-exporter-base": "0.301.1",
29
27
  "@opentelemetry/otlp-transformer": "0.301.1",
@@ -33,8 +31,12 @@
33
31
  "@opentelemetry/sdk-metrics": "3.1.1",
34
32
  "@opentelemetry/sdk-trace": "3.1.1"
35
33
  },
34
+ "peerDependencies": {
35
+ "@opentelemetry/api": ">=1.10.0 <1.11.0"
36
+ },
36
37
  "devDependencies": {
37
- "@libo11y/test": "0.4.0"
38
+ "@libo11y/test": "0.7.0",
39
+ "@opentelemetry/api": "1.10.0"
38
40
  },
39
41
  "files": [
40
42
  "dist",