@libo11y/server 0.8.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/edge.d.ts CHANGED
@@ -1,10 +1,6 @@
1
1
  /**
2
- * @libo11y/server/edge: the parts of the server package that import no Node builtin and read no
3
- * process global, for edge runtimes that have fetch but not Node's modules, such as Cloudflare
4
- * Workers (@libo11y/workers). It holds instrumentServe, instrumentFetch, setRoute and the
5
- * OTLP/protobuf metrics serializer that writes exemplars, with the same API and compatibility
6
- * promise as the package root. edge.test.ts enforces the boundary.
2
+ * @libo11y/server/edge: compatibility re-export of @libo11y/core/edge's HTTP and protobuf metrics
3
+ * surface (instrumentServe, instrumentFetch, setRoute, OtlpProtobufMetricsSerializer), keeping the
4
+ * same API and compatibility promise as 0.7.0 and 0.8.0.
7
5
  */
8
- export { type FetchOptions, instrumentFetch } from "./fetch.ts";
9
- export { OtlpProtobufMetricsSerializer } from "./otlp-proto-metrics.ts";
10
- export { instrumentServe, type ServeOptions, setRoute } from "./serve.ts";
6
+ export { type FetchOptions, instrumentFetch, instrumentServe, OtlpProtobufMetricsSerializer, type ServeOptions, setRoute, } from "@libo11y/core/edge";
package/dist/edge.js CHANGED
@@ -1,10 +1,6 @@
1
1
  /**
2
- * @libo11y/server/edge: the parts of the server package that import no Node builtin and read no
3
- * process global, for edge runtimes that have fetch but not Node's modules, such as Cloudflare
4
- * Workers (@libo11y/workers). It holds instrumentServe, instrumentFetch, setRoute and the
5
- * OTLP/protobuf metrics serializer that writes exemplars, with the same API and compatibility
6
- * promise as the package root. edge.test.ts enforces the boundary.
2
+ * @libo11y/server/edge: compatibility re-export of @libo11y/core/edge's HTTP and protobuf metrics
3
+ * surface (instrumentServe, instrumentFetch, setRoute, OtlpProtobufMetricsSerializer), keeping the
4
+ * same API and compatibility promise as 0.7.0 and 0.8.0.
7
5
  */
8
- export { instrumentFetch } from "./fetch.js";
9
- export { OtlpProtobufMetricsSerializer } from "./otlp-proto-metrics.js";
10
- export { instrumentServe, setRoute } from "./serve.js";
6
+ export { instrumentFetch, instrumentServe, OtlpProtobufMetricsSerializer, setRoute, } from "@libo11y/core/edge";
@@ -1,18 +1,3 @@
1
- /**
2
- * The exporters for each signal core routes to otlp or console.
3
- *
4
- * An OTLP exporter is upstream's in everything but the transport. It is upstream's OTLPExporterBase
5
- * (OTLPMetricExporterBase for metrics) over upstream's export delegate, configured as upstream's own
6
- * exporter classes configure it: convertLegacyHttpOptions with no options, so upstream reads its
7
- * OTEL_EXPORTER_OTLP_* variables (endpoint, headers, timeout, compression, certificates), and
8
- * upstream's serializers and exporter metrics. The transport is libo11y's (otlp-transport.ts),
9
- * because upstream's cannot be stopped: shutdown() ends what is still in flight, so an exporter
10
- * never keeps an exiting process alive.
11
- *
12
- * The metric exporter takes libo11y's serializers, which write exemplars: protobuf from this
13
- * package, JSON from core. Both metric routes wrap the exporter with exemplarMetricExporter, so
14
- * each collection carries the exemplar store's samples.
15
- */
16
1
  import { type ExporterRequest, type ExporterSet } from "@libo11y/core";
17
2
  /** Builds the exporters for every signal the configuration routes to "otlp" or "console". */
18
3
  export declare function buildExporters(req: ExporterRequest): ExporterSet;
