@xynolog/observability 0.0.0-stage → 0.8.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/LICENSE +201 -0
- package/README.md +58 -2
- package/dist/index.d.ts +92 -0
- package/dist/index.js +92 -0
- package/dist/index.js.map +1 -0
- package/dist/node.d.ts +57 -0
- package/dist/node.js +114 -0
- package/dist/node.js.map +1 -0
- package/package.json +64 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,59 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @xynolog/observability
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/xynolog/sdk/actions/workflows/ci.yml?query=branch%3Amain+is%3Asuccess+job%3A%22Test+observability%22)
|
|
4
|
+
[](https://app.codecov.io/gh/xynolog/sdk/components)
|
|
5
|
+
[](https://www.npmjs.com/package/@xynolog/observability)
|
|
6
|
+
[](https://www.npmjs.com/package/@xynolog/observability)
|
|
7
|
+
[](https://github.com/xynolog/sdk/blob/main/LICENSE)
|
|
8
|
+
|
|
9
|
+
Tracing and metrics for Xynolog's TypeScript transport and for a Node program built on it, on [OpenTelemetry](https://opentelemetry.io). It is off unless a process is given somewhere to export to: with no endpoint configured, every function here does nothing.
|
|
10
|
+
|
|
11
|
+
## Who uses it
|
|
12
|
+
|
|
13
|
+
- **[`@xynolog/http-transport`](../http-transport/README.md)** runs each request in a span and carries the trace across the wire. That is how this package comes to be in the Browser's bundle.
|
|
14
|
+
- **[`@xynolog/sdk`](../sdk/README.md)** carries the trace of a job from the request that made it to the worker that claims it.
|
|
15
|
+
|
|
16
|
+
No Xynolog service is a Node process. The gateway, the dispatcher and the Archivist are Rust and have a crate of their own for this; the Python services have `xynolog_service`.
|
|
17
|
+
|
|
18
|
+
**Building an application?** You do not need this package. The SDK's transport reports through OpenTelemetry's global API, so an application that registers a tracer of its own sees the transport's spans in its traces.
|
|
19
|
+
|
|
20
|
+
## What is in it
|
|
21
|
+
|
|
22
|
+
| Import | |
|
|
23
|
+
|---|---|
|
|
24
|
+
| `@xynolog/observability` | Runs in Node and in a browser. Spans: `withSpan`. Trace context across the bus: `getActiveTraceparent`, `extractTraceparent`, `withTraceparent`; and `withoutTrace`, for work that begins a trace of its own. `recordBusSent`, the count of the emits a client sent |
|
|
25
|
+
| `@xynolog/observability/node` | `initObservabilityNode` and `shutdownObservabilityNode`: the tracer, the meter, the exporter and the context manager of a Node process |
|
|
26
|
+
|
|
27
|
+
Each says what it does where it is defined, in [src/index.ts](src/index.ts).
|
|
28
|
+
|
|
29
|
+
## Example
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
import { initObservabilityNode } from '@xynolog/observability/node';
|
|
33
|
+
import { withSpan } from '@xynolog/observability';
|
|
34
|
+
|
|
35
|
+
// Once, at the entry point, before anything that makes a span.
|
|
36
|
+
initObservabilityNode({ serviceName: 'my-program', serviceVersion: '1.0.0' });
|
|
37
|
+
|
|
38
|
+
const length = await withSpan('read-document', async (span) => {
|
|
39
|
+
span.setAttribute('document.pages', 12);
|
|
40
|
+
return 4096;
|
|
41
|
+
});
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## What a change must keep
|
|
45
|
+
|
|
46
|
+
- **Off by default, and free when off.** With no exporter configured, the tracer and the meter are OpenTelemetry's own no-ops. Nothing here may do work, or fail, because telemetry is not set up.
|
|
47
|
+
- **The main import runs in a browser.** It imports no Node builtin. What needs Node is in `/node`.
|
|
48
|
+
- **One trace across the bus.** A request carries the active span as a W3C `traceparent` header, and a frame relayed over the stream carries it in its payload's trace field (`TRACE_FIELD` in `@xynolog/core`, generated from the bus registry). A handler continues that trace rather than starting one.
|
|
49
|
+
- **No domain logic.** The package gives the helpers and the recorder. What is worth a span or a count is decided where the work happens.
|
|
50
|
+
- **Initialized once.** `initObservabilityNode` is called at a process's entry point. A second call does nothing and returns `false`.
|
|
51
|
+
|
|
52
|
+
## Documentation
|
|
53
|
+
|
|
54
|
+
- [API reference](docs/API.md): the helpers, with an example of each.
|
|
55
|
+
- [Observability](https://github.com/xynolog/docs/blob/main/operator/administration/OBSERVABILITY.md): the variables that turn it on, and where a stack sends its telemetry.
|
|
56
|
+
|
|
57
|
+
## License
|
|
58
|
+
|
|
59
|
+
Apache-2.0
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { Span, SpanKind, Attributes } from '@opentelemetry/api';
|
|
2
|
+
export { SpanKind } from '@opentelemetry/api';
|
|
3
|
+
import { TraceCarrier } from '@xynolog/core';
|
|
4
|
+
|
|
5
|
+
/** An attribute key a row of the telemetry table lists. */
|
|
6
|
+
declare const ATTR_BUS_CHANNEL = "bus.channel";
|
|
7
|
+
/** An attribute key a row of the telemetry table lists. */
|
|
8
|
+
declare const ATTR_BUS_SCOPE = "bus.scope";
|
|
9
|
+
/** An attribute key a row of the telemetry table lists. */
|
|
10
|
+
declare const ATTR_CONTENT_FORMAT = "content.format";
|
|
11
|
+
/** An attribute key a row of the telemetry table lists. */
|
|
12
|
+
declare const ATTR_CONTENT_SIZE_BYTES = "content.size_bytes";
|
|
13
|
+
/** An attribute key a row of the telemetry table lists. */
|
|
14
|
+
declare const ATTR_CONTENT_STREAM = "content.stream";
|
|
15
|
+
/** An attribute key a row of the telemetry table lists. */
|
|
16
|
+
declare const ATTR_RESOURCE_ID = "resource.id";
|
|
17
|
+
/** An attribute key a row of the telemetry table lists. */
|
|
18
|
+
declare const ATTR_THREAD_ID = "thread.id";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @xynolog/observability — public API.
|
|
22
|
+
*
|
|
23
|
+
* Universal surface (works in Node + browser). A Node process initializes
|
|
24
|
+
* the SDK from `@xynolog/observability/node` at its entry point; the Browser
|
|
25
|
+
* initializes its own tracer (`images/browser/src/lib/tracing.ts`). Everything
|
|
26
|
+
* else uses this module.
|
|
27
|
+
*
|
|
28
|
+
* Traces and their propagation, and the one metric a client's transport
|
|
29
|
+
* exports. The public surface:
|
|
30
|
+
*
|
|
31
|
+
* - `withSpan(name, fn, options?)` — wrap an async block in a span;
|
|
32
|
+
* `options` carries `kind` and `attrs`.
|
|
33
|
+
* - `extractTraceparent(payload)` — W3C trace-context propagation across
|
|
34
|
+
* the SSE channel (a bus frame the gateway relays carries its trace in
|
|
35
|
+
* the payload field `TRACE_FIELD` names, from `@xynolog/core`).
|
|
36
|
+
* - `withTraceparent(carrier, fn)` — run `fn` with the incoming
|
|
37
|
+
* traceparent as the parent context.
|
|
38
|
+
* - `withoutTrace(fn)` — run `fn` in no trace, so that what it starts
|
|
39
|
+
* begins a trace of its own.
|
|
40
|
+
* - `getActiveTraceparent()` — read the active span's traceparent, for
|
|
41
|
+
* an outbound request's `traceparent` header.
|
|
42
|
+
* - `recordBusSent(channel, scope?)` — count an emit a client sent.
|
|
43
|
+
* - `SpanKind`, re-exported from `@opentelemetry/api`. The type of the
|
|
44
|
+
* trace field, `TraceCarrier`, is `@xynolog/core`'s.
|
|
45
|
+
*
|
|
46
|
+
* No-op when no exporter is configured: `@opentelemetry/api`'s default
|
|
47
|
+
* tracer and meter are no-ops, so `withSpan` and the recorder are
|
|
48
|
+
* essentially free until the process initializes an SDK.
|
|
49
|
+
*/
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Wrap an async block in a span. The span is started before `fn` runs and
|
|
53
|
+
* ended after it resolves or rejects; exceptions are recorded and the span
|
|
54
|
+
* status is set to ERROR. `kind` defaults to INTERNAL.
|
|
55
|
+
*/
|
|
56
|
+
declare function withSpan<T>(name: string, fn: (span: Span) => Promise<T> | T, options?: {
|
|
57
|
+
kind?: SpanKind;
|
|
58
|
+
attrs?: Attributes;
|
|
59
|
+
}): Promise<T>;
|
|
60
|
+
/**
|
|
61
|
+
* Read the active span's W3C traceparent (and tracestate). Returns
|
|
62
|
+
* `undefined` if no span is active.
|
|
63
|
+
*/
|
|
64
|
+
declare function getActiveTraceparent(): TraceCarrier | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* Strip and return the trace field (`TRACE_FIELD`) from a payload. Mutates `payload`.
|
|
67
|
+
* The field is internal plumbing and should not be visible to subscribers.
|
|
68
|
+
*/
|
|
69
|
+
declare function extractTraceparent<T extends Record<string, unknown>>(payload: T): TraceCarrier | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* Run `fn` with the given W3C traceparent set as the parent context.
|
|
72
|
+
* Any spans started inside `fn` will be children of the incoming trace.
|
|
73
|
+
* No-op if `carrier` is undefined.
|
|
74
|
+
*/
|
|
75
|
+
declare function withTraceparent<T>(carrier: TraceCarrier | undefined, fn: () => T): T;
|
|
76
|
+
/**
|
|
77
|
+
* Run `fn` in no trace: a span started inside it, and every continuation it
|
|
78
|
+
* registers, has no parent, whatever span is active where this is called. For
|
|
79
|
+
* work that is nobody's: a worker's claim, which belongs to no job, is made
|
|
80
|
+
* here even when the code that settled the job before it is inside that job's
|
|
81
|
+
* span.
|
|
82
|
+
*/
|
|
83
|
+
declare function withoutTrace<T>(fn: () => T): T;
|
|
84
|
+
/**
|
|
85
|
+
* Count an emit a client sent (`xynolog.bus.sent`,
|
|
86
|
+
* protocol/specs/src/sdk-telemetry/telemetry.json). Called at every transport `emit`
|
|
87
|
+
* site. Its own name, apart from `xynolog.bus.emit`, the gateway's count of
|
|
88
|
+
* the emits it accepted.
|
|
89
|
+
*/
|
|
90
|
+
declare function recordBusSent(channel: string, scope?: string): void;
|
|
91
|
+
|
|
92
|
+
export { ATTR_BUS_CHANNEL, ATTR_BUS_SCOPE, ATTR_CONTENT_FORMAT, ATTR_CONTENT_SIZE_BYTES, ATTR_CONTENT_STREAM, ATTR_RESOURCE_ID, ATTR_THREAD_ID, extractTraceparent, getActiveTraceparent, recordBusSent, withSpan, withTraceparent, withoutTrace };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { trace, isSpanContextValid, SpanKind, context, SpanStatusCode, propagation, ROOT_CONTEXT, metrics } from '@opentelemetry/api';
|
|
2
|
+
export { SpanKind } from '@opentelemetry/api';
|
|
3
|
+
import { setBusLogTraceIdProvider, TRACE_FIELD } from '@xynolog/core';
|
|
4
|
+
|
|
5
|
+
// src/index.ts
|
|
6
|
+
|
|
7
|
+
// src/telemetry-keys.ts
|
|
8
|
+
var ATTR_BUS_CHANNEL = "bus.channel";
|
|
9
|
+
var ATTR_BUS_SCOPE = "bus.scope";
|
|
10
|
+
var ATTR_CONTENT_FORMAT = "content.format";
|
|
11
|
+
var ATTR_CONTENT_SIZE_BYTES = "content.size_bytes";
|
|
12
|
+
var ATTR_CONTENT_STREAM = "content.stream";
|
|
13
|
+
var ATTR_RESOURCE_ID = "resource.id";
|
|
14
|
+
var ATTR_THREAD_ID = "thread.id";
|
|
15
|
+
setBusLogTraceIdProvider(() => {
|
|
16
|
+
const span = trace.getActiveSpan();
|
|
17
|
+
if (!span) return void 0;
|
|
18
|
+
const ctx = span.spanContext();
|
|
19
|
+
if (!isSpanContextValid(ctx)) return void 0;
|
|
20
|
+
return ctx.traceId;
|
|
21
|
+
});
|
|
22
|
+
var TRACER_NAME = "xynolog";
|
|
23
|
+
var tracer = () => trace.getTracer(TRACER_NAME);
|
|
24
|
+
async function withSpan(name, fn, options) {
|
|
25
|
+
const span = tracer().startSpan(name, {
|
|
26
|
+
kind: options?.kind ?? SpanKind.INTERNAL,
|
|
27
|
+
...options?.attrs ? { attributes: options.attrs } : {}
|
|
28
|
+
});
|
|
29
|
+
try {
|
|
30
|
+
return await context.with(
|
|
31
|
+
trace.setSpan(context.active(), span),
|
|
32
|
+
() => fn(span)
|
|
33
|
+
);
|
|
34
|
+
} catch (err) {
|
|
35
|
+
span.recordException(err);
|
|
36
|
+
span.setStatus({
|
|
37
|
+
code: SpanStatusCode.ERROR,
|
|
38
|
+
message: err instanceof Error ? err.message : String(err)
|
|
39
|
+
});
|
|
40
|
+
throw err;
|
|
41
|
+
} finally {
|
|
42
|
+
span.end();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function getActiveTraceparent() {
|
|
46
|
+
const carrier = {};
|
|
47
|
+
propagation.inject(context.active(), carrier);
|
|
48
|
+
const traceparent = carrier["traceparent"];
|
|
49
|
+
if (!traceparent) return void 0;
|
|
50
|
+
return carrier["tracestate"] ? { traceparent, tracestate: carrier["tracestate"] } : { traceparent };
|
|
51
|
+
}
|
|
52
|
+
function extractTraceparent(payload) {
|
|
53
|
+
const carrier = payload[TRACE_FIELD];
|
|
54
|
+
if (carrier !== void 0) {
|
|
55
|
+
delete payload[TRACE_FIELD];
|
|
56
|
+
}
|
|
57
|
+
if (!carrier || typeof carrier.traceparent !== "string") return void 0;
|
|
58
|
+
return carrier;
|
|
59
|
+
}
|
|
60
|
+
function withTraceparent(carrier, fn) {
|
|
61
|
+
if (!carrier) return fn();
|
|
62
|
+
const carrierObj = {
|
|
63
|
+
traceparent: carrier.traceparent
|
|
64
|
+
};
|
|
65
|
+
if (carrier.tracestate) carrierObj["tracestate"] = carrier.tracestate;
|
|
66
|
+
const ctx = propagation.extract(context.active(), carrierObj);
|
|
67
|
+
return context.with(ctx, fn);
|
|
68
|
+
}
|
|
69
|
+
function withoutTrace(fn) {
|
|
70
|
+
return context.with(ROOT_CONTEXT, fn);
|
|
71
|
+
}
|
|
72
|
+
var METER_NAME = "xynolog";
|
|
73
|
+
var meter = () => metrics.getMeter(METER_NAME);
|
|
74
|
+
var _busSentCounter;
|
|
75
|
+
function busSentCounter() {
|
|
76
|
+
if (!_busSentCounter) {
|
|
77
|
+
_busSentCounter = meter().createCounter("xynolog.bus.sent", {
|
|
78
|
+
description: "Emits a client sent, by channel and scope"
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return _busSentCounter;
|
|
82
|
+
}
|
|
83
|
+
function recordBusSent(channel, scope) {
|
|
84
|
+
busSentCounter().add(1, {
|
|
85
|
+
[ATTR_BUS_CHANNEL]: channel,
|
|
86
|
+
...scope ? { [ATTR_BUS_SCOPE]: scope } : {}
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export { ATTR_BUS_CHANNEL, ATTR_BUS_SCOPE, ATTR_CONTENT_FORMAT, ATTR_CONTENT_SIZE_BYTES, ATTR_CONTENT_STREAM, ATTR_RESOURCE_ID, ATTR_THREAD_ID, extractTraceparent, getActiveTraceparent, recordBusSent, withSpan, withTraceparent, withoutTrace };
|
|
91
|
+
//# sourceMappingURL=index.js.map
|
|
92
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/telemetry-keys.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;AAMO,IAAM,gBAAA,GAAmB;AAGzB,IAAM,cAAA,GAAiB;AAGvB,IAAM,mBAAA,GAAsB;AAG5B,IAAM,uBAAA,GAA0B;AAGhC,IAAM,mBAAA,GAAsB;AAG5B,IAAM,gBAAA,GAAmB;AAGzB,IAAM,cAAA,GAAiB;AC+B9B,wBAAA,CAAyB,MAAM;AAC7B,EAAA,MAAM,IAAA,GAAO,MAAM,aAAA,EAAc;AACjC,EAAA,IAAI,CAAC,MAAM,OAAO,MAAA;AAClB,EAAA,MAAM,GAAA,GAAM,KAAK,WAAA,EAAY;AAC7B,EAAA,IAAI,CAAC,kBAAA,CAAmB,GAAG,CAAA,EAAG,OAAO,MAAA;AACrC,EAAA,OAAO,GAAA,CAAI,OAAA;AACb,CAAC,CAAA;AAED,IAAM,WAAA,GAAc,SAAA;AAEpB,IAAM,MAAA,GAAS,MAAM,KAAA,CAAM,SAAA,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AAA,IACpB,GAAI,QAAQ,EAAE,CAAC,cAAc,GAAG,KAAA,KAAU;AAAC,GAC5C,CAAA;AACH","file":"index.js","sourcesContent":["// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/sdk-telemetry/telemetry.json\n// Regenerate: make generate (codegen/lib/telemetry/telemetry.ml)\n\n/** An attribute key a row of the telemetry table lists. */\nexport const ATTR_BUS_CHANNEL = 'bus.channel';\n\n/** An attribute key a row of the telemetry table lists. */\nexport const ATTR_BUS_SCOPE = 'bus.scope';\n\n/** An attribute key a row of the telemetry table lists. */\nexport const ATTR_CONTENT_FORMAT = 'content.format';\n\n/** An attribute key a row of the telemetry table lists. */\nexport const ATTR_CONTENT_SIZE_BYTES = 'content.size_bytes';\n\n/** An attribute key a row of the telemetry table lists. */\nexport const ATTR_CONTENT_STREAM = 'content.stream';\n\n/** An attribute key a row of the telemetry table lists. */\nexport const ATTR_RESOURCE_ID = 'resource.id';\n\n/** An attribute key a row of the telemetry table lists. */\nexport const ATTR_THREAD_ID = 'thread.id';\n","/**\n * @xynolog/observability — public API.\n *\n * Universal surface (works in Node + browser). A Node process initializes\n * the SDK from `@xynolog/observability/node` at its entry point; the Browser\n * initializes its own tracer (`images/browser/src/lib/tracing.ts`). Everything\n * else uses this module.\n *\n * Traces and their propagation, and the one metric a client's transport\n * exports. The public surface:\n *\n * - `withSpan(name, fn, options?)` — wrap an async block in a span;\n * `options` carries `kind` and `attrs`.\n * - `extractTraceparent(payload)` — W3C trace-context propagation across\n * the SSE channel (a bus frame the gateway relays carries its trace in\n * the payload field `TRACE_FIELD` names, from `@xynolog/core`).\n * - `withTraceparent(carrier, fn)` — run `fn` with the incoming\n * traceparent as the parent context.\n * - `withoutTrace(fn)` — run `fn` in no trace, so that what it starts\n * begins a trace of its own.\n * - `getActiveTraceparent()` — read the active span's traceparent, for\n * an outbound request's `traceparent` header.\n * - `recordBusSent(channel, scope?)` — count an emit a client sent.\n * - `SpanKind`, re-exported from `@opentelemetry/api`. The type of the\n * trace field, `TraceCarrier`, is `@xynolog/core`'s.\n *\n * No-op when no exporter is configured: `@opentelemetry/api`'s default\n * tracer and meter are no-ops, so `withSpan` and the recorder are\n * essentially free until the process initializes an SDK.\n */\n\nimport {\n context,\n isSpanContextValid,\n metrics,\n propagation,\n ROOT_CONTEXT,\n SpanKind,\n SpanStatusCode,\n trace,\n type Attributes,\n type Counter,\n type Span,\n} from '@opentelemetry/api';\nimport {\n setBusLogTraceIdProvider,\n TRACE_FIELD,\n type TraceCarrier,\n} from '@xynolog/core';\nimport { ATTR_BUS_CHANNEL, ATTR_BUS_SCOPE } from './telemetry-keys';\n\n// Wire `busLog`'s trace-id provider once at module load. When an OTel\n// SDK is initialized (and a span is active when `busLog` fires), the\n// emitted line gets a `trace=<8hex>` suffix that correlates the\n// grep-timeline with the trace UI. No-op when no SDK is active.\nsetBusLogTraceIdProvider(() => {\n const span = trace.getActiveSpan();\n if (!span) return undefined;\n const ctx = span.spanContext();\n if (!isSpanContextValid(ctx)) return undefined;\n return ctx.traceId;\n});\n\nconst TRACER_NAME = 'xynolog';\n\nconst tracer = () => trace.getTracer(TRACER_NAME);\n\n// ── withSpan ───────────────────────────────────────────────────────────\n\n/**\n * Wrap an async block in a span. The span is started before `fn` runs and\n * ended after it resolves or rejects; exceptions are recorded and the span\n * status is set to ERROR. `kind` defaults to INTERNAL.\n */\nexport async function withSpan<T>(\n name: string,\n fn: (span: Span) => Promise<T> | T,\n options?: { kind?: SpanKind; attrs?: Attributes },\n): Promise<T> {\n const span = tracer().startSpan(name, {\n kind: options?.kind ?? SpanKind.INTERNAL,\n ...(options?.attrs ? { attributes: options.attrs } : {}),\n });\n try {\n return await context.with(trace.setSpan(context.active(), span), () =>\n fn(span),\n );\n } catch (err) {\n span.recordException(err as Error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err instanceof Error ? err.message : String(err),\n });\n throw err;\n } finally {\n span.end();\n }\n}\n\n// ── Traceparent on bus payloads ────────────────────────────────────────\n\n/**\n * Read the active span's W3C traceparent (and tracestate). Returns\n * `undefined` if no span is active.\n */\nexport function getActiveTraceparent(): TraceCarrier | undefined {\n const carrier: Record<string, string> = {};\n propagation.inject(context.active(), carrier);\n const traceparent = carrier['traceparent'];\n if (!traceparent) return undefined;\n return carrier['tracestate']\n ? { traceparent, tracestate: carrier['tracestate'] }\n : { traceparent };\n}\n\n/**\n * Strip and return the trace field (`TRACE_FIELD`) from a payload. Mutates `payload`.\n * The field is internal plumbing and should not be visible to subscribers.\n */\nexport function extractTraceparent<T extends Record<string, unknown>>(\n payload: T,\n): TraceCarrier | undefined {\n const carrier = (payload as Record<string, unknown>)[TRACE_FIELD] as\n TraceCarrier | undefined;\n if (carrier !== undefined) {\n delete (payload as Record<string, unknown>)[TRACE_FIELD];\n }\n if (!carrier || typeof carrier.traceparent !== 'string') return undefined;\n return carrier;\n}\n\n/**\n * Run `fn` with the given W3C traceparent set as the parent context.\n * Any spans started inside `fn` will be children of the incoming trace.\n * No-op if `carrier` is undefined.\n */\nexport function withTraceparent<T>(\n carrier: TraceCarrier | undefined,\n fn: () => T,\n): T {\n if (!carrier) return fn();\n const carrierObj: Record<string, string> = {\n traceparent: carrier.traceparent,\n };\n if (carrier.tracestate) carrierObj['tracestate'] = carrier.tracestate;\n const ctx = propagation.extract(context.active(), carrierObj);\n return context.with(ctx, fn);\n}\n\n/**\n * Run `fn` in no trace: a span started inside it, and every continuation it\n * registers, has no parent, whatever span is active where this is called. For\n * work that is nobody's: a worker's claim, which belongs to no job, is made\n * here even when the code that settled the job before it is inside that job's\n * span.\n */\nexport function withoutTrace<T>(fn: () => T): T {\n return context.with(ROOT_CONTEXT, fn);\n}\n\n// ── Metrics ────────────────────────────────────────────────────────────\n\nconst METER_NAME = 'xynolog';\n\nconst meter = () => metrics.getMeter(METER_NAME);\n\nlet _busSentCounter: Counter | undefined;\n\nfunction busSentCounter(): Counter {\n if (!_busSentCounter) {\n _busSentCounter = meter().createCounter('xynolog.bus.sent', {\n description: 'Emits a client sent, by channel and scope',\n });\n }\n return _busSentCounter;\n}\n\n/**\n * Count an emit a client sent (`xynolog.bus.sent`,\n * protocol/specs/src/sdk-telemetry/telemetry.json). Called at every transport `emit`\n * site. Its own name, apart from `xynolog.bus.emit`, the gateway's count of\n * the emits it accepted.\n */\nexport function recordBusSent(channel: string, scope?: string): void {\n busSentCounter().add(1, {\n [ATTR_BUS_CHANNEL]: channel,\n ...(scope ? { [ATTR_BUS_SCOPE]: scope } : {}),\n });\n}\n\nexport * from './telemetry-keys';\n\n// ── Re-export from @opentelemetry/api ──────────────────────────────────\n\nexport { SpanKind } from '@opentelemetry/api';\n"]}
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node SDK initialization. Call once at the process entry point.
|
|
3
|
+
*
|
|
4
|
+
* Configuration is via standard `OTEL_*` env vars:
|
|
5
|
+
* - `OTEL_SERVICE_NAME` — service identity (e.g. `my-program`)
|
|
6
|
+
* - `OTEL_EXPORTER_OTLP_ENDPOINT` — collector endpoint (HTTP)
|
|
7
|
+
* - `OTEL_TRACES_SAMPLER` — sampler (default: `parentbased_always_on`)
|
|
8
|
+
* - `OTEL_TRACES_SAMPLER_ARG` — sampler ratio (default: `1.0`)
|
|
9
|
+
* - `OTEL_METRICS_EXPORTER` — `console` sends metrics to the process's output
|
|
10
|
+
* - `OTEL_METRIC_EXPORT_INTERVAL` — metric export interval in ms (default: 30000)
|
|
11
|
+
* - `OTEL_CONSOLE_EXPORTER=true` — dev-only: emit spans + metrics to the process's output
|
|
12
|
+
* - `OTEL_SDK_DISABLED=true` — skip initialization entirely
|
|
13
|
+
*
|
|
14
|
+
* **Off-by-default invariant**: with neither `OTEL_EXPORTER_OTLP_ENDPOINT`
|
|
15
|
+
* nor `OTEL_CONSOLE_EXPORTER=true` set, this function is a no-op and the
|
|
16
|
+
* `@opentelemetry/api` no-op tracer takes over. This avoids accidentally
|
|
17
|
+
* flooding production logs when an operator deploys
|
|
18
|
+
* without configuring an exporter.
|
|
19
|
+
*
|
|
20
|
+
* Implementation note: this module wires `TracerProvider` (from
|
|
21
|
+
* `@opentelemetry/sdk-trace`) and `MeterProvider` (from
|
|
22
|
+
* `@opentelemetry/sdk-metrics`) directly, plus
|
|
23
|
+
* `AsyncLocalStorageContextManager` for Node async-context propagation.
|
|
24
|
+
* `sdk-trace` reads no environment variable, so the sampler is read here.
|
|
25
|
+
* `@opentelemetry/sdk-node` would read them all, and brings with it the
|
|
26
|
+
* gRPC, protobuf, Zipkin and Prometheus exporters and the instrumentation
|
|
27
|
+
* framework, which this package does not use.
|
|
28
|
+
*/
|
|
29
|
+
interface NodeObservabilityConfig {
|
|
30
|
+
/** Service identity (e.g. `my-program`). Overridden by `OTEL_SERVICE_NAME`. */
|
|
31
|
+
serviceName: string;
|
|
32
|
+
/** Service version: the program's own, as its package names it. */
|
|
33
|
+
serviceVersion: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Which exporter metrics use. `console` wins even with an OTLP endpoint set —
|
|
37
|
+
* the readout for a bare process or CI with no collector; traces unaffected.
|
|
38
|
+
* Any other value (incl. unrecognised) leaves the endpoint to decide, so an
|
|
39
|
+
* unknown value cannot silently disable metrics. Exported and pure so tests
|
|
40
|
+
* assert the choice without mocking the exporter modules.
|
|
41
|
+
*/
|
|
42
|
+
declare function metricsExporterKind(endpoint: string | undefined, requested: string | undefined): 'otlp' | 'console';
|
|
43
|
+
/**
|
|
44
|
+
* Initialize OTel for the current process. Wires up both tracing and
|
|
45
|
+
* metrics. Idempotent — calling twice is a no-op. Returns `true` if the
|
|
46
|
+
* SDK started, `false` if disabled, no exporter is configured, or
|
|
47
|
+
* already initialized.
|
|
48
|
+
*
|
|
49
|
+
* Metrics export at `OTEL_METRIC_EXPORT_INTERVAL` ms (default 30s) to
|
|
50
|
+
* the same `OTEL_EXPORTER_OTLP_ENDPOINT` as traces.
|
|
51
|
+
*/
|
|
52
|
+
declare function initObservabilityNode(config: NodeObservabilityConfig): boolean;
|
|
53
|
+
/** Force-flush + shutdown both SDKs. Test cleanup, not production. */
|
|
54
|
+
declare function shutdownObservabilityNode(): Promise<void>;
|
|
55
|
+
|
|
56
|
+
export { initObservabilityNode, metricsExporterKind, shutdownObservabilityNode };
|
|
57
|
+
export type { NodeObservabilityConfig };
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { context, trace, propagation, metrics, diag } from '@opentelemetry/api';
|
|
2
|
+
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
|
|
3
|
+
import { W3CTraceContextPropagator } from '@opentelemetry/core';
|
|
4
|
+
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
|
|
5
|
+
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
|
|
6
|
+
import { resourceFromAttributes } from '@opentelemetry/resources';
|
|
7
|
+
import { ConsoleMetricExporter, MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';
|
|
8
|
+
import { ConsoleSpanExporter, TracerProvider, BatchSpanProcessor, ParentBasedSampler, AlwaysOnSampler, TraceIdRatioBasedSampler, AlwaysOffSampler } from '@opentelemetry/sdk-trace';
|
|
9
|
+
import { ATTR_SERVICE_VERSION, ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
|
|
10
|
+
|
|
11
|
+
// src/node.ts
|
|
12
|
+
var tracerProviderInstance;
|
|
13
|
+
var meterProviderInstance;
|
|
14
|
+
var DEFAULT_METRIC_EXPORT_INTERVAL_MS = 3e4;
|
|
15
|
+
function metricsExporterKind(endpoint, requested) {
|
|
16
|
+
if (requested === "console") return "console";
|
|
17
|
+
return endpoint ? "otlp" : "console";
|
|
18
|
+
}
|
|
19
|
+
function samplerFromEnvironment(name, arg) {
|
|
20
|
+
const ratio = () => {
|
|
21
|
+
const value = arg === void 0 || arg.trim() === "" ? Number.NaN : Number(arg.trim());
|
|
22
|
+
if (value >= 0 && value <= 1) return value;
|
|
23
|
+
diag.error(
|
|
24
|
+
`OTEL_TRACES_SAMPLER_ARG=${JSON.stringify(arg)} is no ratio from 0 to 1; using 1`
|
|
25
|
+
);
|
|
26
|
+
return 1;
|
|
27
|
+
};
|
|
28
|
+
const named = name === void 0 || name.trim() === "" ? "parentbased_always_on" : name.trim();
|
|
29
|
+
switch (named) {
|
|
30
|
+
case "always_on":
|
|
31
|
+
return new AlwaysOnSampler();
|
|
32
|
+
case "always_off":
|
|
33
|
+
return new AlwaysOffSampler();
|
|
34
|
+
case "traceidratio":
|
|
35
|
+
return new TraceIdRatioBasedSampler(ratio());
|
|
36
|
+
case "parentbased_always_on":
|
|
37
|
+
return new ParentBasedSampler({ root: new AlwaysOnSampler() });
|
|
38
|
+
case "parentbased_always_off":
|
|
39
|
+
return new ParentBasedSampler({ root: new AlwaysOffSampler() });
|
|
40
|
+
case "parentbased_traceidratio":
|
|
41
|
+
return new ParentBasedSampler({
|
|
42
|
+
root: new TraceIdRatioBasedSampler(ratio())
|
|
43
|
+
});
|
|
44
|
+
default:
|
|
45
|
+
diag.error(
|
|
46
|
+
`OTEL_TRACES_SAMPLER=${JSON.stringify(named)} is no sampler this package makes; using parentbased_always_on`
|
|
47
|
+
);
|
|
48
|
+
return new ParentBasedSampler({ root: new AlwaysOnSampler() });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function initObservabilityNode(config) {
|
|
52
|
+
if (tracerProviderInstance) return false;
|
|
53
|
+
if (process.env["OTEL_SDK_DISABLED"] === "true") return false;
|
|
54
|
+
const endpoint = process.env["OTEL_EXPORTER_OTLP_ENDPOINT"];
|
|
55
|
+
const useConsole = process.env["OTEL_CONSOLE_EXPORTER"] === "true";
|
|
56
|
+
if (!endpoint && !useConsole) return false;
|
|
57
|
+
const resource = resourceFromAttributes({
|
|
58
|
+
[ATTR_SERVICE_NAME]: process.env["OTEL_SERVICE_NAME"] ?? config.serviceName,
|
|
59
|
+
[ATTR_SERVICE_VERSION]: config.serviceVersion
|
|
60
|
+
});
|
|
61
|
+
const traceExporter = endpoint ? new OTLPTraceExporter() : new ConsoleSpanExporter();
|
|
62
|
+
tracerProviderInstance = new TracerProvider({
|
|
63
|
+
resource,
|
|
64
|
+
sampler: samplerFromEnvironment(
|
|
65
|
+
process.env["OTEL_TRACES_SAMPLER"],
|
|
66
|
+
process.env["OTEL_TRACES_SAMPLER_ARG"]
|
|
67
|
+
),
|
|
68
|
+
spanProcessors: [new BatchSpanProcessor({ exporter: traceExporter })]
|
|
69
|
+
});
|
|
70
|
+
context.setGlobalContextManager(
|
|
71
|
+
new AsyncLocalStorageContextManager().enable()
|
|
72
|
+
);
|
|
73
|
+
trace.setGlobalTracerProvider(tracerProviderInstance);
|
|
74
|
+
propagation.setGlobalPropagator(new W3CTraceContextPropagator());
|
|
75
|
+
const metricExporter = metricsExporterKind(endpoint, process.env["OTEL_METRICS_EXPORTER"]) === "console" ? new ConsoleMetricExporter() : new OTLPMetricExporter();
|
|
76
|
+
const intervalRaw = process.env["OTEL_METRIC_EXPORT_INTERVAL"];
|
|
77
|
+
const exportIntervalMillis = intervalRaw ? Number.parseInt(intervalRaw, 10) : DEFAULT_METRIC_EXPORT_INTERVAL_MS;
|
|
78
|
+
meterProviderInstance = new MeterProvider({
|
|
79
|
+
resource,
|
|
80
|
+
readers: [
|
|
81
|
+
new PeriodicExportingMetricReader({
|
|
82
|
+
exporter: metricExporter,
|
|
83
|
+
exportIntervalMillis: Number.isFinite(exportIntervalMillis) && exportIntervalMillis > 0 ? exportIntervalMillis : DEFAULT_METRIC_EXPORT_INTERVAL_MS
|
|
84
|
+
})
|
|
85
|
+
]
|
|
86
|
+
});
|
|
87
|
+
metrics.setGlobalMeterProvider(meterProviderInstance);
|
|
88
|
+
const shutdown = () => {
|
|
89
|
+
Promise.all([
|
|
90
|
+
tracerProviderInstance?.shutdown().catch(() => {
|
|
91
|
+
}),
|
|
92
|
+
meterProviderInstance?.shutdown().catch(() => {
|
|
93
|
+
})
|
|
94
|
+
]).finally(() => {
|
|
95
|
+
tracerProviderInstance = void 0;
|
|
96
|
+
meterProviderInstance = void 0;
|
|
97
|
+
});
|
|
98
|
+
};
|
|
99
|
+
process.once("SIGTERM", shutdown);
|
|
100
|
+
process.once("SIGINT", shutdown);
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
async function shutdownObservabilityNode() {
|
|
104
|
+
await Promise.all([
|
|
105
|
+
tracerProviderInstance?.shutdown(),
|
|
106
|
+
meterProviderInstance?.shutdown()
|
|
107
|
+
]);
|
|
108
|
+
tracerProviderInstance = void 0;
|
|
109
|
+
meterProviderInstance = void 0;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export { initObservabilityNode, metricsExporterKind, shutdownObservabilityNode };
|
|
113
|
+
//# sourceMappingURL=node.js.map
|
|
114
|
+
//# sourceMappingURL=node.js.map
|
package/dist/node.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/node.ts"],"names":[],"mappings":";;;;;;;;;;;AA8DA,IAAI,sBAAA;AACJ,IAAI,qBAAA;AAMJ,IAAM,iCAAA,GAAoC,GAAA;AASnC,SAAS,mBAAA,CACd,UACA,SAAA,EACoB;AACpB,EAAA,IAAI,SAAA,KAAc,WAAW,OAAO,SAAA;AACpC,EAAA,OAAO,WAAW,MAAA,GAAS,SAAA;AAC7B;AASA,SAAS,sBAAA,CACP,MACA,GAAA,EACS;AACT,EAAA,MAAM,QAAQ,MAAc;AAC1B,IAAA,MAAM,KAAA,GACJ,GAAA,KAAQ,MAAA,IAAa,GAAA,CAAI,IAAA,EAAK,KAAM,EAAA,GAAK,MAAA,CAAO,GAAA,GAAM,MAAA,CAAO,GAAA,CAAI,IAAA,EAAM,CAAA;AACzE,IAAA,IAAI,KAAA,IAAS,CAAA,IAAK,KAAA,IAAS,CAAA,EAAG,OAAO,KAAA;AACrC,IAAA,IAAA,CAAK,KAAA;AAAA,MACH,CAAA,wBAAA,EA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Aa,EAAE,CAAA,GAC/B,iCAAA;AAEJ,EAAA,qBAAA,GAAwB,IAAI,aAAA,CAAc;AAAA,IACxC,QAAA;AAAA,IACA,OAAA,EAAS;AAAA,MACP,IAAI,6BAAA,CAA8B;AAAA,QAChC,QAAA,EAAU,cAAA;AAAA,QACV,sBACE,MAAA,CAAO,QAAA,CAAS,oBAAoB,CAAA,IAAK,oBAAA,GAAuB,IAC5D,oBAAA,GACA;AAAA,OACP;AAAA;AACH,GACD,CAAA;AACD,EAAA,OAAA,CAAQ,uBAAuB,qBAAqB,CAAA;AAGpD,EAAA,MAAM,WAAW,MAAM;AACrB,IAAA,OAAA,CAAQ,GAAA,CAAI;AAAA,MACV,sBAAA,EAAwB,QAAA,EAAS,CAAE,KAAA,CAAM,MAAM;AAAA,MAAC,CAAC,CAAA;AAAA,MACjD,qBAAA,EAAuB,QAAA,EAAS,CAAE,KAAA,CAAM,MAAM;AAAA,MAAC,CAAC;AAAA,KACjD,CAAA,CAAE,OAAA,CAAQ,MAAM;AACf,MAAA,sBAAA,GAAyB,MAAA;AACzB,MAAA,qBAAA,GAAwB,MAAA;AAAA,IAC1B,CAAC,CAAA;AAAA,EACH,CAAA;AACA,EAAA,OAAA,CAAQ,IAAA,CAAK,WAAW,QAAQ,CAAA;AAChC,EAAA,OAAA,CAAQ,IAAA,CAAK,UAAU,QAAQ,CAAA;AAE/B,EAAA,OAAO,IAAA;AACT;AAGA,eAAsB,yBAAA,GAA2C;AAC/D,EAAA,MAAM,QAAQ,GAAA,CAAI;AAAA,IAChB,wBAAwB,QAAA,EAAS;AAAA,IACjC,uBAAuB,QAAA;AAAS,GACjC,CAAA;AACD,EAAA,sBAAA,GAAyB,MAAA;AACzB,EAAA,qBAAA,GAAwB,MAAA;AAC1B","file":"node.js","sourcesContent":["/**\n * Node SDK initialization. Call once at the process entry point.\n *\n * Configuration is via standard `OTEL_*` env vars:\n * - `OTEL_SERVICE_NAME` — service identity (e.g. `my-program`)\n * - `OTEL_EXPORTER_OTLP_ENDPOINT` — collector endpoint (HTTP)\n * - `OTEL_TRACES_SAMPLER` — sampler (default: `parentbased_always_on`)\n * - `OTEL_TRACES_SAMPLER_ARG` — sampler ratio (default: `1.0`)\n * - `OTEL_METRICS_EXPORTER` — `console` sends metrics to the process's output\n * - `OTEL_METRIC_EXPORT_INTERVAL` — metric export interval in ms (default: 30000)\n * - `OTEL_CONSOLE_EXPORTER=true` — dev-only: emit spans + metrics to the process's output\n * - `OTEL_SDK_DISABLED=true` — skip initialization entirely\n *\n * **Off-by-default invariant**: with neither `OTEL_EXPORTER_OTLP_ENDPOINT`\n * nor `OTEL_CONSOLE_EXPORTER=true` set, this function is a no-op and the\n * `@opentelemetry/api` no-op tracer takes over. This avoids accidentally\n * flooding production logs when an operator deploys\n * without configuring an exporter.\n *\n * Implementation note: this module wires `TracerProvider` (from\n * `@opentelemetry/sdk-trace`) and `MeterProvider` (from\n * `@opentelemetry/sdk-metrics`) directly, plus\n * `AsyncLocalStorageContextManager` for Node async-context propagation.\n * `sdk-trace` reads no environment variable, so the sampler is read here.\n * `@opentelemetry/sdk-node` would read them all, and brings with it the\n * gRPC, protobuf, Zipkin and Prometheus exporters and the instrumentation\n * framework, which this package does not use.\n */\n\nimport { context, diag, metrics, propagation, trace } from '@opentelemetry/api';\nimport { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';\nimport { W3CTraceContextPropagator } from '@opentelemetry/core';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { resourceFromAttributes } from '@opentelemetry/resources';\nimport {\n ConsoleMetricExporter,\n MeterProvider,\n PeriodicExportingMetricReader,\n} from '@opentelemetry/sdk-metrics';\nimport {\n AlwaysOffSampler,\n AlwaysOnSampler,\n BatchSpanProcessor,\n ConsoleSpanExporter,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n TracerProvider,\n type Sampler,\n} from '@opentelemetry/sdk-trace';\nimport {\n ATTR_SERVICE_NAME,\n ATTR_SERVICE_VERSION,\n} from '@opentelemetry/semantic-conventions';\n\nexport interface NodeObservabilityConfig {\n /** Service identity (e.g. `my-program`). Overridden by `OTEL_SERVICE_NAME`. */\n serviceName: string;\n /** Service version: the program's own, as its package names it. */\n serviceVersion: string;\n}\n\nlet tracerProviderInstance: TracerProvider | undefined;\nlet meterProviderInstance: MeterProvider | undefined;\n\n/**\n * Default metric export interval. 30s mirrors the SDK default and gives\n * operators enough granularity without flooding the collector.\n */\nconst DEFAULT_METRIC_EXPORT_INTERVAL_MS = 30_000;\n\n/**\n * Which exporter metrics use. `console` wins even with an OTLP endpoint set —\n * the readout for a bare process or CI with no collector; traces unaffected.\n * Any other value (incl. unrecognised) leaves the endpoint to decide, so an\n * unknown value cannot silently disable metrics. Exported and pure so tests\n * assert the choice without mocking the exporter modules.\n */\nexport function metricsExporterKind(\n endpoint: string | undefined,\n requested: string | undefined,\n): 'otlp' | 'console' {\n if (requested === 'console') return 'console';\n return endpoint ? 'otlp' : 'console';\n}\n\n/**\n * The sampler `OTEL_TRACES_SAMPLER` names, and the ratio\n * `OTEL_TRACES_SAMPLER_ARG` gives the two that take one, as the\n * OpenTelemetry SDK configuration spec defines them. A value unset, unknown\n * or out of range is logged and treated as unset, as the spec requires:\n * `parentbased_always_on`, and a ratio of 1.\n */\nfunction samplerFromEnvironment(\n name: string | undefined,\n arg: string | undefined,\n): Sampler {\n const ratio = (): number => {\n const value =\n arg === undefined || arg.trim() === '' ? Number.NaN : Number(arg.trim());\n if (value >= 0 && value <= 1) return value;\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${JSON.stringify(arg)} is no ratio from 0 to 1; using 1`,\n );\n return 1;\n };\n const named =\n name === undefined || name.trim() === ''\n ? 'parentbased_always_on'\n : name.trim();\n switch (named) {\n case 'always_on':\n return new AlwaysOnSampler();\n case 'always_off':\n return new AlwaysOffSampler();\n case 'traceidratio':\n return new TraceIdRatioBasedSampler(ratio());\n case 'parentbased_always_on':\n return new ParentBasedSampler({ root: new AlwaysOnSampler() });\n case 'parentbased_always_off':\n return new ParentBasedSampler({ root: new AlwaysOffSampler() });\n case 'parentbased_traceidratio':\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(ratio()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER=${JSON.stringify(named)} is no sampler this package makes; using parentbased_always_on`,\n );\n return new ParentBasedSampler({ root: new AlwaysOnSampler() });\n }\n}\n\n/**\n * Initialize OTel for the current process. Wires up both tracing and\n * metrics. Idempotent — calling twice is a no-op. Returns `true` if the\n * SDK started, `false` if disabled, no exporter is configured, or\n * already initialized.\n *\n * Metrics export at `OTEL_METRIC_EXPORT_INTERVAL` ms (default 30s) to\n * the same `OTEL_EXPORTER_OTLP_ENDPOINT` as traces.\n */\nexport function initObservabilityNode(\n config: NodeObservabilityConfig,\n): boolean {\n if (tracerProviderInstance) return false;\n if (process.env['OTEL_SDK_DISABLED'] === 'true') return false;\n\n const endpoint = process.env['OTEL_EXPORTER_OTLP_ENDPOINT'];\n const useConsole = process.env['OTEL_CONSOLE_EXPORTER'] === 'true';\n\n // No exporter configured = no SDK init. The `@opentelemetry/api`\n // no-op tracer takes over; `withSpan` still runs `fn` but emits\n // nothing, `getActiveSpan()` returns a sentinel. Avoids flooding\n // production stderr when no collector endpoint is set.\n if (!endpoint && !useConsole) return false;\n\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: process.env['OTEL_SERVICE_NAME'] ?? config.serviceName,\n [ATTR_SERVICE_VERSION]: config.serviceVersion,\n });\n\n // Trace SDK\n const traceExporter = endpoint\n ? new OTLPTraceExporter()\n : new ConsoleSpanExporter();\n tracerProviderInstance = new TracerProvider({\n resource,\n sampler: samplerFromEnvironment(\n process.env['OTEL_TRACES_SAMPLER'],\n process.env['OTEL_TRACES_SAMPLER_ARG'],\n ),\n spanProcessors: [new BatchSpanProcessor({ exporter: traceExporter })],\n });\n\n // Async-context propagation across `await` boundaries — what NodeSDK\n // installs internally.\n context.setGlobalContextManager(\n new AsyncLocalStorageContextManager().enable(),\n );\n trace.setGlobalTracerProvider(tracerProviderInstance);\n\n // W3C trace-context propagator. Without this, `propagation.inject`\n // and `propagation.extract` walk an empty propagator chain and\n // silently do nothing — which means traceparent never makes it onto\n // outgoing HTTP headers or the trace field of SSE payloads, and cross-service\n // traces stay disconnected. NodeSDK registers this for you; a bare\n // TracerProvider does not.\n propagation.setGlobalPropagator(new W3CTraceContextPropagator());\n\n // Traces follow the endpoint; metrics additionally honour OTEL_METRICS_EXPORTER.\n const metricExporter =\n metricsExporterKind(endpoint, process.env['OTEL_METRICS_EXPORTER']) ===\n 'console'\n ? new ConsoleMetricExporter()\n : new OTLPMetricExporter();\n const intervalRaw = process.env['OTEL_METRIC_EXPORT_INTERVAL'];\n const exportIntervalMillis = intervalRaw\n ? Number.parseInt(intervalRaw, 10)\n : DEFAULT_METRIC_EXPORT_INTERVAL_MS;\n\n meterProviderInstance = new MeterProvider({\n resource,\n readers: [\n new PeriodicExportingMetricReader({\n exporter: metricExporter,\n exportIntervalMillis:\n Number.isFinite(exportIntervalMillis) && exportIntervalMillis > 0\n ? exportIntervalMillis\n : DEFAULT_METRIC_EXPORT_INTERVAL_MS,\n }),\n ],\n });\n metrics.setGlobalMeterProvider(meterProviderInstance);\n\n // Flush traces + metrics on shutdown so nothing is lost on SIGTERM/SIGINT.\n const shutdown = () => {\n Promise.all([\n tracerProviderInstance?.shutdown().catch(() => {}),\n meterProviderInstance?.shutdown().catch(() => {}),\n ]).finally(() => {\n tracerProviderInstance = undefined;\n meterProviderInstance = undefined;\n });\n };\n process.once('SIGTERM', shutdown);\n process.once('SIGINT', shutdown);\n\n return true;\n}\n\n/** Force-flush + shutdown both SDKs. Test cleanup, not production. */\nexport async function shutdownObservabilityNode(): Promise<void> {\n await Promise.all([\n tracerProviderInstance?.shutdown(),\n meterProviderInstance?.shutdown(),\n ]);\n tracerProviderInstance = undefined;\n meterProviderInstance = undefined;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xynolog/observability",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.8.0",
|
|
4
|
+
"description": "OpenTelemetry tracing and metrics for Xynolog's TypeScript transport. Node process-init helpers, a withSpan wrapper, W3C trace-context propagation across the bus, and the count of the emits a client sent. No-op when no exporter is configured.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./node": {
|
|
15
|
+
"types": "./dist/node.d.ts",
|
|
16
|
+
"import": "./dist/node.js",
|
|
17
|
+
"default": "./dist/node.js"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=24.15.0"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/xynolog/sdk.git",
|
|
33
|
+
"directory": "typescript/observability"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"typecheck": "tsc --noEmit",
|
|
37
|
+
"build": "npm run typecheck && tsup && tsc -p tsconfig.build.json && rollup -c rollup.dts.config.mjs && rm -rf dist-types",
|
|
38
|
+
"watch": "tsup --watch",
|
|
39
|
+
"clean": "rm -rf dist *.tsbuildinfo",
|
|
40
|
+
"test": "vitest run",
|
|
41
|
+
"test:coverage": "vitest run --coverage",
|
|
42
|
+
"test:watch": "vitest"
|
|
43
|
+
},
|
|
44
|
+
"author": "Xynolog Team",
|
|
45
|
+
"license": "Apache-2.0",
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@vitest/coverage-v8": "^5.0.5",
|
|
48
|
+
"rollup": "^4.67.5",
|
|
49
|
+
"rollup-plugin-dts": "^6.4.1",
|
|
50
|
+
"tsup": "^9.0.0",
|
|
51
|
+
"typescript": "^6.0.2",
|
|
52
|
+
"vitest": "^5.1.0"
|
|
53
|
+
},
|
|
54
|
+
"dependencies": {
|
|
55
|
+
"@opentelemetry/api": "^1.10.0",
|
|
56
|
+
"@opentelemetry/context-async-hooks": "^3.0.0",
|
|
57
|
+
"@opentelemetry/core": "^3.0.0",
|
|
58
|
+
"@opentelemetry/exporter-metrics-otlp-http": "^0.301.1",
|
|
59
|
+
"@opentelemetry/exporter-trace-otlp-http": "^0.301.1",
|
|
60
|
+
"@opentelemetry/resources": "^3.0.0",
|
|
61
|
+
"@opentelemetry/sdk-metrics": "^3.0.0",
|
|
62
|
+
"@opentelemetry/sdk-trace": "^3.0.0",
|
|
63
|
+
"@opentelemetry/semantic-conventions": "^1.44.0",
|
|
64
|
+
"@xynolog/core": "0.8.0"
|
|
65
|
+
}
|
|
66
|
+
}
|