@libo11y/server 0.0.0-stage → 0.1.2

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.
@@ -0,0 +1,85 @@
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 { type Telemetry } from "@libo11y/core";
14
+ /** Options for {@link instrumentServe}. */
15
+ export interface ServeOptions {
16
+ /** The telemetry whose providers and propagator to use. Without it, the globals setup installs. */
17
+ readonly telemetry?: Telemetry;
18
+ /**
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.
22
+ */
23
+ readonly route?: (req: Request) => string | undefined;
24
+ /**
25
+ * An internet-facing server: inbound trace context starts a new root span linked to it instead
26
+ * of becoming its parent, so untrusted callers cannot graft onto internal traces. Baggage is
27
+ * still extracted.
28
+ */
29
+ readonly publicEndpoint?: boolean;
30
+ /**
31
+ * URL paths to leave uninstrumented, as Go path.Match patterns ("/healthz", "/debug/*"). They
32
+ * match the percent-decoded path, as in Go, so "/café" matches a request for "/caf%C3%A9". A
33
+ * matching request gets no span, metric or summary. A malformed pattern never matches.
34
+ */
35
+ readonly ignorePaths?: readonly string[];
36
+ /**
37
+ * Adds `Server-Timing: traceparent;desc="00-<trace>-<span>-<flags>"` to text/html responses, so
38
+ * the page can join the server's trace. It works whether or not the body is watched (see
39
+ * watchBody); the headers of an unwatched response are changed in place when they are mutable.
40
+ */
41
+ readonly serverTiming?: boolean;
42
+ /**
43
+ * Emits one o11y.request.summary event per request, carrying the request's wide record (see
44
+ * currentRecord in the core package) and then the method, status, outcome, duration and route. It
45
+ * needs telemetry; without it this option is a silent no-op, as in Go.
46
+ */
47
+ readonly canonicalLine?: boolean;
48
+ /**
49
+ * Decides whether a response's body is watched, so that the span, the duration and the summary end
50
+ * when the body finishes, errors or is cancelled rather than when the handler returns. A watched
51
+ * body is passed through a stream wrapper, so a body of known length is sent chunked, without
52
+ * Content-Length, and Bun cannot send a Bun.file body with sendfile. An unwatched response is
53
+ * returned exactly as the handler made it, and its duration excludes the body's transfer.
54
+ *
55
+ * The default watches responses whose content type is text/html or text/event-stream, compared
56
+ * 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
+ */
60
+ readonly watchBody?: (res: Response) => boolean;
61
+ }
62
+ /**
63
+ * Wraps a fetch-style handler with server instrumentation. Extra handler arguments, such as
64
+ * Bun.serve's server, pass through. The handler runs inside the server span's context, so spans and
65
+ * logs it makes are children of it. A throw marks the span failed, records the exception and a 500,
66
+ * and is re-thrown. A watched body (see ServeOptions.watchBody: HTML and event streams by default)
67
+ * is passed through a wrapper that ends the span when the body finishes; that wrapper is a stream,
68
+ * so a body of known length is sent chunked. Any other response ends the span when the handler
69
+ * returns and is passed on untouched.
70
+ */
71
+ export declare function instrumentServe<A extends unknown[]>(handler: (req: Request, ...rest: A) => Response | Promise<Response>, opts?: ServeOptions): (req: Request, ...rest: A) => Promise<Response>;
72
+ /**
73
+ * Sets the route template of the server request being handled, such as "/projects/:id", for
74
+ * frameworks that route inside the handler, as TanStack Start does. It is the counterpart of Go
75
+ * reading r.Pattern after the ServeMux has run. When the request ends, the route set last names
76
+ * the span ("<METHOD> <route>", or the route verbatim when it starts with a method and a space)
77
+ * and is the http.route of the span, the duration metric and the summary, in place of the one
78
+ * ServeOptions.route resolved. The span starts under the name ServeOptions.route gives, so a
79
+ * sampler sees that one.
80
+ *
81
+ * It finds the request through the active context, which instrumentServe sets for the handler, so
82
+ * it needs a context manager (setup installs one). Outside a request, after it has ended, or with
83
+ * an empty route, it does nothing.
84
+ */
85
+ export declare function setRoute(route: string): void;
package/dist/serve.js ADDED
@@ -0,0 +1,321 @@
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, diag, isSpanContextValid, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
16
+ import { matchesAny } from "./glob.js";
17
+ import { asException, errorConstructorName, HEADERS_GETTER, instrumentResolver, methodName, normalizeMethod, 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
+ export function instrumentServe(handler, opts = {}) {
28
+ const instruments = instrumentResolver(opts.telemetry, "http.server.request.duration", "Duration of HTTP server requests.");
29
+ const ignore = opts.ignorePaths ?? [];
30
+ const watch = opts.watchBody ?? watchesByDefault;
31
+ const shouldWatch = (res) => {
32
+ try {
33
+ return watch(res);
34
+ }
35
+ catch (err) {
36
+ diag.warn(`libo11y: instrumentServe: watchBody threw, the body is not watched: ${errorMessage(err)}`);
37
+ return false;
38
+ }
39
+ };
40
+ const summaryTelemetry = opts.canonicalLine === true ? opts.telemetry : undefined;
41
+ return async (req, ...rest) => {
42
+ const url = new URL(req.url);
43
+ if (ignore.length > 0 && matchesAny(ignore, decodedPath(url.pathname)))
44
+ return handler(req, ...rest);
45
+ const start = performance.now();
46
+ const { tracer, histogram, propagator } = instruments();
47
+ const { method, original } = normalizeMethod(req.method);
48
+ let resolved;
49
+ try {
50
+ resolved = opts.route?.(req);
51
+ }
52
+ catch (err) {
53
+ diag.warn(`libo11y: instrumentServe: route threw, the request is unrouted: ${errorMessage(err)}`);
54
+ }
55
+ const route = resolved === "" ? undefined : resolved;
56
+ const startRoute = route === undefined ? undefined : routeOnly(route);
57
+ const scheme = schemeOf(url);
58
+ const extracted = propagator.extract(context.active(), req.headers, HEADERS_GETTER);
59
+ const attributes = {
60
+ "http.request.method": method,
61
+ ...(original === undefined ? {} : { "http.request.method_original": original }),
62
+ "url.scheme": scheme,
63
+ "url.path": url.pathname,
64
+ ...serverAttributes(url),
65
+ };
66
+ const userAgent = req.headers.get("user-agent");
67
+ if (userAgent !== null)
68
+ attributes["user_agent.original"] = userAgent;
69
+ if (startRoute !== undefined)
70
+ attributes["http.route"] = startRoute;
71
+ const spanOptions = { kind: SpanKind.SERVER, attributes };
72
+ if (opts.publicEndpoint === true) {
73
+ spanOptions.root = true;
74
+ const inbound = trace.getSpanContext(extracted);
75
+ if (inbound !== undefined && isSpanContextValid(inbound) && inbound.isRemote === true) {
76
+ spanOptions.links = [{ context: inbound }];
77
+ }
78
+ }
79
+ const span = tracer.startSpan(spanName(method, route), spanOptions, extracted);
80
+ const routeSlot = { open: true };
81
+ let handlerContext = trace.setSpan(extracted, span).setValue(ROUTE_KEY, routeSlot);
82
+ let record;
83
+ if (summaryTelemetry !== undefined) {
84
+ ({ context: handlerContext, record } = startRecord(handlerContext));
85
+ }
86
+ // The context the end is reported in, captured now: the body may finish where none is active.
87
+ const spanContext = handlerContext;
88
+ // end reports the outcome once; finish guards it, so a throw from a span processor or an
89
+ // instrument never fails the request, replaces the handler's error or stops a body's cancel.
90
+ const end = (outcome) => {
91
+ let httpRoute = startRoute;
92
+ if (routeSlot.route !== undefined) {
93
+ httpRoute = routeOnly(routeSlot.route);
94
+ span.updateName(spanName(method, routeSlot.route));
95
+ span.setAttribute("http.route", httpRoute);
96
+ }
97
+ const failure = outcome.failure;
98
+ const failed = failure !== undefined;
99
+ const errorType = failed
100
+ ? errorConstructorName(failure.error)
101
+ : outcome.status >= 500
102
+ ? String(outcome.status)
103
+ : undefined;
104
+ span.setAttribute("http.response.status_code", outcome.status);
105
+ if (errorType !== undefined)
106
+ span.setAttribute("error.type", errorType);
107
+ if (failed) {
108
+ span.recordException(asException(failure.error));
109
+ span.setStatus({ code: SpanStatusCode.ERROR, message: errorMessage(failure.error) });
110
+ }
111
+ else if (outcome.status >= 500) {
112
+ span.setStatus({ code: SpanStatusCode.ERROR });
113
+ }
114
+ const seconds = (performance.now() - start) / 1000;
115
+ histogram.record(seconds, {
116
+ "http.request.method": method,
117
+ "url.scheme": scheme,
118
+ ...(httpRoute === undefined ? {} : { "http.route": httpRoute }),
119
+ "http.response.status_code": outcome.status,
120
+ ...(errorType === undefined ? {} : { "error.type": errorType }),
121
+ }, trace.setSpan(ROOT_CONTEXT, span));
122
+ if (record !== undefined && summaryTelemetry !== undefined) {
123
+ emitSummary(summaryTelemetry, record, spanContext, {
124
+ method,
125
+ original,
126
+ status: outcome.status,
127
+ failed: failed || outcome.status >= 500,
128
+ seconds,
129
+ route: httpRoute,
130
+ });
131
+ }
132
+ span.end();
133
+ };
134
+ let finished = false;
135
+ const finish = (outcome) => {
136
+ if (finished)
137
+ return;
138
+ finished = true;
139
+ routeSlot.open = false;
140
+ try {
141
+ end(outcome);
142
+ }
143
+ catch (err) {
144
+ diag.error(`libo11y: instrumentServe: ending the request threw: ${errorMessage(err)}`);
145
+ }
146
+ };
147
+ let res;
148
+ try {
149
+ res = await context.with(handlerContext, () => handler(req, ...rest));
150
+ }
151
+ catch (err) {
152
+ finish({ status: 500, failure: { error: err } });
153
+ throw err;
154
+ }
155
+ if (res === undefined) {
156
+ // Bun.serve handlers return nothing after server.upgrade(req): the connection was taken over,
157
+ // which Go reports as 101.
158
+ finish({ status: 101 });
159
+ return res;
160
+ }
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);
176
+ }
177
+ let headers = resHeaders;
178
+ if (timing !== undefined) {
179
+ headers = new Headers(resHeaders);
180
+ headers.append("server-timing", timing);
181
+ }
182
+ const body = watchBody(res.body, (failure) => finish(failure === undefined ? { status } : { status, failure }));
183
+ return rebuild(res, body, headers);
184
+ };
185
+ }
186
+ // The statuses whose responses never carry a body: 101 has none, and the Fetch standard calls
187
+ // 204, 205 and 304 null body statuses.
188
+ const BODILESS_STATUSES = new Set([101, 204, 205, 304]);
189
+ const ROUTE_KEY = createContextKey("libo11y.server.route");
190
+ /**
191
+ * Sets the route template of the server request being handled, such as "/projects/:id", for
192
+ * frameworks that route inside the handler, as TanStack Start does. It is the counterpart of Go
193
+ * reading r.Pattern after the ServeMux has run. When the request ends, the route set last names
194
+ * the span ("<METHOD> <route>", or the route verbatim when it starts with a method and a space)
195
+ * and is the http.route of the span, the duration metric and the summary, in place of the one
196
+ * ServeOptions.route resolved. The span starts under the name ServeOptions.route gives, so a
197
+ * sampler sees that one.
198
+ *
199
+ * It finds the request through the active context, which instrumentServe sets for the handler, so
200
+ * it needs a context manager (setup installs one). Outside a request, after it has ended, or with
201
+ * an empty route, it does nothing.
202
+ */
203
+ export function setRoute(route) {
204
+ if (route === "")
205
+ return;
206
+ const slot = context.active().getValue(ROUTE_KEY);
207
+ if (slot?.open === true)
208
+ slot.route = route;
209
+ }
210
+ function spanName(method, route) {
211
+ if (route === undefined || route === "")
212
+ return methodName(method);
213
+ if (route.includes(" "))
214
+ return route;
215
+ return `${methodName(method)} ${route}`;
216
+ }
217
+ // routeOnly strips a leading method from a route template ("GET /users/:id" -> "/users/:id").
218
+ function routeOnly(route) {
219
+ const space = route.indexOf(" ");
220
+ return space < 0 ? route : route.slice(space + 1);
221
+ }
222
+ /**
223
+ * The percent-decoded path, as Go's URL.Path, which ignorePaths match against. A malformed escape
224
+ * leaves the path as it is.
225
+ */
226
+ function decodedPath(path) {
227
+ try {
228
+ return decodeURIComponent(path);
229
+ }
230
+ catch {
231
+ return path;
232
+ }
233
+ }
234
+ function mediaType(contentType) {
235
+ return contentType === null ? "" : (contentType.split(";")[0] ?? "").trim().toLowerCase();
236
+ }
237
+ function isHtml(contentType) {
238
+ return mediaType(contentType) === "text/html";
239
+ }
240
+ /** The default watchBody: HTML pages, which stream as they render, and server-sent event streams. */
241
+ function watchesByDefault(res) {
242
+ const type = mediaType(res.headers.get("content-type"));
243
+ return type === "text/html" || type === "text/event-stream";
244
+ }
245
+ function serverTiming(span) {
246
+ const sc = span.spanContext();
247
+ const flags = (sc.traceFlags & 0xff).toString(16).padStart(2, "0");
248
+ return `traceparent;desc="00-${sc.traceId}-${sc.spanId}-${flags}"`;
249
+ }
250
+ function errorMessage(err) {
251
+ return err instanceof Error ? err.message : String(err);
252
+ }
253
+ // rebuild makes a new Response: upstream responses, such as fetch's, have immutable headers.
254
+ function rebuild(res, body, headers) {
255
+ return new Response(body, { status: res.status, statusText: res.statusText, headers });
256
+ }
257
+ /**
258
+ * Adds the Server-Timing entry to a response whose body is passed on untouched. The headers are
259
+ * changed in place, so Bun keeps the body's length and its sendfile path; a response with immutable
260
+ * headers, such as fetch's, is rebuilt around the same body instead.
261
+ */
262
+ function withServerTiming(res, headers, timing) {
263
+ try {
264
+ headers.append("server-timing", timing);
265
+ return res;
266
+ }
267
+ catch {
268
+ const copy = new Headers(headers);
269
+ copy.append("server-timing", timing);
270
+ return rebuild(res, BODILESS_STATUSES.has(res.status) ? null : res.body, copy);
271
+ }
272
+ }
273
+ /**
274
+ * Passes body through and calls done when it finishes, errors (with the error) or is cancelled by
275
+ * the consumer. The source is read only as the consumer pulls.
276
+ */
277
+ function watchBody(body, done) {
278
+ const reader = body.getReader();
279
+ return new ReadableStream({
280
+ async pull(controller) {
281
+ let chunk;
282
+ try {
283
+ chunk = await reader.read();
284
+ }
285
+ catch (err) {
286
+ done({ error: err });
287
+ controller.error(err);
288
+ return;
289
+ }
290
+ if (chunk.done) {
291
+ controller.close();
292
+ done();
293
+ return;
294
+ }
295
+ controller.enqueue(chunk.value);
296
+ },
297
+ cancel(reason) {
298
+ // The source's cancel starts first, so nothing done does can keep it from running.
299
+ const cancelled = reader.cancel(reason);
300
+ done();
301
+ return cancelled;
302
+ },
303
+ }, { highWaterMark: 0 });
304
+ }
305
+ // emitSummary emits o11y.request.summary with Go's attributes, in Go's order, after the record's.
306
+ function emitSummary(telemetry, record, ctx, s) {
307
+ const attrs = {
308
+ "http.request.method": s.method,
309
+ ...(s.original === undefined ? {} : { "http.request.method_original": s.original }),
310
+ "http.response.status_code": s.status,
311
+ [ATTR_OUTCOME]: s.failed ? OUTCOME_VALUE_FAILURE : OUTCOME_VALUE_SUCCESS,
312
+ [ATTR_DURATION]: s.seconds,
313
+ ...(s.route === undefined ? {} : { "http.route": s.route }),
314
+ };
315
+ try {
316
+ record.emitEvent(telemetry, EVENT_REQUEST_SUMMARY, attrs, ctx);
317
+ }
318
+ catch {
319
+ // The summary is best effort; it never fails the request.
320
+ }
321
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * setup and createTelemetry bound to the server platform: Go's Setup and New for Bun and Node.
3
+ */
4
+ import { type Telemetry, type TelemetryOptions } from "@libo11y/core";
5
+ /**
6
+ * Builds telemetry on the server platform, emits the o11y.telemetry.configured canary and installs
7
+ * it globally: the AsyncLocalStorage context manager, the tracer, meter and logger providers, the
8
+ * propagator and the error handler (Go Setup). A second call fails with ALREADY_SETUP until the
9
+ * first telemetry shuts down.
10
+ */
11
+ export declare function setup(options?: TelemetryOptions): Promise<Telemetry>;
12
+ /** Builds telemetry on the server platform without touching any global or emitting the canary (Go New). */
13
+ export declare function createTelemetry(options?: TelemetryOptions): Promise<Telemetry>;
package/dist/setup.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * setup and createTelemetry bound to the server platform: Go's Setup and New for Bun and Node.
3
+ */
4
+ import { createTelemetryWith, setupWith } from "@libo11y/core";
5
+ import { serverPlatform } from "./platform.js";
6
+ /**
7
+ * Builds telemetry on the server platform, emits the o11y.telemetry.configured canary and installs
8
+ * it globally: the AsyncLocalStorage context manager, the tracer, meter and logger providers, the
9
+ * propagator and the error handler (Go Setup). A second call fails with ALREADY_SETUP until the
10
+ * first telemetry shuts down.
11
+ */
12
+ export function setup(options = {}) {
13
+ return setupWith(options, serverPlatform());
14
+ }
15
+ /** Builds telemetry on the server platform without touching any global or emitting the canary (Go New). */
16
+ export function createTelemetry(options = {}) {
17
+ return createTelemetryWith(options, serverPlatform());
18
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Shutting down on a termination signal (Go ShutdownOnSignals). One listener per signal is
3
+ * registered with once; the first signal removes the others, so a second signal gets the runtime's
4
+ * default handling and ends the process. The process is never exited here.
5
+ */
6
+ import type { SignalReport, Telemetry } from "@libo11y/core";
7
+ /** Where signals come from: process, or a test's emitter. */
8
+ export interface SignalSource {
9
+ once(signal: string, listener: () => void): unknown;
10
+ removeListener(signal: string, listener: () => void): unknown;
11
+ }
12
+ /** Options for shutdownOnSignals. */
13
+ export interface ShutdownOnSignalsOptions {
14
+ /** The signal names to wait for. Default ["SIGINT", "SIGTERM"]. */
15
+ readonly signals?: readonly string[];
16
+ /** The shutdown deadline, which also bounds beforeShutdown. Default: shutdown's own, 5000 ms. */
17
+ readonly timeoutMillis?: number;
18
+ /**
19
+ * Runs after the signal and before the telemetry shuts down, to stop what still makes telemetry:
20
+ * 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.
24
+ */
25
+ readonly beforeShutdown?: () => Promise<void> | void;
26
+ }
27
+ /** shutdownOnSignals with the signals taken from source. */
28
+ export declare function shutdownOnSignalsWith(source: SignalSource, telemetry: Telemetry, opts?: ShutdownOnSignalsOptions): Promise<SignalReport>;
29
+ /**
30
+ * Resolves with the shutdown report once the process receives one of opts.signals (default SIGINT
31
+ * and SIGTERM). Until then each of those signals has a listener, which replaces the runtime's
32
+ * default handling; after the first, they are all removed, so a second signal ends the process.
33
+ * opts.beforeShutdown, when given, runs first, so the server can stop before its telemetry does.
34
+ */
35
+ export declare function shutdownOnSignals(telemetry: Telemetry, opts?: ShutdownOnSignalsOptions): Promise<SignalReport>;
@@ -0,0 +1,58 @@
1
+ const DEFAULT_SIGNALS = ["SIGINT", "SIGTERM"];
2
+ const DEFAULT_TIMEOUT_MILLIS = 5000;
3
+ /** The longest delay a timer takes: setTimeout treats anything larger as 1 ms. */
4
+ const MAX_TIMEOUT_MILLIS = 2 ** 31 - 1;
5
+ /** shutdownOnSignals with the signals taken from source. */
6
+ export function shutdownOnSignalsWith(source, telemetry, opts = {}) {
7
+ const signals = opts.signals ?? DEFAULT_SIGNALS;
8
+ return new Promise((resolve) => {
9
+ const listeners = new Map();
10
+ for (const signal of signals) {
11
+ const listener = () => {
12
+ for (const [other, l] of listeners)
13
+ if (other !== signal)
14
+ source.removeListener(other, l);
15
+ resolve();
16
+ };
17
+ listeners.set(signal, listener);
18
+ source.once(signal, listener);
19
+ }
20
+ }).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 });
25
+ if (before === undefined)
26
+ return report;
27
+ return { ok: false, errors: [{ signal: "lifecycle", error: before.error }, ...report.errors] };
28
+ });
29
+ }
30
+ /** Runs fn within ms, and returns what went wrong, if anything. */
31
+ async function runBefore(fn, ms) {
32
+ let timer;
33
+ 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));
35
+ });
36
+ const ran = Promise.resolve()
37
+ .then(fn)
38
+ .then(() => undefined, (err) => ({
39
+ error: new Error(`o11y: beforeShutdown: ${err instanceof Error ? err.message : String(err)}`, {
40
+ cause: err,
41
+ }),
42
+ }));
43
+ try {
44
+ return await Promise.race([ran, expired]);
45
+ }
46
+ finally {
47
+ clearTimeout(timer);
48
+ }
49
+ }
50
+ /**
51
+ * Resolves with the shutdown report once the process receives one of opts.signals (default SIGINT
52
+ * and SIGTERM). Until then each of those signals has a listener, which replaces the runtime's
53
+ * default handling; after the first, they are all removed, so a second signal ends the process.
54
+ * opts.beforeShutdown, when given, runs first, so the server can stop before its telemetry does.
55
+ */
56
+ export function shutdownOnSignals(telemetry, opts) {
57
+ return shutdownOnSignalsWith(process, telemetry, opts);
58
+ }
@@ -0,0 +1,2 @@
1
+ /** The @libo11y/server package version. scripts/release.ts keeps it equal to package.json. */
2
+ export declare const VERSION = "0.1.2";
@@ -0,0 +1,2 @@
1
+ /** The @libo11y/server package version. scripts/release.ts keeps it equal to package.json. */
2
+ export const VERSION = "0.1.2";
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@libo11y/server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
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
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/jamesainslie/libo11y.git",
17
+ "directory": "ts/packages/server"
18
+ },
19
+ "dependencies": {
20
+ "@libo11y/core": "0.1.2",
21
+ "@libo11y/spec": "0.1.2",
22
+ "@opentelemetry/api": "1.10.0",
23
+ "@opentelemetry/context-async-hooks": "3.1.1",
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
+ "@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
+ "@opentelemetry/instrumentation": "0.301.1",
31
+ "@opentelemetry/instrumentation-runtime-node": "0.38.0",
32
+ "@opentelemetry/otlp-exporter-base": "0.301.1",
33
+ "@opentelemetry/otlp-transformer": "0.301.1",
34
+ "@opentelemetry/resource-detector-container": "0.9.1",
35
+ "@opentelemetry/resources": "3.1.1",
36
+ "@opentelemetry/sdk-logs": "3.1.1",
37
+ "@opentelemetry/sdk-metrics": "3.1.1",
38
+ "@opentelemetry/sdk-trace": "3.1.1"
39
+ },
40
+ "devDependencies": {
41
+ "@libo11y/test": "0.1.2"
42
+ },
43
+ "files": [
44
+ "dist",
45
+ "README.md",
46
+ "LICENSE"
47
+ ],
48
+ "publishConfig": {
49
+ "access": "public",
50
+ "provenance": true
51
+ }
52
+ }