package/dist/exporters.js CHANGED
@@ -1,34 +1,50 @@
1
1
  /**
2
2
  * The exporters for each signal core routes to otlp or console.
3
3
  *
4
- * An OTLP exporter is upstream's in everything but the transport. It is upstream's OTLPExporterBase
5
- * (OTLPMetricExporterBase for metrics) over upstream's export delegate, configured as upstream's own
6
- * exporter classes configure it: convertLegacyHttpOptions with no options, so upstream reads its
7
- * OTEL_EXPORTER_OTLP_* variables (endpoint, headers, timeout, compression, certificates), and
8
- * upstream's serializers and exporter metrics. The transport is libo11y's (otlp-transport.ts),
9
- * because upstream's cannot be stopped: shutdown() ends what is still in flight, so an exporter
10
- * never keeps an exiting process alive.
4
+ * An OTLP exporter is upstream's OTLPExporterBase (OTLPMetricExporterBase for metrics) over
5
+ * upstream's export delegate, configured by @libo11y/core/internal's resolveOtlpSignalConfig as the
6
+ * sole owner of url, headers, compression, timeoutMillis, protocol, and temporalityPreference.
7
+ * Upstream's httpAgentFactoryFromOptions supplies the lazy Node TLS/mTLS agentFactory from
8
+ * OTEL_EXPORTER_OTLP_*_CERTIFICATE / CLIENT_* without re-reading or re-warning on other OTLP env
9
+ * variables. The transport is libo11y's (otlp-transport.ts), because upstream's cannot be stopped:
10
+ * shutdown() ends what is still in flight, so an exporter never keeps an exiting process alive.
11
11
  *
12
- * The metric exporter takes libo11y's serializers, which write exemplars: protobuf from this
13
- * package, JSON from core. Both metric routes wrap the exporter with exemplarMetricExporter, so
14
- * each collection carries the exemplar store's samples.
12
+ * The metric exporter takes libo11y's serializers, which write exemplars: protobuf from core/edge,
13
+ * JSON from core. Both metric routes wrap the exporter with exemplarMetricExporter, so each
14
+ * collection carries the exemplar store's samples.
15
15
  */
16
+ import { readFileSync } from "node:fs";
17
+ import { resolve } from "node:path";
16
18
  import { exemplarMetricExporter, O11yError, OtlpJsonMetricsSerializer, } from "@libo11y/core";
17
- import { OTLPMetricExporterBase } from "@opentelemetry/exporter-metrics-otlp-http";
19
+ import { OtlpProtobufMetricsSerializer } from "@libo11y/core/edge";
20
+ import { joinOtlpSignalPath, resolveOtlpSignalConfig, } from "@libo11y/core/internal";
21
+ import { diag } from "@opentelemetry/api";
22
+ import { AggregationTemporalityPreference, OTLPMetricExporterBase, } from "@opentelemetry/exporter-metrics-otlp-http";
18
23
  import { createOtlpNetworkExportDelegate, OTLPExporterBase, } from "@opentelemetry/otlp-exporter-base";
19
- import { convertLegacyHttpOptions, createOtlpHttpExporterMetrics, } from "@opentelemetry/otlp-exporter-base/node-http";
24
+ import { createOtlpHttpExporterMetrics, httpAgentFactoryFromOptions, } from "@opentelemetry/otlp-exporter-base/node-http";
20
25
  import { JsonLogsSerializer, JsonTraceSerializer, LogsExporterMetricsHelper, MetricsExporterMetricsHelper, ProtobufLogsSerializer, ProtobufTraceSerializer, TraceExporterMetricsHelper, } from "@opentelemetry/otlp-transformer";
21
26
  import { ConsoleLogRecordExporter, } from "@opentelemetry/sdk-logs";
22
27
  import { ConsoleMetricExporter, PeriodicExportingMetricReader, } from "@opentelemetry/sdk-metrics";
23
28
  import { ConsoleSpanExporter } from "@opentelemetry/sdk-trace";
24
- import { OtlpProtobufMetricsSerializer } from "./otlp-proto-metrics.js";
25
- import { createHttpTransport } from "./otlp-transport.js";
29
+ import { createHttpTransport, } from "./otlp-transport.js";
26
30
  /** The otel.component.type upstream's OTLP HTTP exporters report. */
27
31
  const SPAN_EXPORTER_COMPONENT = "otlp_http_span_exporter";
