@libo11y/server 0.7.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/serve.js DELETED
@@ -1,375 +0,0 @@
1
- /**
2
- * instrumentServe: server instrumentation for fetch-style handlers, `(Request) => Response`, as
3
- * Bun.serve, Hono, Elysia and node:http adapters use. It is the counterpart of Go's
4
- * o11yhttp.NewHandler: a SERVER span named "<METHOD> <route>", http.server.request.duration with
5
- * exemplars, and optionally the o11y.request.summary canonical line.
6
- *
7
- * For a watched body (HTML and event streams by default), the span, the duration and the summary
8
- * end when the response body finishes, errors or is cancelled, from a body wrapper that holds the
9
- * span itself. For any other response they end when the handler returns. Nothing at the end reads
10
- * the active context, because Bun 1.3 loses it inside an async generator body after its first
11
- * await (oven-sh/bun#24199).
12
- */
13
- import { startRecord } from "@libo11y/core";
14
- import { ATTR_DURATION, ATTR_OUTCOME, EVENT_REQUEST_SUMMARY, OUTCOME_VALUE_FAILURE, OUTCOME_VALUE_SUCCESS, } from "@libo11y/spec";
15
- import { context, createContextKey, isSpanContextValid, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
16
- import { matchesAny } from "./glob.js";
17
- import { asException, errorConstructorName, errorMessage, HEADERS_GETTER, instrumentResolver, methodName, normalizeMethod, reportError, schemeOf, serverAttributes, } from "./http-common.js";
18
- /**
19
- * Wraps a fetch-style handler with server instrumentation. Extra handler arguments, such as
20
- * Bun.serve's server, pass through. The handler runs inside the server span's context, so spans and
21
- * logs it makes are children of it. A throw marks the span failed, records the exception and a 500,
22
- * and is re-thrown. A watched body (see ServeOptions.watchBody: HTML and event streams by default)
23
- * is passed through a wrapper that ends the span when the body finishes; that wrapper is a stream,
24
- * so a body of known length is sent chunked. Any other response ends the span when the handler
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.
31
- */
32
- export function instrumentServe(handler, opts = {}) {
33
- const instruments = instrumentResolver(opts.telemetry, "http.server.request.duration", "Duration of HTTP server requests.");
34
- const ignore = opts.ignorePaths ?? [];
35
- const watch = opts.watchBody ?? watchesByDefault;
36
- const shouldWatch = (res) => {
37
- try {
38
- return watch(res);
39
- }
40
- catch (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);
44
- return false;
45
- }
46
- };
47
- const summaryTelemetry = opts.canonicalLine === true ? opts.telemetry : undefined;
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) => {
51
- const url = new URL(req.url);
52
- if (ignore.length > 0 && matchesAny(ignore, decodedPath(url.pathname)))
53
- return undefined;
54
- const { tracer, histogram, propagator } = instruments();
55
- const { method, original } = normalizeMethod(req.method);
56
- let resolved;
57
- try {
58
- resolved = opts.route?.(req);
59
- }
60
- catch (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);
63
- }
64
- const startRoute = routeOnly(resolved);
65
- const scheme = schemeOf(url);
66
- let extracted = context.active();
67
- try {
68
- extracted = propagator.extract(extracted, req.headers, HEADERS_GETTER);
69
- }
70
- catch (err) {
71
- reportError(opts.telemetry, "instrumentServe: extracting the inbound context failed, it is ignored", err);
72
- }
73
- const attributes = {
74
- "http.request.method": method,
75
- ...(original === undefined ? {} : { "http.request.method_original": original }),
76
- "url.scheme": scheme,
77
- "url.path": url.pathname,
78
- ...serverAttributes(url),
79
- };
80
- const userAgent = req.headers.get("user-agent");
81
- if (userAgent !== null)
82
- attributes["user_agent.original"] = userAgent;
83
- if (startRoute !== undefined)
84
- attributes["http.route"] = startRoute;
85
- const spanOptions = { kind: SpanKind.SERVER, attributes };
86
- if (opts.publicEndpoint === true) {
87
- spanOptions.root = true;
88
- const inbound = trace.getSpanContext(extracted);
89
- if (inbound !== undefined && isSpanContextValid(inbound) && inbound.isRemote === true) {
90
- spanOptions.links = [{ context: inbound }];
91
- }
92
- }
93
- const span = tracer.startSpan(spanName(method, startRoute), spanOptions, extracted);
94
- const routeSlot = { open: true };
95
- let handlerContext = trace.setSpan(extracted, span).setValue(ROUTE_KEY, routeSlot);
96
- let record;
97
- if (summaryTelemetry !== undefined) {
98
- ({ context: handlerContext, record } = startRecord(handlerContext));
99
- }
100
- return { span, histogram, method, original, scheme, startRoute, routeSlot, handlerContext, record };
101
- };
102
- // respond ends the request, or arranges for the response body to end it, and returns the response
103
- // to send.
104
- const respond = (req, res, span, finish) => {
105
- // Headers first: Bun fills in the implicit content-type of a Blob, Bun.file, FormData or
106
- // URLSearchParams body only when headers is read before body or bodyUsed.
107
- const resHeaders = res.headers;
108
- const status = res.status;
109
- const timing = opts.serverTiming === true && isHtml(resHeaders.get("content-type")) ? serverTiming(span) : undefined;
110
- // A HEAD response or a bodiless status sends no body, and Bun neither reads nor cancels one it was
111
- // given. An unwatched body is sent as it is, keeping its length and Bun's sendfile path. Either
112
- // way the request ends now and the response goes out as the handler returned it.
113
- if (req.method.toUpperCase() === "HEAD" ||
114
- BODILESS_STATUSES.has(status) ||
115
- !shouldWatch(res) ||
116
- res.bodyUsed ||
117
- res.body === null) {
118
- finish({ status });
119
- return timing === undefined ? res : withServerTiming(res, resHeaders, timing);
120
- }
121
- let headers = resHeaders;
122
- if (timing !== undefined) {
123
- headers = new Headers(resHeaders);
124
- headers.append("server-timing", timing);
125
- }
126
- const body = watchBody(res.body, (failure) => finish(failure === undefined ? { status } : { status, failure }));
127
- return rebuild(res, body, headers);
128
- };
129
- return async (req, ...rest) => {
130
- const start = performance.now();
131
- let begun;
132
- try {
133
- begun = begin(req);
134
- }
135
- catch (err) {
136
- reportError(opts.telemetry, "instrumentServe: starting the request's telemetry failed, the request is not instrumented", err);
137
- }
138
- // An ignored path, or telemetry that could not start: the handler runs as if unwrapped.
139
- if (begun === undefined)
140
- return handler(req, ...rest);
141
- const { span, histogram, method, original, scheme, startRoute, routeSlot, handlerContext, record } = begun;
142
- // The context the end is reported in, captured now: the body may finish where none is active.
143
- const spanContext = handlerContext;
144
- // end reports the outcome once; finish guards it, so a throw from a span processor or an
145
- // instrument never fails the request, replaces the handler's error or stops a body's cancel.
146
- const end = (outcome) => {
147
- let httpRoute = startRoute;
148
- if (routeSlot.route !== undefined) {
149
- httpRoute = routeSlot.route;
150
- span.updateName(spanName(method, httpRoute));
151
- span.setAttribute("http.route", httpRoute);
152
- }
153
- const failure = outcome.failure;
154
- const failed = failure !== undefined;
155
- const errorType = failed
156
- ? errorConstructorName(failure.error)
157
- : outcome.status >= 500
158
- ? String(outcome.status)
159
- : undefined;
160
- span.setAttribute("http.response.status_code", outcome.status);
161
- if (errorType !== undefined)
162
- span.setAttribute("error.type", errorType);
163
- if (failed) {
164
- span.recordException(asException(failure.error));
165
- span.setStatus({ code: SpanStatusCode.ERROR, message: errorMessage(failure.error) });
166
- }
167
- else if (outcome.status >= 500) {
168
- span.setStatus({ code: SpanStatusCode.ERROR });
169
- }
170
- const seconds = (performance.now() - start) / 1000;
171
- histogram.record(seconds, {
172
- "http.request.method": method,
173
- "url.scheme": scheme,
174
- ...(httpRoute === undefined ? {} : { "http.route": httpRoute }),
175
- "http.response.status_code": outcome.status,
176
- ...(errorType === undefined ? {} : { "error.type": errorType }),
177
- }, trace.setSpan(ROOT_CONTEXT, span));
178
- if (record !== undefined && summaryTelemetry !== undefined) {
179
- emitSummary(summaryTelemetry, record, spanContext, {
180
- method,
181
- original,
182
- status: outcome.status,
183
- failed: failed || outcome.status >= 500,
184
- seconds,
185
- route: httpRoute,
186
- });
187
- }
188
- span.end();
189
- };
190
- let finished = false;
191
- const finish = (outcome) => {
192
- if (finished)
193
- return;
194
- finished = true;
195
- routeSlot.open = false;
196
- try {
197
- end(outcome);
198
- }
199
- catch (err) {
200
- reportError(opts.telemetry, "instrumentServe: ending the request's telemetry failed", err);
201
- }
202
- };
203
- let res;
204
- try {
205
- res = await context.with(handlerContext, () => handler(req, ...rest));
206
- }
207
- catch (err) {
208
- finish({ status: 500, failure: { error: err } });
209
- throw err;
210
- }
211
- if (res === undefined) {
212
- // Bun.serve handlers return nothing after server.upgrade(req): the connection was taken over,
213
- // which Go reports as 101.
214
- finish({ status: 101 });
215
- return res;
216
- }
217
- try {
218
- return respond(req, res, span, finish);
219
- }
220
- catch (err) {
221
- // Nothing of the handler's runs in respond, so this is the telemetry failing on a response it
222
- // could not read, such as a value that is not a Response. The caller gets what the handler made.
223
- reportError(opts.telemetry, "instrumentServe: reading the response failed, it is returned as the handler made it", err);
224
- finish({ status: statusOf(res) });
225
- return res;
226
- }
227
- };
228
- }
229
- /** The status of whatever a handler resolved with, or 500 when it has none to read. */
230
- function statusOf(res) {
231
- try {
232
- const status = res?.status;
233
- return typeof status === "number" ? status : 500;
234
- }
235
- catch {
236
- return 500;
237
- }
238
- }
239
- // The statuses whose responses never carry a body: 101 has none, and the Fetch standard calls
240
- // 204, 205 and 304 null body statuses.
241
- const BODILESS_STATUSES = new Set([101, 204, 205, 304]);
242
- const ROUTE_KEY = createContextKey("libo11y.server.route");
243
- /**
244
- * Sets the route template of the server request being handled, such as "/projects/:id", for
245
- * frameworks that route inside the handler, as TanStack Start does. It is the counterpart of Go
246
- * reading r.Pattern after the ServeMux has run. When the request ends, the route set last names
247
- * the span using the normalized request method and the route template
248
- * and is the http.route of the span, the duration metric and the summary, in place of the one
249
- * ServeOptions.route resolved. The span starts under the name ServeOptions.route gives, so a
250
- * sampler sees that one.
251
- *
252
- * It finds the request through the active context, which instrumentServe sets for the handler, so
253
- * it needs a context manager (setup installs one). Outside a request, after it has ended, or with
254
- * an empty route, it does nothing.
255
- */
256
- export function setRoute(route) {
257
- const template = routeOnly(route);
258
- if (template === undefined)
259
- return;
260
- const slot = context.active().getValue(ROUTE_KEY);
261
- if (slot?.open === true)
262
- slot.route = template;
263
- }
264
- function spanName(method, route) {
265
- const name = methodName(method);
266
- return route === undefined ? name : `${name} ${route}`;
267
- }
268
- // Like Go's ServeMux, a route pattern can have a method and host before the path.
269
- function routeOnly(route) {
270
- if (route === undefined)
271
- return undefined;
272
- const pathStart = route.indexOf("/");
273
- return pathStart >= 0 ? route.slice(pathStart).trimEnd() : undefined;
274
- }
275
- /**
276
- * The percent-decoded path, as Go's URL.Path, which ignorePaths match against. A malformed escape
277
- * leaves the path as it is.
278
- */
279
- function decodedPath(path) {
280
- try {
281
- return decodeURIComponent(path);
282
- }
283
- catch {
284
- return path;
285
- }
286
- }
287
- function mediaType(contentType) {
288
- return contentType === null ? "" : (contentType.split(";")[0] ?? "").trim().toLowerCase();
289
- }
290
- function isHtml(contentType) {
291
- return mediaType(contentType) === "text/html";
292
- }
293
- /** The default watchBody: HTML pages, which stream as they render, and server-sent event streams. */
294
- function watchesByDefault(res) {
295
- const type = mediaType(res.headers.get("content-type"));
296
- return type === "text/html" || type === "text/event-stream";
297
- }
298
- /** The Server-Timing traceparent entry for span, or undefined when its span context is not valid. */
299
- function serverTiming(span) {
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;
304
- const flags = (sc.traceFlags & 0xff).toString(16).padStart(2, "0");
305
- return `traceparent;desc="00-${sc.traceId}-${sc.spanId}-${flags}"`;
306
- }
307
- // rebuild makes a new Response: upstream responses, such as fetch's, have immutable headers.
308
- function rebuild(res, body, headers) {
309
- return new Response(body, { status: res.status, statusText: res.statusText, headers });
310
- }
311
- /**
312
- * Adds the Server-Timing entry to a response whose body is passed on untouched. The headers are
313
- * changed in place, so Bun keeps the body's length and its sendfile path; a response with immutable
314
- * headers, such as fetch's, is rebuilt around the same body instead.
315
- */
316
- function withServerTiming(res, headers, timing) {
317
- try {
318
- headers.append("server-timing", timing);
319
- return res;
320
- }
321
- catch {
322
- const copy = new Headers(headers);
323
- copy.append("server-timing", timing);
324
- return rebuild(res, BODILESS_STATUSES.has(res.status) ? null : res.body, copy);
325
- }
326
- }
327
- /**
328
- * Passes body through and calls done when it finishes, errors (with the error) or is cancelled by
329
- * the consumer. The source is read only as the consumer pulls.
330
- */
331
- function watchBody(body, done) {
332
- const reader = body.getReader();
333
- return new ReadableStream({
334
- async pull(controller) {
335
- let chunk;
336
- try {
337
- chunk = await reader.read();
338
- }
339
- catch (err) {
340
- done({ error: err });
341
- controller.error(err);
342
- return;
343
- }
344
- if (chunk.done) {
345
- controller.close();
346
- done();
347
- return;
348
- }
349
- controller.enqueue(chunk.value);
350
- },
351
- cancel(reason) {
352
- // The source's cancel starts first, so nothing done does can keep it from running.
353
- const cancelled = reader.cancel(reason);
354
- done();
355
- return cancelled;
356
- },
357
- }, { highWaterMark: 0 });
358
- }
359
- // emitSummary emits o11y.request.summary with Go's attributes, in Go's order, after the record's.
360
- function emitSummary(telemetry, record, ctx, s) {
361
- const attrs = {
362
- "http.request.method": s.method,
363
- ...(s.original === undefined ? {} : { "http.request.method_original": s.original }),
364
- "http.response.status_code": s.status,
365
- [ATTR_OUTCOME]: s.failed ? OUTCOME_VALUE_FAILURE : OUTCOME_VALUE_SUCCESS,
366
- [ATTR_DURATION]: s.seconds,
367
- ...(s.route === undefined ? {} : { "http.route": s.route }),
368
- };
369
- try {
370
- record.emitEvent(telemetry, EVENT_REQUEST_SUMMARY, attrs, ctx);
371
- }
372
- catch {
373
- // The summary is best effort; it never fails the request.
374
- }
375
- }