@libo11y/server 0.1.2 → 0.3.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 +140 -17
- package/dist/exporters.d.ts +13 -7
- package/dist/exporters.js +74 -25
- package/dist/fetch.d.ts +7 -1
- package/dist/fetch.js +64 -19
- package/dist/http-common.d.ts +24 -1
- package/dist/http-common.js +64 -0
- package/dist/otlp-transport.d.ts +92 -0
- package/dist/otlp-transport.js +289 -0
- package/dist/serve.d.ts +10 -2
- package/dist/serve.js +84 -33
- package/dist/signals.d.ts +22 -6
- package/dist/signals.js +33 -9
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +4 -8
package/README.md
CHANGED
|
@@ -45,9 +45,22 @@ if (!report.ok) process.exitCode = 1;
|
|
|
45
45
|
and installs the context manager, providers, propagator and error handler
|
|
46
46
|
globally. A second call fails with `O11yError` code `ALREADY_SETUP` until
|
|
47
47
|
the first telemetry shuts down. `createTelemetry` is Go's `New`. It
|
|
48
|
-
|
|
49
|
-
`instrumentServe` and `instrumentFetch`, and its
|
|
50
|
-
to other code that needs them.
|
|
48
|
+
installs nothing in the OpenTelemetry globals and emits no canary. Pass
|
|
49
|
+
its `telemetry` to `instrumentServe` and `instrumentFetch`, and its
|
|
50
|
+
providers and propagator to other code that needs them.
|
|
51
|
+
|
|
52
|
+
Two options still reach outside a `createTelemetry` handle:
|
|
53
|
+
|
|
54
|
+
- `runtimeMetrics`, on by default, installs upstream's
|
|
55
|
+
require-in-the-middle hook on `Module.prototype.require`, and the hook
|
|
56
|
+
stays for the life of the process, after `shutdown` too. Pass
|
|
57
|
+
`runtimeMetrics: false` to avoid it.
|
|
58
|
+
- `captureConsole: true` patches `globalThis.console` until `shutdown`.
|
|
59
|
+
It is off by default. Leave it off to avoid it.
|
|
60
|
+
|
|
61
|
+
An option outside the closed set of values it takes, such as
|
|
62
|
+
`logLevel: "verbose"` or `console: "pretty"`, rejects `setup` and
|
|
63
|
+
`createTelemetry` with `O11yError` code `INVALID_OPTION`.
|
|
51
64
|
|
|
52
65
|
Both take the `TelemetryOptions` that the
|
|
53
66
|
[core README](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/core#options) lists. `OTEL_SDK_DISABLED=true`
|
|
@@ -75,6 +88,26 @@ handler runs inside the span's context, so the spans and logs it makes are
|
|
|
75
88
|
children of it. A thrown error marks the span failed, records the
|
|
76
89
|
exception and a 500, and is thrown again.
|
|
77
90
|
|
|
91
|
+
The telemetry never fails the request. The handler runs exactly once, and
|
|
92
|
+
only its own error reaches the caller:
|
|
93
|
+
|
|
94
|
+
- A propagator that throws on extract leaves the request without the
|
|
95
|
+
inbound context.
|
|
96
|
+
- A span that cannot start leaves the request uninstrumented. So does a
|
|
97
|
+
request the instrumentation cannot read, such as a value that is not a
|
|
98
|
+
`Request`: the handler is called with it as if it were not wrapped.
|
|
99
|
+
- A span that cannot end changes nothing the caller sees.
|
|
100
|
+
- A handler that resolves with something that is not a `Response` gets
|
|
101
|
+
that value returned unchanged.
|
|
102
|
+
|
|
103
|
+
Each of these is reported as one `o11y: telemetry error` line on stderr.
|
|
104
|
+
With the `telemetry` option the line goes through that telemetry's own
|
|
105
|
+
rate-limited handler, so it is written for a `createTelemetry` handle too.
|
|
106
|
+
Without it the report goes to the OpenTelemetry global error handler,
|
|
107
|
+
which `setup` makes libo11y's. A report names the step that failed and
|
|
108
|
+
the class of the error, and never the error's message, because a
|
|
109
|
+
propagator is handed the request's headers and its error can quote them.
|
|
110
|
+
|
|
78
111
|
| Option | Effect |
|
|
79
112
|
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
80
113
|
| `telemetry` | the telemetry whose providers and propagator to use. Default: the globals `setup` installs |
|
|
@@ -101,6 +134,14 @@ headers arrive. A 4xx or 5xx response or a failed request marks it failed.
|
|
|
101
134
|
The trace context goes into a copy of the request headers, and the caller's
|
|
102
135
|
`Request` and `init` are never changed.
|
|
103
136
|
|
|
137
|
+
The telemetry never fails the request here either. A propagator that
|
|
138
|
+
throws on inject is reported and the request is sent with its own headers.
|
|
139
|
+
A span that cannot start leaves the request uninstrumented. A span that
|
|
140
|
+
cannot end replaces neither the response nor fetch's own error. A
|
|
141
|
+
`fetchImpl` that resolves with something that is not a `Response` gets
|
|
142
|
+
that value returned unchanged. The reports are written as
|
|
143
|
+
`instrumentServe`'s are.
|
|
144
|
+
|
|
104
145
|
| Option | Effect |
|
|
105
146
|
| ------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
|
106
147
|
| `telemetry` | the telemetry whose providers and propagator to use. Default: the globals `setup` installs |
|
|
@@ -126,10 +167,18 @@ report. Each signal gets one `process.once` listener. The first signal
|
|
|
126
167
|
removes the others, so a second signal gets the runtime's default handling
|
|
127
168
|
and ends the process. It never exits the process itself.
|
|
128
169
|
|
|
170
|
+
`beforeShutdown` and the telemetry shutdown share one deadline, and
|
|
171
|
+
together they never take longer than `timeoutMillis`. `beforeShutdown` may
|
|
172
|
+
use nine tenths of it. The shutdown gets what is left of the whole, which
|
|
173
|
+
is then never less than a tenth, so buffered telemetry has a chance to
|
|
174
|
+
leave even when `beforeShutdown` used all it was allowed. A
|
|
175
|
+
`beforeShutdown` still running after nine tenths of the deadline is
|
|
176
|
+
reported as a `lifecycle` error, and the shutdown starts without it.
|
|
177
|
+
|
|
129
178
|
| Option | Effect |
|
|
130
179
|
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
131
180
|
| `signals` | the signal names to wait for. Default `["SIGINT", "SIGTERM"]` |
|
|
132
|
-
| `timeoutMillis` | the shutdown
|
|
181
|
+
| `timeoutMillis` | the one deadline for `beforeShutdown` and the telemetry shutdown together. Default 5000 ms. Read as `shutdown` reads its own: see the core README |
|
|
133
182
|
| `beforeShutdown` | runs after the signal and before telemetry shutdown. Stop the HTTP server here, so in-flight requests finish while their telemetry can still export |
|
|
134
183
|
|
|
135
184
|
## Runtime metrics
|
|
@@ -157,24 +206,93 @@ protocol is `http/protobuf` by default, or `http/json`, from
|
|
|
157
206
|
`OTEL_EXPORTER_OTLP_PROTOCOL` and its per-signal forms. `grpc` fails with
|
|
158
207
|
`UNSUPPORTED_PROTOCOL`.
|
|
159
208
|
|
|
160
|
-
|
|
161
|
-
|
|
209
|
+
Each OTLP exporter is upstream's exporter base, export delegate and
|
|
210
|
+
configuration over libo11y's own HTTP transport. Traces and logs use
|
|
211
|
+
upstream's serializers. Metrics use libo11y's, which write exemplars:
|
|
162
212
|
`OtlpProtobufMetricsSerializer` from this package, and core's
|
|
163
213
|
`OtlpJsonMetricsSerializer`. Upstream reads every other
|
|
164
|
-
`OTEL_EXPORTER_OTLP_*` variable,
|
|
165
|
-
certificates, compression
|
|
166
|
-
`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`. An
|
|
214
|
+
`OTEL_EXPORTER_OTLP_*` variable, shared and per signal: the endpoints,
|
|
215
|
+
headers, certificates, client key and certificate, compression, timeout
|
|
216
|
+
and `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`. An
|
|
167
217
|
`OTEL_METRIC_EXPORT_TIMEOUT` above `OTEL_METRIC_EXPORT_INTERVAL` is
|
|
168
218
|
clamped to the interval, as sdk-node does.
|
|
169
219
|
|
|
220
|
+
### The transport
|
|
221
|
+
|
|
222
|
+
Upstream does not export its HTTP transport or its retrying transport, and
|
|
223
|
+
neither can be stopped, so libo11y has its own. It follows upstream's in
|
|
224
|
+
everything a collector or a diag logger sees, apart from the six
|
|
225
|
+
differences below: the request and its framing, gzip, the `User-Agent`,
|
|
226
|
+
the statuses (429, 502, 503, 504) and network
|
|
227
|
+
errors that are retried, at most five retries, the backoff from one second
|
|
228
|
+
by half each time to five seconds with a fifth of jitter, `Retry-After` in
|
|
229
|
+
seconds or as an HTTP date, the time a retry is given, the 4 MiB cap on a
|
|
230
|
+
response body, and the diag messages about retries. The tests pin each of
|
|
231
|
+
these, and fail when the upstream files the transport follows change.
|
|
232
|
+
|
|
233
|
+
It differs from upstream's transport in six ways, and in no other:
|
|
234
|
+
|
|
235
|
+
1. **The timeout covers the whole attempt.** `OTEL_EXPORTER_OTLP_TIMEOUT`
|
|
236
|
+
bounds connecting, sending and reading the response together. Upstream's
|
|
237
|
+
timeout is an idle timeout that starts only once the socket has
|
|
238
|
+
connected. Two things follow. A connection that never completes, to an
|
|
239
|
+
unroutable address or a host that drops packets, now fails at the
|
|
240
|
+
timeout, where under Node it used to last as long as the operating
|
|
241
|
+
system kept trying. And a response that trickles in for longer than the
|
|
242
|
+
timeout now fails, where upstream let it run as long as bytes kept
|
|
243
|
+
arriving.
|
|
244
|
+
2. **Shutdown ends what is in flight.** Stopping an exporter destroys its
|
|
245
|
+
requests in flight, cancels its wait between two retries, and fails
|
|
246
|
+
every later export at once. Upstream's transport does nothing when it is
|
|
247
|
+
shut down.
|
|
248
|
+
3. **Shutdown destroys the agent**, which closes its idle keep-alive
|
|
249
|
+
connections to the collector.
|
|
250
|
+
4. **Exports that start together share one agent.** Upstream builds an
|
|
251
|
+
agent for each export that starts before the first agent exists, and
|
|
252
|
+
keeps the last.
|
|
253
|
+
5. **A wait that is too long for a timer is clamped.** A `Retry-After`
|
|
254
|
+
beyond 2147483647 ms, about 24.8 days, waits that long. Upstream's
|
|
255
|
+
timer fires after a millisecond. A timeout that large is clamped the
|
|
256
|
+
same way, which is also what upstream's amounts to.
|
|
257
|
+
6. **Under Bun a gzip body carries a `Content-Length`.** Upstream streams
|
|
258
|
+
the compressed body, which Bun frames as chunked. This transport
|
|
259
|
+
compresses the body in one call and then sends it, so Bun sends its
|
|
260
|
+
length. Under Node both send a gzip body chunked, though the same bytes
|
|
261
|
+
can be split into chunks differently. A body that is not compressed is
|
|
262
|
+
framed the same by both on each runtime. A collector reads either
|
|
263
|
+
framing.
|
|
264
|
+
|
|
265
|
+
Once `shutdown()` has resolved, the telemetry holds nothing that keeps
|
|
266
|
+
the process alive, with one exception. Under Node a name lookup in
|
|
267
|
+
progress cannot be cancelled. When the collector's host name does not
|
|
268
|
+
resolve and the resolver does not answer either, the export still fails on
|
|
269
|
+
time and `shutdown()` still resolves at its deadline, but the process
|
|
270
|
+
stays alive until the resolver gives up. That took 10 s in the review that
|
|
271
|
+
found it, and it depends on the resolver's own timeouts.
|
|
272
|
+
|
|
273
|
+
When the shutdown deadline passes with an export still in flight, the
|
|
274
|
+
export is abandoned and that signal is in the report. Its error is
|
|
275
|
+
`deadline exceeded`, unless another export of the same signal had already
|
|
276
|
+
failed, in which case the report carries that earlier error.
|
|
277
|
+
|
|
170
278
|
The export timeout defaults to 5000 ms for spans, logs and metrics, where
|
|
171
|
-
sdk-node uses 30000 ms
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
has resolved. The 5000 ms default matches the shutdown deadline. An
|
|
175
|
-
explicit `OTEL_BSP_EXPORT_TIMEOUT`, `OTEL_BLRP_EXPORT_TIMEOUT` or
|
|
279
|
+
sdk-node uses 30000 ms, so a flush against a collector that does not
|
|
280
|
+
answer gives up when the default shutdown deadline does. An explicit
|
|
281
|
+
`OTEL_BSP_EXPORT_TIMEOUT`, `OTEL_BLRP_EXPORT_TIMEOUT` or
|
|
176
282
|
`OTEL_METRIC_EXPORT_TIMEOUT` still wins.
|
|
177
283
|
|
|
284
|
+
## Propagators
|
|
285
|
+
|
|
286
|
+
`OTEL_PROPAGATORS` selects the propagators when the `propagators` option
|
|
287
|
+
is not given: `tracecontext`, `baggage` and `none`, as a comma-separated
|
|
288
|
+
list applied in order. Unset or empty, it leaves the default,
|
|
289
|
+
`tracecontext,baggage`. Any other name, such as `b3` or `jaeger`, rejects
|
|
290
|
+
`setup` and `createTelemetry` with `O11yError` code
|
|
291
|
+
`UNSUPPORTED_PROPAGATOR`. Pass a propagator for it through the
|
|
292
|
+
`propagators` option. The
|
|
293
|
+
[core README](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/core#options)
|
|
294
|
+
has the details.
|
|
295
|
+
|
|
178
296
|
## Resource
|
|
179
297
|
|
|
180
298
|
The detected resource holds the upstream `telemetry.sdk.*` attributes,
|
|
@@ -223,9 +341,14 @@ Node 24 keeps the context in both of the last two cases.
|
|
|
223
341
|
## Known limitations
|
|
224
342
|
|
|
225
343
|
- Upstream's `RuntimeNodeInstrumentation` installs a require-in-the-middle
|
|
226
|
-
hook on `Module.prototype.require
|
|
227
|
-
|
|
228
|
-
|
|
344
|
+
hook on `Module.prototype.require`, for `setup` and for `createTelemetry`
|
|
345
|
+
alike. It installs the hook when it is constructed, although it patches
|
|
346
|
+
no module. The hook stays for the life of the process, even after
|
|
347
|
+
`shutdown()`. Pass `runtimeMetrics: false` to avoid it.
|
|
348
|
+
- A span's attributes are read by upstream's tracer. An attributes object
|
|
349
|
+
that cannot be read, such as a revoked `Proxy`, throws from `startSpan`
|
|
350
|
+
or `setAttributes`. The logger, wide records and metric instruments do
|
|
351
|
+
not throw this way.
|
|
229
352
|
- OTLP over gRPC is not supported.
|
|
230
353
|
|
|
231
354
|
## Parity
|
package/dist/exporters.d.ts
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The exporters for each signal core routes to otlp or console.
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* upstream's
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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.
|
|
9
15
|
*/
|
|
10
16
|
import { type ExporterRequest, type ExporterSet } from "@libo11y/core";
|
|
11
17
|
/** Builds the exporters for every signal the configuration routes to "otlp" or "console". */
|
package/dist/exporters.js
CHANGED
|
@@ -1,26 +1,34 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The exporters for each signal core routes to otlp or console.
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* upstream's
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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.
|
|
9
15
|
*/
|
|
10
16
|
import { exemplarMetricExporter, O11yError, OtlpJsonMetricsSerializer, } from "@libo11y/core";
|
|
11
|
-
import { OTLPLogExporter as OTLPJsonLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
|
|
12
|
-
import { OTLPLogExporter as OTLPProtoLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
|
|
13
17
|
import { OTLPMetricExporterBase } from "@opentelemetry/exporter-metrics-otlp-http";
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import { ConsoleLogRecordExporter } from "@opentelemetry/sdk-logs";
|
|
18
|
+
import { createOtlpNetworkExportDelegate, OTLPExporterBase, } from "@opentelemetry/otlp-exporter-base";
|
|
19
|
+
import { convertLegacyHttpOptions, createOtlpHttpExporterMetrics, } from "@opentelemetry/otlp-exporter-base/node-http";
|
|
20
|
+
import { JsonLogsSerializer, JsonTraceSerializer, LogsExporterMetricsHelper, MetricsExporterMetricsHelper, ProtobufLogsSerializer, ProtobufTraceSerializer, TraceExporterMetricsHelper, } from "@opentelemetry/otlp-transformer";
|
|
21
|
+
import { ConsoleLogRecordExporter, } from "@opentelemetry/sdk-logs";
|
|
19
22
|
import { ConsoleMetricExporter, PeriodicExportingMetricReader, } from "@opentelemetry/sdk-metrics";
|
|
20
23
|
import { ConsoleSpanExporter } from "@opentelemetry/sdk-trace";
|
|
21
24
|
import { OtlpProtobufMetricsSerializer } from "./otlp-proto-metrics.js";
|
|
22
|
-
|
|
25
|
+
import { createHttpTransport } from "./otlp-transport.js";
|
|
26
|
+
/** The otel.component.type upstream's OTLP HTTP exporters report. */
|
|
27
|
+
const SPAN_EXPORTER_COMPONENT = "otlp_http_span_exporter";
|
|
23
28
|
const METRIC_EXPORTER_COMPONENT = "otlp_http_metric_exporter";
|
|
29
|
+
const LOG_EXPORTER_COMPONENT = "otlp_http_log_exporter";
|
|
30
|
+
const PROTOBUF = "application/x-protobuf";
|
|
31
|
+
const JSON_TYPE = "application/json";
|
|
24
32
|
// build runs a constructor and reports a failure as Go's "o11y: building <kind>: %w".
|
|
25
33
|
function build(kind, fn) {
|
|
26
34
|
try {
|
|
@@ -33,17 +41,52 @@ function build(kind, fn) {
|
|
|
33
41
|
}
|
|
34
42
|
}
|
|
35
43
|
/**
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
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.
|
|
39
47
|
*/
|
|
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 };
|
|
53
|
+
}
|
|
54
|
+
// stop ends an exporter. Upstream's shutdown waits for the exports in flight, which is what keeps
|
|
55
|
+
// an exiting process alive when the collector does not answer. This one ends them first: whoever
|
|
56
|
+
// stops an exporter has flushed it, or has run out of time to.
|
|
57
|
+
async function stop(transport, shutdown) {
|
|
58
|
+
transport.abort();
|
|
59
|
+
await shutdown();
|
|
60
|
+
}
|
|
61
|
+
/** Upstream's OTLP exporter for spans or log records, over a transport that shutdown() stops. */
|
|
62
|
+
class OtlpExporter extends OTLPExporterBase {
|
|
63
|
+
transport;
|
|
64
|
+
constructor(otlp) {
|
|
65
|
+
super(otlp.delegate);
|
|
66
|
+
this.transport = otlp.transport;
|
|
67
|
+
}
|
|
68
|
+
shutdown() {
|
|
69
|
+
return stop(this.transport, () => super.shutdown());
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
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.
|
|
75
|
+
*/
|
|
76
|
+
class OtlpMetricExporter extends OTLPMetricExporterBase {
|
|
77
|
+
transport;
|
|
78
|
+
constructor(otlp) {
|
|
79
|
+
super(otlp.delegate);
|
|
80
|
+
this.transport = otlp.transport;
|
|
81
|
+
}
|
|
82
|
+
shutdown() {
|
|
83
|
+
return stop(this.transport, () => super.shutdown());
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** The OTLP metric exporter for protocol, with libo11y's serializer, which writes exemplars. */
|
|
40
87
|
function otlpMetricExporter(protocol) {
|
|
41
88
|
const protobuf = protocol === "http/protobuf";
|
|
42
|
-
|
|
43
|
-
"Content-Type": protobuf ? "application/x-protobuf" : "application/json",
|
|
44
|
-
});
|
|
45
|
-
const serializer = protobuf ? OtlpProtobufMetricsSerializer : OtlpJsonMetricsSerializer;
|
|
46
|
-
return new OTLPMetricExporterBase(createOtlpHttpExportDelegate(options, serializer, METRIC_EXPORTER_COMPONENT, MetricsExporterMetricsHelper, undefined));
|
|
89
|
+
return new OtlpMetricExporter(otlpExport("METRICS", "v1/metrics", protobuf ? PROTOBUF : JSON_TYPE, protobuf ? OtlpProtobufMetricsSerializer : OtlpJsonMetricsSerializer, METRIC_EXPORTER_COMPONENT, MetricsExporterMetricsHelper));
|
|
47
90
|
}
|
|
48
91
|
function spanExporter(req) {
|
|
49
92
|
const { traces, protocol } = req.config;
|
|
@@ -51,7 +94,10 @@ function spanExporter(req) {
|
|
|
51
94
|
return new ConsoleSpanExporter();
|
|
52
95
|
if (traces !== "otlp")
|
|
53
96
|
return undefined;
|
|
54
|
-
return build("span exporter", () =>
|
|
97
|
+
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));
|
|
100
|
+
});
|
|
55
101
|
}
|
|
56
102
|
function logExporter(req) {
|
|
57
103
|
const { logs, protocol } = req.config;
|
|
@@ -59,7 +105,10 @@ function logExporter(req) {
|
|
|
59
105
|
return new ConsoleLogRecordExporter();
|
|
60
106
|
if (logs !== "otlp")
|
|
61
107
|
return undefined;
|
|
62
|
-
return build("log exporter", () =>
|
|
108
|
+
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));
|
|
111
|
+
});
|
|
63
112
|
}
|
|
64
113
|
function metricReader(req) {
|
|
65
114
|
const { metrics, protocol, metricExport } = req.config;
|
package/dist/fetch.d.ts
CHANGED
|
@@ -11,7 +11,8 @@ export interface FetchOptions {
|
|
|
11
11
|
/**
|
|
12
12
|
* Decides per destination whether the trace context and baggage are injected. Every destination
|
|
13
13
|
* gets them by default; return false for third parties that should not see internal trace IDs.
|
|
14
|
-
* A predicate that throws is reported
|
|
14
|
+
* A predicate that throws is taken as false and reported to the error handler by the class of
|
|
15
|
+
* what it threw, never with its message, which can quote the URL.
|
|
15
16
|
*/
|
|
16
17
|
readonly propagate?: (url: URL) => boolean;
|
|
17
18
|
/** The peer.service attribute: the logical name of the service called. */
|
|
@@ -24,5 +25,10 @@ export interface FetchOptions {
|
|
|
24
25
|
* fails. 4xx and 5xx responses and failures mark the span failed. The trace context is injected
|
|
25
26
|
* into a copy of the request headers; the caller's Request and init are never changed. A URL that
|
|
26
27
|
* cannot be parsed is passed to fetchImpl uninstrumented, so its own error surfaces.
|
|
28
|
+
*
|
|
29
|
+
* The telemetry never fails the request. A span that cannot start leaves the request
|
|
30
|
+
* uninstrumented, a propagator that throws leaves it without the injected context, and a span that
|
|
31
|
+
* cannot end changes nothing the caller sees. Each is reported to the error handler. Only fetchImpl
|
|
32
|
+
* itself, or headers it would reject, make the returned promise reject.
|
|
27
33
|
*/
|
|
28
34
|
export declare function instrumentFetch(fetchImpl?: typeof fetch, opts?: FetchOptions): typeof fetch;
|
package/dist/fetch.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { context,
|
|
2
|
-
import { asException, HEADERS_SETTER, instrumentResolver, methodAttributes, methodName, normalizeMethod, serverAttributes, } from "./http-common.js";
|
|
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";
|
|
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. */
|
|
@@ -14,6 +14,17 @@ function errorName(err) {
|
|
|
14
14
|
}
|
|
15
15
|
return "_OTHER";
|
|
16
16
|
}
|
|
17
|
+
/** Injects ctx into headers. A propagator that throws is reported, and false is returned. */
|
|
18
|
+
function inject(telemetry, propagator, ctx, headers) {
|
|
19
|
+
try {
|
|
20
|
+
propagator.inject(ctx, headers, HEADERS_SETTER);
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
catch (err) {
|
|
24
|
+
reportError(telemetry, "instrumentFetch: injecting the trace context failed, the request is sent without it", err);
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
17
28
|
/**
|
|
18
29
|
* Wraps fetchImpl (default: globalThis.fetch as it is now) with a CLIENT span per request, named by
|
|
19
30
|
* method, and the http.client.request.duration histogram, recorded in the span's context so its
|
|
@@ -21,22 +32,20 @@ function errorName(err) {
|
|
|
21
32
|
* fails. 4xx and 5xx responses and failures mark the span failed. The trace context is injected
|
|
22
33
|
* into a copy of the request headers; the caller's Request and init are never changed. A URL that
|
|
23
34
|
* cannot be parsed is passed to fetchImpl uninstrumented, so its own error surfaces.
|
|
35
|
+
*
|
|
36
|
+
* The telemetry never fails the request. A span that cannot start leaves the request
|
|
37
|
+
* uninstrumented, a propagator that throws leaves it without the injected context, and a span that
|
|
38
|
+
* cannot end changes nothing the caller sees. Each is reported to the error handler. Only fetchImpl
|
|
39
|
+
* itself, or headers it would reject, make the returned promise reject.
|
|
24
40
|
*/
|
|
25
41
|
export function instrumentFetch(fetchImpl = globalThis.fetch, opts = {}) {
|
|
26
42
|
const base = fetchImpl;
|
|
27
43
|
const instruments = instrumentResolver(opts.telemetry, "http.client.request.duration", "Duration of HTTP client requests.");
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
try {
|
|
32
|
-
url = new URL(request?.url ?? String(input));
|
|
33
|
-
}
|
|
34
|
-
catch {
|
|
35
|
-
return base(input, init);
|
|
36
|
-
}
|
|
37
|
-
const start = performance.now();
|
|
44
|
+
// begin resolves the instruments and starts the client span. Whatever it throws comes from the
|
|
45
|
+
// telemetry, never from the request.
|
|
46
|
+
const begin = (url, rawMethod) => {
|
|
38
47
|
const { tracer, histogram, propagator } = instruments();
|
|
39
|
-
const raw = sentMethod(
|
|
48
|
+
const raw = sentMethod(rawMethod);
|
|
40
49
|
const { method } = normalizeMethod(raw);
|
|
41
50
|
const server = serverAttributes(url);
|
|
42
51
|
const full = new URL(url);
|
|
@@ -50,16 +59,41 @@ export function instrumentFetch(fetchImpl = globalThis.fetch, opts = {}) {
|
|
|
50
59
|
};
|
|
51
60
|
const parent = context.active();
|
|
52
61
|
const span = tracer.startSpan(methodName(method), { kind: SpanKind.CLIENT, attributes }, parent);
|
|
53
|
-
|
|
62
|
+
return { span, spanContext: trace.setSpan(parent, span), histogram, propagator, method, server };
|
|
63
|
+
};
|
|
64
|
+
const traced = async (input, init) => {
|
|
65
|
+
const request = input instanceof Request ? input : undefined;
|
|
66
|
+
let url;
|
|
67
|
+
try {
|
|
68
|
+
url = new URL(request?.url ?? String(input));
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return base(input, init);
|
|
72
|
+
}
|
|
73
|
+
const start = performance.now();
|
|
74
|
+
let begun;
|
|
75
|
+
try {
|
|
76
|
+
begun = begin(url, init?.method ?? request?.method ?? "GET");
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
reportError(opts.telemetry, "instrumentFetch: starting the request's telemetry failed, the request is not instrumented", err);
|
|
80
|
+
return base(input, init);
|
|
81
|
+
}
|
|
82
|
+
const { span, spanContext, histogram, propagator, method, server } = begun;
|
|
54
83
|
let propagate = true;
|
|
55
84
|
try {
|
|
56
85
|
propagate = opts.propagate?.(url) ?? true;
|
|
57
86
|
}
|
|
58
87
|
catch (err) {
|
|
59
88
|
propagate = false;
|
|
60
|
-
|
|
89
|
+
// By class only: the predicate is handed the URL, and its error can quote it.
|
|
90
|
+
reportError(opts.telemetry, "instrumentFetch: the propagate option failed, the context is not sent", err);
|
|
61
91
|
}
|
|
62
|
-
const
|
|
92
|
+
const end = (response, failure) => {
|
|
93
|
+
// The status is read here, inside finish's guard: a fetchImpl may resolve with something
|
|
94
|
+
// that is not a Response, and that is the caller's to deal with, not a reason to throw.
|
|
95
|
+
const read = response?.status;
|
|
96
|
+
const status = typeof read === "number" ? read : undefined;
|
|
63
97
|
const errorType = failure !== undefined
|
|
64
98
|
? errorName(failure.error)
|
|
65
99
|
: status !== undefined && status >= 400
|
|
@@ -81,6 +115,16 @@ export function instrumentFetch(fetchImpl = globalThis.fetch, opts = {}) {
|
|
|
81
115
|
}, trace.setSpan(ROOT_CONTEXT, span));
|
|
82
116
|
span.end();
|
|
83
117
|
};
|
|
118
|
+
// finish guards end, so a throw from a span processor or an instrument never replaces the
|
|
119
|
+
// response or fetch's own error.
|
|
120
|
+
const finish = (response, failure) => {
|
|
121
|
+
try {
|
|
122
|
+
end(response, failure);
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
reportError(opts.telemetry, "instrumentFetch: ending the request's telemetry failed", err);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
84
128
|
let res;
|
|
85
129
|
try {
|
|
86
130
|
let args = [input, init];
|
|
@@ -88,8 +132,9 @@ export function instrumentFetch(fetchImpl = globalThis.fetch, opts = {}) {
|
|
|
88
132
|
// fetch takes init's headers over the Request's, so the copy starts from the same source.
|
|
89
133
|
// Headers fetch would reject throw here instead, and fail the request the same way.
|
|
90
134
|
const headers = new Headers(init?.headers ?? request?.headers);
|
|
91
|
-
propagator
|
|
92
|
-
|
|
135
|
+
// A copy the propagator only half filled is not sent: the request keeps its own headers.
|
|
136
|
+
if (inject(opts.telemetry, propagator, spanContext, headers))
|
|
137
|
+
args = [input, { ...init, headers }];
|
|
93
138
|
}
|
|
94
139
|
res = await context.with(spanContext, () => base(...args));
|
|
95
140
|
}
|
|
@@ -97,7 +142,7 @@ export function instrumentFetch(fetchImpl = globalThis.fetch, opts = {}) {
|
|
|
97
142
|
finish(undefined, { error: err });
|
|
98
143
|
throw err;
|
|
99
144
|
}
|
|
100
|
-
finish(res
|
|
145
|
+
finish(res);
|
|
101
146
|
return res;
|
|
102
147
|
};
|
|
103
148
|
const preconnect = base.preconnect;
|
package/dist/http-common.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* What instrumentServe and instrumentFetch share: the semantic-convention method set and its
|
|
3
3
|
* normalization (Go o11yhttp's normalizeMethod), the duration histograms, the Headers carrier, URL
|
|
4
|
-
* attributes,
|
|
4
|
+
* attributes, resolving the tracer, meter and propagator from a Telemetry or the globals, and
|
|
5
|
+
* reporting a failure of the instrumentation itself.
|
|
5
6
|
*/
|
|
6
7
|
import type { Telemetry } from "@libo11y/core";
|
|
7
8
|
import { type Attributes, type Histogram, type TextMapGetter, type TextMapPropagator, type TextMapSetter, type Tracer } from "@opentelemetry/api";
|
|
@@ -29,6 +30,28 @@ export declare function serverAttributes(url: URL): Attributes;
|
|
|
29
30
|
export declare function schemeOf(url: URL): string;
|
|
30
31
|
/** The error.type of a thrown value: its constructor name for an Error, else "_OTHER". */
|
|
31
32
|
export declare function errorConstructorName(err: unknown): string;
|
|
33
|
+
/** The message of a thrown value. It never throws, whatever was thrown. */
|
|
34
|
+
export declare function errorMessage(err: unknown): string;
|
|
35
|
+
/**
|
|
36
|
+
* The class of a thrown value, for a report: its constructor's name when that reads as a class
|
|
37
|
+
* name, "Error" for any other error, and the value's type for anything that is not an object. It
|
|
38
|
+
* never throws and never returns the value's own text.
|
|
39
|
+
*/
|
|
40
|
+
export declare function errorClass(thrown: unknown): string;
|
|
41
|
+
/**
|
|
42
|
+
* Reports a failure of the instrumentation itself, which must never reach the request it wraps:
|
|
43
|
+
* a propagator that throws, a span that cannot start or end. It never throws.
|
|
44
|
+
*
|
|
45
|
+
* The report is an Error whose message is "o11y: <what>: <class of what was thrown>", with what
|
|
46
|
+
* was thrown on its cause. The message of what was thrown is left out: a propagator is handed the
|
|
47
|
+
* request's headers, and its error can quote them.
|
|
48
|
+
*
|
|
49
|
+
* With a telemetry the report goes through that handle's own handler, so it is written for a
|
|
50
|
+
* createTelemetry handle too, which installs nothing globally. Without one, or with something that
|
|
51
|
+
* is not a core handle, it goes to the OpenTelemetry global error handler, which setup makes
|
|
52
|
+
* libo11y's rate-limited one.
|
|
53
|
+
*/
|
|
54
|
+
export declare function reportError(telemetry: Telemetry | undefined, what: string, err: unknown): void;
|
|
32
55
|
/** A thrown value as a span exception, for recordException. */
|
|
33
56
|
export declare function asException(err: unknown): Error | string;
|
|
34
57
|
/** Reads a Headers carrier for extraction. */
|