28
32
  const METRIC_EXPORTER_COMPONENT = "otlp_http_metric_exporter";
29
33
  const LOG_EXPORTER_COMPONENT = "otlp_http_log_exporter";
30
34
  const PROTOBUF = "application/x-protobuf";
31
35
  const JSON_TYPE = "application/json";
36
+ const DEFAULT_SERVER_ENDPOINT = "http://localhost:4318";
37
+ const DEFAULT_CONCURRENCY_LIMIT = 30;
38
+ const SERVER_PROFILE = {
39
+ envKeys: "full",
40
+ urlMode: "standard",
41
+ timeoutParseMode: "upstream-number",
42
+ headerParseMode: "upstream-baggage",
43
+ compressionParseMode: "case-sensitive",
44
+ defaultEndpoint: DEFAULT_SERVER_ENDPOINT,
45
+ defaultCompression: "none",
46
+ defaultProtocol: "http/protobuf",
47
+ };
32
48
  // build runs a constructor and reports a failure as Go's "o11y: building <kind>: %w".
33
49
  function build(kind, fn) {
34
50
  try {
@@ -40,16 +56,65 @@ function build(kind, fn) {
40
56
  });
41
57
  }
42
58
  }
59
+ function toAggregationTemporalityPreference(pref) {
60
+ switch (pref) {
61
+ case "delta":
62
+ return AggregationTemporalityPreference.DELTA;
63
+ case "lowmemory":
64
+ return AggregationTemporalityPreference.LOWMEMORY;
65
+ default:
66
+ return AggregationTemporalityPreference.CUMULATIVE;
67
+ }
68
+ }
69
+ function readTlsFile(signalVar, sharedVar, warning) {
70
+ const raw = process.env[signalVar]?.trim() || process.env[sharedVar]?.trim();
71
+ if (!raw)
72
+ return undefined;
73
+ try {
74
+ return readFileSync(resolve(process.cwd(), raw));
75
+ }
76
+ catch {
77
+ diag.warn(warning);
78
+ return undefined;
79
+ }
80
+ }
81
+ function tlsAgentFactory(signal) {
82
+ const upper = signal.toUpperCase();
83
+ const ca = readTlsFile(`OTEL_EXPORTER_OTLP_${upper}_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CERTIFICATE", "Failed to read root certificate file");
84
+ const cert = readTlsFile(`OTEL_EXPORTER_OTLP_${upper}_CLIENT_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE", "Failed to read client certificate chain file");
85
+ const key = readTlsFile(`OTEL_EXPORTER_OTLP_${upper}_CLIENT_KEY`, "OTEL_EXPORTER_OTLP_CLIENT_KEY", "Failed to read client certificate private key file");
86
+ return httpAgentFactoryFromOptions({
87
+ keepAlive: true,
88
+ ...(ca === undefined ? {} : { ca }),
89
+ ...(cert === undefined ? {} : { cert }),
90
+ ...(key === undefined ? {} : { key }),
91
+ });
92
+ }
43
93
  /**
44
- * Builds the export delegate for a signal as upstream's exporter classes do: the options from
45
- * convertLegacyHttpOptions, so the shared and the signal's own OTEL_EXPORTER_OTLP_* variables apply,
46
- * upstream's bounded export queue and exporter metrics, and libo11y's transport.
94
+ * Builds the export delegate for a signal: resolveOtlpSignalConfig owns url, headers, compression,
95
+ * timeoutMillis, protocol, and temporalityPreference; upstream's httpAgentFactoryFromOptions
96
+ * supplies the Node TLS/mTLS agentFactory.
47
97
  */
48
- function otlpExport(signal, path, contentType, serializer, component, metricsHelper) {
49
- const options = convertLegacyHttpOptions({}, signal, path, { "Content-Type": contentType });
50
- const transport = createHttpTransport(options);
51
- const delegate = createOtlpNetworkExportDelegate(options, serializer, createOtlpHttpExporterMetrics(component, metricsHelper, options.url, undefined), transport);
52
- return { delegate, transport };
98
+ function otlpExport(signal, serializers, component, metricsHelper) {
99
+ const resolved = resolveOtlpSignalConfig(signal, {}, process.env, SERVER_PROFILE);
100
+ const url = resolved.url ?? joinOtlpSignalPath(DEFAULT_SERVER_ENDPOINT, signal);
101
+ const json = resolved.protocol === "http/json";
102
+ const contentType = json ? JSON_TYPE : PROTOBUF;
103
+ const serializer = json ? serializers.json : serializers.protobuf;
104
+ const headers = { ...resolved.headers, "Content-Type": contentType };
105
+ const transportParams = {
106
+ url,
107
+ headers: async () => ({ ...headers }),
108
+ compression: resolved.compression,
109
+ agentFactory: tlsAgentFactory(signal),
110
+ };
111
+ const transport = createHttpTransport(transportParams);
112
+ const delegate = createOtlpNetworkExportDelegate({
113
+ timeoutMillis: resolved.timeoutMillis,
114
+ concurrencyLimit: DEFAULT_CONCURRENCY_LIMIT,
115
+ compression: resolved.compression,
116
+ }, serializer, createOtlpHttpExporterMetrics(component, metricsHelper, url, undefined), transport);
117
+ return { delegate, transport, temporalityPreference: resolved.temporalityPreference };
53
118
  }
54
119
  // stop ends an exporter. Upstream's shutdown waits for the exports in flight, which is what keeps
55
120
  // an exiting process alive when the collector does not answer. This one ends them first: whoever
@@ -70,52 +135,51 @@ class OtlpExporter extends OTLPExporterBase {
70
135
  }
71
136
  }
72
137
  /**
73
- * Upstream's OTLP metric exporter base, which takes the temporality preference from
74
- * OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE, over a transport that shutdown() stops.
138
+ * Upstream's OTLP metric exporter base, configured with the resolved temporality preference, over
139
+ * a transport that shutdown() stops.
75
140
  */
76
141
  class OtlpMetricExporter extends OTLPMetricExporterBase {
77
142
  transport;
78
143
  constructor(otlp) {
79
- super(otlp.delegate);
144
+ super(otlp.delegate, {
145
+ temporalityPreference: toAggregationTemporalityPreference(otlp.temporalityPreference),
146
+ });
80
147
  this.transport = otlp.transport;
81
148
  }
82
149
  shutdown() {
83
150
  return stop(this.transport, () => super.shutdown());
84
151
  }
85
152
  }
86
- /** The OTLP metric exporter for protocol, with libo11y's serializer, which writes exemplars. */
87
- function otlpMetricExporter(protocol) {
88
- const protobuf = protocol === "http/protobuf";
89
- return new OtlpMetricExporter(otlpExport("METRICS", "v1/metrics", protobuf ? PROTOBUF : JSON_TYPE, protobuf ? OtlpProtobufMetricsSerializer : OtlpJsonMetricsSerializer, METRIC_EXPORTER_COMPONENT, MetricsExporterMetricsHelper));
153
+ /** The OTLP metric exporter, selecting protobuf or JSON from resolved.protocol, with exemplars. */
154
+ function otlpMetricExporter() {
155
+ return new OtlpMetricExporter(otlpExport("metrics", { json: OtlpJsonMetricsSerializer, protobuf: OtlpProtobufMetricsSerializer }, METRIC_EXPORTER_COMPONENT, MetricsExporterMetricsHelper));
90
156
  }
91
157
  function spanExporter(req) {
92
- const { traces, protocol } = req.config;
158
+ const { traces } = req.config;
93
159
  if (traces === "console")
94
160
  return new ConsoleSpanExporter();
95
161
  if (traces !== "otlp")
96
162
  return undefined;
97
163
  return build("span exporter", () => {
98
- const json = protocol.traces === "http/json";
99
- return new OtlpExporter(otlpExport("TRACES", "v1/traces", json ? JSON_TYPE : PROTOBUF, json ? JsonTraceSerializer : ProtobufTraceSerializer, SPAN_EXPORTER_COMPONENT, TraceExporterMetricsHelper));
164
+ return new OtlpExporter(otlpExport("traces", { json: JsonTraceSerializer, protobuf: ProtobufTraceSerializer }, SPAN_EXPORTER_COMPONENT, TraceExporterMetricsHelper));
100
165
  });
101
166
  }
102
167
  function logExporter(req) {
103
- const { logs, protocol } = req.config;
168
+ const { logs } = req.config;
104
169
  if (logs === "console")
105
170
  return new ConsoleLogRecordExporter();
106
171
  if (logs !== "otlp")
107
172
  return undefined;
108
173
  return build("log exporter", () => {
109
- const json = protocol.logs === "http/json";
110
- return new OtlpExporter(otlpExport("LOGS", "v1/logs", json ? JSON_TYPE : PROTOBUF, json ? JsonLogsSerializer : ProtobufLogsSerializer, LOG_EXPORTER_COMPONENT, LogsExporterMetricsHelper));
174
+ return new OtlpExporter(otlpExport("logs", { json: JsonLogsSerializer, protobuf: ProtobufLogsSerializer }, LOG_EXPORTER_COMPONENT, LogsExporterMetricsHelper));
111
175
  });
112
176
  }
113
177
  function metricReader(req) {
114
- const { metrics, protocol, metricExport } = req.config;
178
+ const { metrics, metricExport } = req.config;
115
179
  if (metrics !== "otlp" && metrics !== "console")
116
180
  return undefined;
117
181
  return build("metric reader", () => {
118
- const inner = metrics === "console" ? new ConsoleMetricExporter() : otlpMetricExporter(protocol.metrics);
182
+ const inner = metrics === "console" ? new ConsoleMetricExporter() : otlpMetricExporter();
119
183
  // PeriodicExportingMetricReader refuses a timeout above the interval; sdk-node clamps it.
120
184
  const exportIntervalMillis = metricExport.intervalMillis;
121
185
  const exportTimeoutMillis = Math.min(metricExport.timeoutMillis, exportIntervalMillis);
package/dist/index.d.ts CHANGED
@@ -4,11 +4,9 @@
4
4
  * runtime metrics, and HTTP server and client instrumentation.
5
5
  */
6
6
  export { type LifecycleOptions, type Logger, O11yError, type O11yErrorCode, type SignalReport, type Telemetry, type TelemetryOptions, } from "@libo11y/core";
7
+ export { type FetchOptions, instrumentFetch, instrumentServe, OtlpProtobufMetricsSerializer, type ServeOptions, setRoute, } from "@libo11y/core/edge";
7
8
  export { createContextManager } from "./context.ts";
8
- export { type FetchOptions, instrumentFetch } from "./fetch.ts";
9
- export { OtlpProtobufMetricsSerializer } from "./otlp-proto-metrics.ts";
10
9
  export { serverPlatform } from "./platform.ts";
11
10
  export { loadAppRegistry } from "./registry.ts";
12
- export { instrumentServe, type ServeOptions, setRoute } from "./serve.ts";
13
11
  export { createTelemetry, setup } from "./setup.ts";
14
12
  export { type ShutdownOnSignalsOptions, shutdownOnSignals } from "./signals.ts";
package/dist/index.js CHANGED
@@ -4,11 +4,9 @@
4
4
  * runtime metrics, and HTTP server and client instrumentation.
5
5
  */
6
6
  export { O11yError, } from "@libo11y/core";
7
+ export { instrumentFetch, instrumentServe, OtlpProtobufMetricsSerializer, setRoute, } from "@libo11y/core/edge";
7
8
  export { createContextManager } from "./context.js";
8
- export { instrumentFetch } from "./fetch.js";
9
- export { OtlpProtobufMetricsSerializer } from "./otlp-proto-metrics.js";
10
9
  export { serverPlatform } from "./platform.js";
11
10
  export { loadAppRegistry } from "./registry.js";
12
- export { instrumentServe, setRoute } from "./serve.js";
13
11
  export { createTelemetry, setup } from "./setup.js";
14
12
  export { shutdownOnSignals } from "./signals.js";
@@ -37,13 +37,14 @@
37
37
  * follows change, so an upgrade is checked against them again.
38
38
  */
39
39
  import type { Agent } from "node:http";
40
+ import { MAX_TIMER_MILLIS, type RetryTimers } from "@libo11y/core/internal";
40
41
  import { type IExporterTransport } from "@opentelemetry/otlp-exporter-base";
41
42
  /** The version of @opentelemetry/otlp-exporter-base this transport follows, for the User-Agent. */
42
43
  export declare const OTLP_EXPORTER_VERSION = "0.301.1";
43
44
  /** The largest response body read. A larger one fails the export, whatever its status. */
44
45
  export declare const MAX_RESPONSE_BODY_SIZE: number;
45
46
  /** The longest delay a timer takes. Node and Bun treat anything larger as 1 ms. */
46
- export declare const MAX_TIMER_MILLIS: number;
47
+ export { MAX_TIMER_MILLIS };
47
48
  /**
48
49
  * What the transport takes from an exporter's configuration, as upstream's convertLegacyHttpOptions
49
50
  * gives it. The configuration's other two members, timeoutMillis and concurrencyLimit, go to
@@ -63,13 +64,7 @@ export interface HttpTransportParameters {
63
64
  * The clock, the timers and the random numbers the transport uses. A test replaces them to decide
64
65
  * when time passes and how much jitter a retry gets.
65
66
  */
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
- }
67
+ export type TransportTimers = RetryTimers;
73
68
  /** A transport whose work in flight can be ended. */
74
69
  export interface AbortableTransport extends IExporterTransport {
75
70
  /**
@@ -1,19 +1,24 @@
1
1
  import { gzip } from "node:zlib";
2
+ import { clampTimerMillis, classifyHttpStatus, MAX_PARTIAL_SUCCESS_BODY_BYTES, MAX_TIMER_MILLIS, parseRetryAfter, retryOtlpSend, } from "@libo11y/core/internal";
2
3
  import { diag } from "@opentelemetry/api";
3
4
  import { OTLPExporterError, } from "@opentelemetry/otlp-exporter-base";
4
5
  /** The version of @opentelemetry/otlp-exporter-base this transport follows, for the User-Agent. */
5
6
  export const OTLP_EXPORTER_VERSION = "0.301.1";
6
7
  const DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${OTLP_EXPORTER_VERSION}`;
7
8
  /** 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
+ export const MAX_RESPONSE_BODY_SIZE = MAX_PARTIAL_SUCCESS_BODY_BYTES;
9
10
  /** 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
+ export { MAX_TIMER_MILLIS };
11
12
  const MAX_ATTEMPTS = 5;
12
13
  const INITIAL_BACKOFF = 1000;
13
14
  const MAX_BACKOFF = 5000;
14
15
  const BACKOFF_MULTIPLIER = 1.5;
15
16
  const JITTER = 0.2;
16
- const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
17
+ const SERVER_STATUS_POLICY = {
18
+ retryableStatuses: [429, 502, 503, 504],
19
+ retryAfterStatuses: "all-retryable",
20
+ retryAfterMode: "upstream-lenient",
21
+ };
17
22
  const RETRYABLE_NETWORK_ERRORS = new Set([
18
23
  "ECONNRESET",
19
24
  "ECONNREFUSED",
@@ -30,8 +35,11 @@ const REAL_TIMERS = {
30
35
  setTimeout: (fn, ms) => setTimeout(fn, ms),
31
36
  clearTimeout: (handle) => clearTimeout(handle),
32
37
  };
33
- function aborted() {
34
- return { status: "failure", error: new Error("the export was aborted at shutdown") };
38
+ function abortedError() {
39
+ return new Error("the export was aborted at shutdown");
40
+ }
41
+ function abortedAttempt() {
42
+ return { status: "failure", error: abortedError() };
35
43
  }
36
44
  function asError(err) {
37
45
  return err instanceof Error ? err : new Error(String(err));
@@ -46,75 +54,76 @@ function retryableNetworkError(error) {
46
54
  * mean at once.
47
55
  */
48
56
  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;
57
+ return parseRetryAfter(header, now, "upstream-lenient");
58
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;
59
+ function toExportResponse(result) {
60
+ if (result.status === "success") {
61
+ return result.value === undefined ? { status: "success" } : { status: "success", data: result.value };
62
+ }
63
+ if (result.status === "retryable") {
64
+ return {
65
+ status: "retryable",
66
+ ...(result.retryInMillis === undefined ? {} : { retryInMillis: result.retryInMillis }),
67
+ ...(result.error === undefined ? {} : { error: result.error }),
68
+ };
69
+ }
70
+ return { status: "failure", error: result.error };
62
71
  }
63
72
  class HttpTransport {
64
73
  params;
65
74
  timers;
66
75
  url;
67
76
  io;
68
- stopped = false;
77
+ abortController = new AbortController();
69
78
  /** Ends each attempt in flight with the response given. */
70
79
  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
80
  constructor(params, timers) {
74
81
  this.params = params;
75
82
  this.timers = timers;
76
83
  this.url = new URL(params.url);
77
84
  }
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.
85
+ // send delegates retry scheduling, backoff, timer clamping, and abortable waits to core's shared
86
+ // retryOtlpSend using the server compatibility profile (5 retries, pre-wait remaining timeout,
87
+ // equal jitter 1s..5s +/-20%, upstream Retry-After override, and upstream diag messages).
81
88
  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;
89
+ const result = await retryOtlpSend((remainingMillis) => this.attempt(data, remainingMillis), {
90
+ maxRetries: MAX_ATTEMPTS,
91
+ initialBackoffMillis: INITIAL_BACKOFF,
92
+ maxBackoffMillis: MAX_BACKOFF,
93
+ backoffMultiplier: BACKOFF_MULTIPLIER,
94
+ jitterMode: "equal-jitter",
95
+ jitterRatio: JITTER,
96
+ retryAfterMode: "override",
97
+ timeoutMode: "pre-wait-remaining",
98
+ timeoutMillis,
99
+ timers: this.timers,
100
+ abortedError,
101
+ onRetryExceedsDeadline: ({ retryInMillis, remainingMillis }) => {
102
+ diag.info(`Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(remainingMillis)}ms, not retrying further.`);
103
+ },
104
+ onRetryScheduled: ({ retryInMillis }) => {
105
+ diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`);
106
+ },
107
+ onFinished: ({ result: finalResult, retriesUsed, maxRetries }) => {
108
+ if (finalResult.status === "success") {
109
+ diag.verbose(`Export succeeded after ${retriesUsed} retry attempts.`);
110
+ }
111
+ else if (finalResult.status === "retryable") {
112
+ diag.info(`Export failed after maximum retry attempts (${maxRetries}).`);
113
+ }
114
+ else {
115
+ diag.info(`Export failed with non-retryable error: ${finalResult.error}`);
116
+ }
117
+ },
118
+ }, this.abortController.signal);
119
+ return toExportResponse(result);
111
120
  }
