@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.
- package/LICENSE +202 -0
- package/README.md +234 -2
- package/dist/context.d.ts +10 -0
- package/dist/context.js +5 -0
- package/dist/exporters.d.ts +12 -0
- package/dist/exporters.js +90 -0
- package/dist/fetch.d.ts +28 -0
- package/dist/fetch.js +107 -0
- package/dist/glob.d.ts +14 -0
- package/dist/glob.js +177 -0
- package/dist/http-common.d.ts +50 -0
- package/dist/http-common.js +105 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +14 -0
- package/dist/otlp-proto-metrics.d.ts +21 -0
- package/dist/otlp-proto-metrics.js +401 -0
- package/dist/platform.d.ts +3 -0
- package/dist/platform.js +31 -0
- package/dist/registry.d.ts +8 -0
- package/dist/registry.js +66 -0
- package/dist/resource.d.ts +13 -0
- package/dist/resource.js +67 -0
- package/dist/runtime-metrics.d.ts +23 -0
- package/dist/runtime-metrics.js +62 -0
- package/dist/serve.d.ts +85 -0
- package/dist/serve.js +321 -0
- package/dist/setup.d.ts +13 -0
- package/dist/setup.js +18 -0
- package/dist/signals.d.ts +35 -0
- package/dist/signals.js +58 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/package.json +50 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,235 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @libo11y/server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The libo11y server platform for TypeScript on Bun 1.3.13 and Node 24. It
|
|
4
|
+
binds [`@libo11y/core`](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/core) to a server runtime with an
|
|
5
|
+
`AsyncLocalStorage` context manager, resource detection, OTLP exporters
|
|
6
|
+
built from the `OTEL_*` variables, a protobuf metric serializer that
|
|
7
|
+
carries exemplars, runtime metrics, application registry loading and
|
|
8
|
+
signal handling. `instrumentServe` and `instrumentFetch` instrument HTTP
|
|
9
|
+
servers and clients.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install @libo11y/server
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { instrumentFetch, instrumentServe, loadAppRegistry, setup, shutdownOnSignals } from "@libo11y/server";
|
|
19
|
+
|
|
20
|
+
const telemetry = await setup({
|
|
21
|
+
serviceName: "checkout",
|
|
22
|
+
environment: "production",
|
|
23
|
+
registry: await loadAppRegistry("o11y-registry.yaml"),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const upstream = instrumentFetch(fetch, { peerService: "inventory" });
|
|
27
|
+
const server = Bun.serve({
|
|
28
|
+
port: 8080,
|
|
29
|
+
fetch: instrumentServe(
|
|
30
|
+
async (req) => {
|
|
31
|
+
const stock = await upstream("http://inventory.internal/stock");
|
|
32
|
+
telemetry.logger.info("stock loaded");
|
|
33
|
+
return new Response(stock.ok ? "in stock" : "unknown");
|
|
34
|
+
},
|
|
35
|
+
{ route: () => "/stock", serverTiming: true },
|
|
36
|
+
),
|
|
37
|
+
});
|
|
38
|
+
telemetry.logger.info("listening", { "server.port": server.port ?? 0 });
|
|
39
|
+
|
|
40
|
+
const report = await shutdownOnSignals(telemetry, { beforeShutdown: () => server.stop() });
|
|
41
|
+
if (!report.ok) process.exitCode = 1;
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`setup` is Go's `Setup`. It emits the `o11y.telemetry.configured` canary
|
|
45
|
+
and installs the context manager, providers, propagator and error handler
|
|
46
|
+
globally. A second call fails with `O11yError` code `ALREADY_SETUP` until
|
|
47
|
+
the first telemetry shuts down. `createTelemetry` is Go's `New`. It
|
|
48
|
+
touches no global and emits no canary. Pass its `telemetry` to
|
|
49
|
+
`instrumentServe` and `instrumentFetch`, and its providers and propagator
|
|
50
|
+
to other code that needs them.
|
|
51
|
+
|
|
52
|
+
Both take the `TelemetryOptions` that the
|
|
53
|
+
[core README](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/core#options) lists. `OTEL_SDK_DISABLED=true`
|
|
54
|
+
turns off every export, injected exporters included, and runtime metrics.
|
|
55
|
+
The logger still writes to the console.
|
|
56
|
+
|
|
57
|
+
This package re-exports the core types an application needs most:
|
|
58
|
+
`Telemetry`, `TelemetryOptions`, `Logger`, `SignalReport`,
|
|
59
|
+
`LifecycleOptions`, `O11yError` and `O11yErrorCode`.
|
|
60
|
+
|
|
61
|
+
The repository has two complete examples:
|
|
62
|
+
[`examples/bun-server`](https://github.com/jamesainslie/libo11y/tree/main/ts/examples/bun-server) and
|
|
63
|
+
[`examples/node-server`](https://github.com/jamesainslie/libo11y/tree/main/ts/examples/node-server), a `node:http` server
|
|
64
|
+
with a `Request` and `Response` adapter.
|
|
65
|
+
|
|
66
|
+
## HTTP servers
|
|
67
|
+
|
|
68
|
+
`instrumentServe(handler, opts?)` wraps a fetch-style handler,
|
|
69
|
+
`(req: Request, ...rest) => Response`, as `Bun.serve`, Hono, Elysia and
|
|
70
|
+
`node:http` adapters use. It is the counterpart of Go's
|
|
71
|
+
`o11yhttp.NewHandler`. Each request gets a SERVER span named
|
|
72
|
+
`<METHOD> <route>`, or by method alone without a route, the `http.server.request.duration` histogram with
|
|
73
|
+
exemplars, and optionally the `o11y.request.summary` canonical line. The
|
|
74
|
+
handler runs inside the span's context, so the spans and logs it makes are
|
|
75
|
+
children of it. A thrown error marks the span failed, records the
|
|
76
|
+
exception and a 500, and is thrown again.
|
|
77
|
+
|
|
78
|
+
| Option | Effect |
|
|
79
|
+
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
80
|
+
| `telemetry` | the telemetry whose providers and propagator to use. Default: the globals `setup` installs |
|
|
81
|
+
| `route` | resolves the route template of a request, such as `/projects/:id`, for the span name, `http.route` and the metric. A template that starts with a method and a space, such as `GET /x`, names the span verbatim |
|
|
82
|
+
| `publicEndpoint` | an internet-facing server. Inbound trace context starts a new root span linked to it, instead of becoming its parent. Baggage is still extracted |
|
|
83
|
+
| `ignorePaths` | URL paths to leave uninstrumented, as Go `path.Match` patterns such as `/healthz` or `/debug/*`, matched against the decoded path as Go matches them |
|
|
84
|
+
| `serverTiming` | adds `Server-Timing: traceparent;desc="00-<trace>-<span>-<flags>"` to `text/html` responses, so the page can join the server's trace |
|
|
85
|
+
| `canonicalLine` | emits one `o11y.request.summary` event per request with the request's wide record. It needs `telemetry` |
|
|
86
|
+
| `watchBody` | `watchBody(res)` decides which responses end the span when the body finishes. Default: `text/html` and `text/event-stream` bodies. Other responses end the span when the handler returns, and keep their `Content-Length` and sendfile |
|
|
87
|
+
|
|
88
|
+
A framework that routes inside its own handler, such as TanStack Start,
|
|
89
|
+
calls `setRoute(route)` from inside the handler. It sets `http.route` and
|
|
90
|
+
the span name for the current request.
|
|
91
|
+
|
|
92
|
+
## HTTP clients
|
|
93
|
+
|
|
94
|
+
`instrumentFetch(fetchImpl?, opts?)` wraps a fetch function and returns a
|
|
95
|
+
new one. It is the counterpart of Go's `o11yhttp.NewTransport`. It never
|
|
96
|
+
patches `globalThis.fetch`, and it works on Bun, whose fetch publishes
|
|
97
|
+
none of the diagnostics channels that Node's upstream instrumentation
|
|
98
|
+
reads. Each request gets a CLIENT span named by method and the
|
|
99
|
+
`http.client.request.duration` histogram. The span ends when the response
|
|
100
|
+
headers arrive. A 4xx or 5xx response or a failed request marks it failed.
|
|
101
|
+
The trace context goes into a copy of the request headers, and the caller's
|
|
102
|
+
`Request` and `init` are never changed.
|
|
103
|
+
|
|
104
|
+
| Option | Effect |
|
|
105
|
+
| ------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
|
106
|
+
| `telemetry` | the telemetry whose providers and propagator to use. Default: the globals `setup` installs |
|
|
107
|
+
| `propagate` | `propagate(url)` decides per destination whether the trace context and baggage are injected. Default: every destination |
|
|
108
|
+
| `peerService` | the `peer.service` attribute, the logical name of the service called |
|
|
109
|
+
|
|
110
|
+
## Application registries
|
|
111
|
+
|
|
112
|
+
`loadAppRegistry(path)` reads, validates and compiles a registry file,
|
|
113
|
+
with the path as its source. It fails with `O11yError` code
|
|
114
|
+
`INVALID_APP_REGISTRY` and Go's messages:
|
|
115
|
+
|
|
116
|
+
- `o11y: reading application registry: open <path>: no such file or directory`
|
|
117
|
+
- `o11y: <path>: application registry is empty`
|
|
118
|
+
- `o11y: <path>: parsing application registry: ...`
|
|
119
|
+
- `o11y: invalid application registry: <path>: <violation>; <violation>`
|
|
120
|
+
|
|
121
|
+
## Signals
|
|
122
|
+
|
|
123
|
+
`shutdownOnSignals(telemetry, opts?)` waits for a termination signal, runs
|
|
124
|
+
`beforeShutdown`, then shuts the telemetry down and resolves with the
|
|
125
|
+
report. Each signal gets one `process.once` listener. The first signal
|
|
126
|
+
removes the others, so a second signal gets the runtime's default handling
|
|
127
|
+
and ends the process. It never exits the process itself.
|
|
128
|
+
|
|
129
|
+
| Option | Effect |
|
|
130
|
+
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
131
|
+
| `signals` | the signal names to wait for. Default `["SIGINT", "SIGTERM"]` |
|
|
132
|
+
| `timeoutMillis` | the shutdown deadline. Default 5000 ms, shutdown's own |
|
|
133
|
+
| `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
|
+
|
|
135
|
+
## Runtime metrics
|
|
136
|
+
|
|
137
|
+
Runtime metrics are on by default, and `runtimeMetrics: false` turns them
|
|
138
|
+
off. They come from upstream's `RuntimeNodeInstrumentation`, on the
|
|
139
|
+
telemetry's meter provider, never the global one. On Bun:
|
|
140
|
+
|
|
141
|
+
- `nodejs.eventloop.utilization` is not recorded, because Bun always
|
|
142
|
+
reports zero ([oven-sh/bun#34068](https://github.com/oven-sh/bun/issues/34068)).
|
|
143
|
+
- The `v8js.*` metrics are absent, because Bun 1.3.13 has no
|
|
144
|
+
`v8.getHeapSpaceStatistics` and reports no GC or active-resource data
|
|
145
|
+
to the instrumentation.
|
|
146
|
+
|
|
147
|
+
Shutdown stops runtime metrics after the meter provider's final
|
|
148
|
+
collection, so a process that ends before its first periodic export still
|
|
149
|
+
reports them.
|
|
150
|
+
|
|
151
|
+
## Exporters
|
|
152
|
+
|
|
153
|
+
`serverPlatform()` builds the exporters core asks for from the `OTEL_*`
|
|
154
|
+
variables. `OTEL_TRACES_EXPORTER`, `OTEL_METRICS_EXPORTER` and
|
|
155
|
+
`OTEL_LOGS_EXPORTER` take `otlp` (the default), `console` or `none`. The
|
|
156
|
+
protocol is `http/protobuf` by default, or `http/json`, from
|
|
157
|
+
`OTEL_EXPORTER_OTLP_PROTOCOL` and its per-signal forms. `grpc` fails with
|
|
158
|
+
`UNSUPPORTED_PROTOCOL`.
|
|
159
|
+
|
|
160
|
+
Traces and logs use the upstream OTLP exporters. Metrics use upstream's
|
|
161
|
+
OTLP transport with libo11y's serializers, which write exemplars:
|
|
162
|
+
`OtlpProtobufMetricsSerializer` from this package, and core's
|
|
163
|
+
`OtlpJsonMetricsSerializer`. Upstream reads every other
|
|
164
|
+
`OTEL_EXPORTER_OTLP_*` variable, such as the endpoints, headers,
|
|
165
|
+
certificates, compression and
|
|
166
|
+
`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`. An
|
|
167
|
+
`OTEL_METRIC_EXPORT_TIMEOUT` above `OTEL_METRIC_EXPORT_INTERVAL` is
|
|
168
|
+
clamped to the interval, as sdk-node does.
|
|
169
|
+
|
|
170
|
+
The export timeout defaults to 5000 ms for spans, logs and metrics, where
|
|
171
|
+
sdk-node uses 30000 ms. Upstream's batch processors and periodic reader
|
|
172
|
+
arm an export timer that does not let the process exit, so a hung exporter
|
|
173
|
+
keeps an exiting process alive until the timer fires, even after shutdown
|
|
174
|
+
has resolved. The 5000 ms default matches the shutdown deadline. An
|
|
175
|
+
explicit `OTEL_BSP_EXPORT_TIMEOUT`, `OTEL_BLRP_EXPORT_TIMEOUT` or
|
|
176
|
+
`OTEL_METRIC_EXPORT_TIMEOUT` still wins.
|
|
177
|
+
|
|
178
|
+
## Resource
|
|
179
|
+
|
|
180
|
+
The detected resource holds the upstream `telemetry.sdk.*` attributes,
|
|
181
|
+
`process.runtime.name` (`bun` or `nodejs`), `process.runtime.version`,
|
|
182
|
+
`process.runtime.description`, `host.name` and `container.id`. It never
|
|
183
|
+
holds the process command line, the pid or `host.id`. Upstream's detectors
|
|
184
|
+
read `OTEL_RESOURCE_ATTRIBUTES` and `OTEL_SERVICE_NAME`, and
|
|
185
|
+
`OTEL_SERVICE_NAME` wins.
|
|
186
|
+
|
|
187
|
+
There is no Kubernetes detector, as in Go. Pass the pod identity through
|
|
188
|
+
the Downward API and `OTEL_RESOURCE_ATTRIBUTES`. Kubernetes expands
|
|
189
|
+
`$(NAME)` from variables defined earlier in the list:
|
|
190
|
+
|
|
191
|
+
```yaml
|
|
192
|
+
env:
|
|
193
|
+
- name: POD_UID
|
|
194
|
+
valueFrom: { fieldRef: { fieldPath: metadata.uid } }
|
|
195
|
+
- name: POD_NAME
|
|
196
|
+
valueFrom: { fieldRef: { fieldPath: metadata.name } }
|
|
197
|
+
- name: POD_NAMESPACE
|
|
198
|
+
valueFrom: { fieldRef: { fieldPath: metadata.namespace } }
|
|
199
|
+
- name: OTEL_RESOURCE_ATTRIBUTES
|
|
200
|
+
value: k8s.pod.uid=$(POD_UID),k8s.pod.name=$(POD_NAME),k8s.namespace.name=$(POD_NAMESPACE),deployment.environment.name=production
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
`service.instance.id` is then the UUIDv5 of the pod UID, the same ID every
|
|
204
|
+
libo11y implementation derives.
|
|
205
|
+
|
|
206
|
+
## Context
|
|
207
|
+
|
|
208
|
+
`createContextManager()` returns OpenTelemetry's `AsyncLocalStorage`
|
|
209
|
+
context manager, which `setup` installs. On Bun 1.3.13 it loses the active
|
|
210
|
+
context in three places:
|
|
211
|
+
|
|
212
|
+
- An async generator used as a `Bun.serve` response body
|
|
213
|
+
([oven-sh/bun#24199](https://github.com/oven-sh/bun/issues/24199)).
|
|
214
|
+
Use a `ReadableStream` body instead. `instrumentServe` still ends its
|
|
215
|
+
span correctly.
|
|
216
|
+
- A thenable returned from an async function after an `await`
|
|
217
|
+
([oven-sh/bun#34266](https://github.com/oven-sh/bun/issues/34266)).
|
|
218
|
+
- `unhandledRejection` listeners
|
|
219
|
+
([oven-sh/bun#40223](https://github.com/oven-sh/bun/issues/40223)).
|
|
220
|
+
|
|
221
|
+
Node 24 keeps the context in both of the last two cases.
|
|
222
|
+
|
|
223
|
+
## Known limitations
|
|
224
|
+
|
|
225
|
+
- Upstream's `RuntimeNodeInstrumentation` installs a require-in-the-middle
|
|
226
|
+
hook on `Module.prototype.require`. The hook stays for the life of the
|
|
227
|
+
process, even after `shutdown()`. Pass `runtimeMetrics: false` to avoid
|
|
228
|
+
it.
|
|
229
|
+
- OTLP over gRPC is not supported.
|
|
230
|
+
|
|
231
|
+
## Parity
|
|
232
|
+
|
|
233
|
+
[docs/PARITY.md](https://github.com/jamesainslie/libo11y/blob/main/docs/PARITY.md)
|
|
234
|
+
lists where the TypeScript packages match Go and where they differ, with
|
|
235
|
+
the reasons.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server context manager: OpenTelemetry's AsyncLocalStorage manager, which Bun and Node both
|
|
3
|
+
* implement. It carries the active context across timers, microtasks, await, fetch, streams and
|
|
4
|
+
* Bun.serve handlers. On Bun 1.3.x it loses the context in an async generator response body
|
|
5
|
+
* (oven-sh/bun#24199), in a thenable returned after an await (#34266) and in unhandledRejection
|
|
6
|
+
* listeners (#40223); prefer ReadableStream bodies there.
|
|
7
|
+
*/
|
|
8
|
+
import type { ContextManager } from "@opentelemetry/api";
|
|
9
|
+
/** A new AsyncLocalStorage context manager, enabled. Enabling it again is a no-op. */
|
|
10
|
+
export declare function createContextManager(): ContextManager;
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
|
|
2
|
+
/** A new AsyncLocalStorage context manager, enabled. Enabling it again is a no-op. */
|
|
3
|
+
export function createContextManager() {
|
|
4
|
+
return new AsyncLocalStorageContextManager().enable();
|
|
5
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The exporters for each signal core routes to otlp or console. Upstream's OTLP exporters read
|
|
3
|
+
* their own OTEL_EXPORTER_OTLP_* variables (endpoint, headers, timeout, compression, certificates),
|
|
4
|
+
* so they are built with no options. The metric exporter is upstream's OTLPMetricExporterBase over
|
|
5
|
+
* upstream's OTLP HTTP export delegate, configured exactly as upstream's own OTLPMetricExporter
|
|
6
|
+
* configures it, but with libo11y's serializers, which write exemplars: protobuf from this package,
|
|
7
|
+
* JSON from core. Both metric routes wrap the exporter with exemplarMetricExporter, so each
|
|
8
|
+
* collection carries the exemplar store's samples.
|
|
9
|
+
*/
|
|
10
|
+
import { type ExporterRequest, type ExporterSet } from "@libo11y/core";
|
|
11
|
+
/** Builds the exporters for every signal the configuration routes to "otlp" or "console". */
|
|
12
|
+
export declare function buildExporters(req: ExporterRequest): ExporterSet;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The exporters for each signal core routes to otlp or console. Upstream's OTLP exporters read
|
|
3
|
+
* their own OTEL_EXPORTER_OTLP_* variables (endpoint, headers, timeout, compression, certificates),
|
|
4
|
+
* so they are built with no options. The metric exporter is upstream's OTLPMetricExporterBase over
|
|
5
|
+
* upstream's OTLP HTTP export delegate, configured exactly as upstream's own OTLPMetricExporter
|
|
6
|
+
* configures it, but with libo11y's serializers, which write exemplars: protobuf from this package,
|
|
7
|
+
* JSON from core. Both metric routes wrap the exporter with exemplarMetricExporter, so each
|
|
8
|
+
* collection carries the exemplar store's samples.
|
|
9
|
+
*/
|
|
10
|
+
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
|
+
import { OTLPMetricExporterBase } from "@opentelemetry/exporter-metrics-otlp-http";
|
|
14
|
+
import { OTLPTraceExporter as OTLPJsonTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
|
|
15
|
+
import { OTLPTraceExporter as OTLPProtoTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
|
|
16
|
+
import { convertLegacyHttpOptions, createOtlpHttpExportDelegate, } from "@opentelemetry/otlp-exporter-base/node-http";
|
|
17
|
+
import { MetricsExporterMetricsHelper } from "@opentelemetry/otlp-transformer";
|
|
18
|
+
import { ConsoleLogRecordExporter } from "@opentelemetry/sdk-logs";
|
|
19
|
+
import { ConsoleMetricExporter, PeriodicExportingMetricReader, } from "@opentelemetry/sdk-metrics";
|
|
20
|
+
import { ConsoleSpanExporter } from "@opentelemetry/sdk-trace";
|
|
21
|
+
import { OtlpProtobufMetricsSerializer } from "./otlp-proto-metrics.js";
|
|
22
|
+
/** The otel.component.type upstream's OTLP HTTP metric exporter reports. */
|
|
23
|
+
const METRIC_EXPORTER_COMPONENT = "otlp_http_metric_exporter";
|
|
24
|
+
// build runs a constructor and reports a failure as Go's "o11y: building <kind>: %w".
|
|
25
|
+
function build(kind, fn) {
|
|
26
|
+
try {
|
|
27
|
+
return fn();
|
|
28
|
+
}
|
|
29
|
+
catch (err) {
|
|
30
|
+
throw new O11yError("EXPORTER", `o11y: building ${kind}: ${err instanceof Error ? err.message : String(err)}`, {
|
|
31
|
+
cause: err,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The OTLP metric exporter for protocol: upstream's construction (convertLegacyHttpOptions for
|
|
37
|
+
* METRICS and v1/metrics, so the shared and metric-specific variables apply, and the temporality
|
|
38
|
+
* preference from OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE) with libo11y's serializer.
|
|
39
|
+
*/
|
|
40
|
+
function otlpMetricExporter(protocol) {
|
|
41
|
+
const protobuf = protocol === "http/protobuf";
|
|
42
|
+
const options = convertLegacyHttpOptions({}, "METRICS", "v1/metrics", {
|
|
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));
|
|
47
|
+
}
|
|
48
|
+
function spanExporter(req) {
|
|
49
|
+
const { traces, protocol } = req.config;
|
|
50
|
+
if (traces === "console")
|
|
51
|
+
return new ConsoleSpanExporter();
|
|
52
|
+
if (traces !== "otlp")
|
|
53
|
+
return undefined;
|
|
54
|
+
return build("span exporter", () => protocol.traces === "http/json" ? new OTLPJsonTraceExporter() : new OTLPProtoTraceExporter());
|
|
55
|
+
}
|
|
56
|
+
function logExporter(req) {
|
|
57
|
+
const { logs, protocol } = req.config;
|
|
58
|
+
if (logs === "console")
|
|
59
|
+
return new ConsoleLogRecordExporter();
|
|
60
|
+
if (logs !== "otlp")
|
|
61
|
+
return undefined;
|
|
62
|
+
return build("log exporter", () => protocol.logs === "http/json" ? new OTLPJsonLogExporter() : new OTLPProtoLogExporter());
|
|
63
|
+
}
|
|
64
|
+
function metricReader(req) {
|
|
65
|
+
const { metrics, protocol, metricExport } = req.config;
|
|
66
|
+
if (metrics !== "otlp" && metrics !== "console")
|
|
67
|
+
return undefined;
|
|
68
|
+
return build("metric reader", () => {
|
|
69
|
+
const inner = metrics === "console" ? new ConsoleMetricExporter() : otlpMetricExporter(protocol.metrics);
|
|
70
|
+
// PeriodicExportingMetricReader refuses a timeout above the interval; sdk-node clamps it.
|
|
71
|
+
const exportIntervalMillis = metricExport.intervalMillis;
|
|
72
|
+
const exportTimeoutMillis = Math.min(metricExport.timeoutMillis, exportIntervalMillis);
|
|
73
|
+
return new PeriodicExportingMetricReader({
|
|
74
|
+
exporter: exemplarMetricExporter(inner, req.exemplars),
|
|
75
|
+
exportIntervalMillis,
|
|
76
|
+
exportTimeoutMillis,
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/** Builds the exporters for every signal the configuration routes to "otlp" or "console". */
|
|
81
|
+
export function buildExporters(req) {
|
|
82
|
+
const spans = spanExporter(req);
|
|
83
|
+
const reader = metricReader(req);
|
|
84
|
+
const logs = logExporter(req);
|
|
85
|
+
return {
|
|
86
|
+
...(spans === undefined ? {} : { spanExporter: spans }),
|
|
87
|
+
...(reader === undefined ? {} : { metricReader: reader }),
|
|
88
|
+
...(logs === undefined ? {} : { logExporter: logs }),
|
|
89
|
+
};
|
|
90
|
+
}
|
package/dist/fetch.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* instrumentFetch: client instrumentation for fetch, the counterpart of Go's o11yhttp.NewTransport.
|
|
3
|
+
* It wraps a fetch function and returns a new one; it never patches globalThis.fetch, and it works
|
|
4
|
+
* on Bun, whose fetch publishes none of the undici diagnostics channels Node's instrumentation reads.
|
|
5
|
+
*/
|
|
6
|
+
import type { Telemetry } from "@libo11y/core";
|
|
7
|
+
/** Options for {@link instrumentFetch}. */
|
|
8
|
+
export interface FetchOptions {
|
|
9
|
+
/** The telemetry whose providers and propagator to use. Without it, the globals setup installs. */
|
|
10
|
+
readonly telemetry?: Telemetry;
|
|
11
|
+
/**
|
|
12
|
+
* Decides per destination whether the trace context and baggage are injected. Every destination
|
|
13
|
+
* gets them by default; return false for third parties that should not see internal trace IDs.
|
|
14
|
+
* A predicate that throws is reported through the OpenTelemetry diag logger and taken as false.
|
|
15
|
+
*/
|
|
16
|
+
readonly propagate?: (url: URL) => boolean;
|
|
17
|
+
/** The peer.service attribute: the logical name of the service called. */
|
|
18
|
+
readonly peerService?: string;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Wraps fetchImpl (default: globalThis.fetch as it is now) with a CLIENT span per request, named by
|
|
22
|
+
* method, and the http.client.request.duration histogram, recorded in the span's context so its
|
|
23
|
+
* exemplar carries the trace. The span ends when the response headers arrive, or when the request
|
|
24
|
+
* fails. 4xx and 5xx responses and failures mark the span failed. The trace context is injected
|
|
25
|
+
* into a copy of the request headers; the caller's Request and init are never changed. A URL that
|
|
26
|
+
* cannot be parsed is passed to fetchImpl uninstrumented, so its own error surfaces.
|
|
27
|
+
*/
|
|
28
|
+
export declare function instrumentFetch(fetchImpl?: typeof fetch, opts?: FetchOptions): typeof fetch;
|