112
121
  abort() {
113
- this.stopped = true;
122
+ if (!this.abortController.signal.aborted) {
123
+ this.abortController.abort();
124
+ }
114
125
  for (const end of [...this.inFlight])
115
- end(aborted());
116
- for (const wake of [...this.waiting])
117
- wake(false);
126
+ end(abortedAttempt());
118
127
  }
119
128
  shutdown() {
120
129
  this.abort();
@@ -123,7 +132,7 @@ class HttpTransport {
123
132
  }
124
133
  // arm sets a timer, clamped to what a timer can wait: a longer delay would fire after 1 ms.
125
134
  arm(fn, ms) {
126
- return this.timers.setTimeout(fn, Math.min(Math.max(ms, 0), MAX_TIMER_MILLIS));
135
+ return this.timers.setTimeout(fn, clampTimerMillis(ms));
127
136
  }
128
137
  // load builds the agent and loads the request function once. Sends that start together share
129
138
  // one agent. A failure is not kept: the next send tries again, as upstream's does. The http
@@ -147,30 +156,16 @@ class HttpTransport {
147
156
  }
148
157
  return this.io;
149
158
  }
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
159
  // attempt makes one request and resolves with what became of it. It rejects only when the agent
165
160
  // or the headers cannot be built, as upstream's does, and upstream's export delegate reports
166
161
  // that rejection as a failed export.
167
162
  async attempt(data, timeoutMillis) {
168
- if (this.stopped)
169
- return aborted();
163
+ if (this.abortController.signal.aborted)
164
+ return abortedAttempt();
170
165
  const io = await this.load();
171
166
  const headers = { ...(await this.params.headers()) };
172
- if (this.stopped)
173
- return aborted();
167
+ if (this.abortController.signal.aborted)
168
+ return abortedAttempt();
174
169
  const userAgent = this.params.userAgent;
175
170
  headers["User-Agent"] = userAgent ? `${userAgent} ${DEFAULT_USER_AGENT}` : DEFAULT_USER_AGENT;
176
171
  const gzipped = this.params.compression === "gzip";
@@ -212,17 +207,18 @@ class HttpTransport {
212
207
  }
213
208
  chunks.push(chunk);
214
209
  });
215
- const retryAfter = () => {
216
- const retryInMillis = retryAfterMillis(res.headers["retry-after"], this.timers.now());
217
- return retryInMillis === undefined ? {} : { retryInMillis };
218
- };
219
210
  res.on("end", () => {
220
211
  const status = res.statusCode;
221
- if (status && status <= 299) {
222
- settle({ status: "success", data: Buffer.concat(chunks) });
212
+ const classified = status === undefined
213
+ ? { kind: "fatal", status: 0 }
214
+ : classifyHttpStatus(status, res.headers["retry-after"], SERVER_STATUS_POLICY, this.timers.now());
215
+ if (classified.kind === "ok") {
216
+ settle({ status: "success", value: Buffer.concat(chunks) });
223
217
  }
224
- else if (status && RETRYABLE_STATUSES.has(status)) {
225
- settle({ status: "retryable", ...retryAfter() });
218
+ else if (classified.kind === "retry") {
219
+ settle(classified.retryAfterMillis === undefined
220
+ ? { status: "retryable" }
221
+ : { status: "retryable", retryInMillis: classified.retryAfterMillis });
226
222
  }
227
223
  else {
228
224
  settle({
@@ -235,11 +231,16 @@ class HttpTransport {
235
231
  // retries a retryable status, and fails anything else.
236
232
  res.on("error", (error) => {
237
233
  const status = res.statusCode;
238
- if (status && status <= 299) {
234
+ const classified = status === undefined
235
+ ? { kind: "fatal", status: 0 }
236
+ : classifyHttpStatus(status, res.headers["retry-after"], SERVER_STATUS_POLICY, this.timers.now());
237
+ if (classified.kind === "ok") {
239
238
  settle({ status: "success" });
240
239
  }
241
- else if (status && RETRYABLE_STATUSES.has(status)) {
242
- settle({ status: "retryable", error, ...retryAfter() });
240
+ else if (classified.kind === "retry") {
241
+ settle(classified.retryAfterMillis === undefined
242
+ ? { status: "retryable", error }
243
+ : { status: "retryable", error, retryInMillis: classified.retryAfterMillis });
243
244
  }
244
245
  else {
245
246
  settle({ status: "failure", error });
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.8.0";
2
+ export declare const VERSION = "0.9.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.8.0";
2
+ export const VERSION = "0.9.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libo11y/server",
3
- "version": "0.8.0",
3
+ "version": "0.9.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",
@@ -21,8 +21,8 @@
21
21
  "directory": "ts/packages/server"
22
22
  },
23
23
  "dependencies": {
24
- "@libo11y/core": "0.8.0",
25
- "@libo11y/spec": "0.8.0",
24
+ "@libo11y/core": "0.9.0",
25
+ "@libo11y/spec": "0.9.0",
26
26
  "@opentelemetry/context-async-hooks": "3.1.1",
27
27
  "@opentelemetry/core": "3.1.1",
28
28
  "@opentelemetry/exporter-metrics-otlp-http": "0.301.1",
@@ -39,7 +39,7 @@
39
39
  "@opentelemetry/api": ">=1.10.0 <1.11.0"
40
40
  },
41
41
  "devDependencies": {
42
- "@libo11y/test": "0.8.0",
42
+ "@libo11y/test": "0.9.0",
43
43
  "@opentelemetry/api": "1.10.0"
44
44
  },
45
45
  "files": [