@watchtowerobservability/node 0.0.0-stage → 0.2.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 +202 -0
- package/README.md +121 -2
- package/dist/cjs/buffer.d.ts +49 -0
- package/dist/cjs/buffer.js +134 -0
- package/dist/cjs/errors.d.ts +17 -0
- package/dist/cjs/errors.js +55 -0
- package/dist/cjs/index.d.ts +120 -0
- package/dist/cjs/index.js +302 -0
- package/dist/cjs/integrations/azure-functions.d.ts +18 -0
- package/dist/cjs/integrations/azure-functions.js +97 -0
- package/dist/cjs/integrations/express.d.ts +25 -0
- package/dist/cjs/integrations/express.js +58 -0
- package/dist/cjs/integrations/fastify.d.ts +6 -0
- package/dist/cjs/integrations/fastify.js +44 -0
- package/dist/cjs/integrations/genai-agents.d.ts +36 -0
- package/dist/cjs/integrations/genai-agents.js +124 -0
- package/dist/cjs/integrations/genai-stream.d.ts +19 -0
- package/dist/cjs/integrations/genai-stream.js +135 -0
- package/dist/cjs/integrations/genai.d.ts +18 -0
- package/dist/cjs/integrations/genai.js +150 -0
- package/dist/cjs/integrations/koa.d.ts +19 -0
- package/dist/cjs/integrations/koa.js +34 -0
- package/dist/cjs/integrations/lambda.d.ts +11 -0
- package/dist/cjs/integrations/lambda.js +68 -0
- package/dist/cjs/integrations/logs.d.ts +10 -0
- package/dist/cjs/integrations/logs.js +77 -0
- package/dist/cjs/integrations/nestjs.d.ts +16 -0
- package/dist/cjs/integrations/nestjs.js +30 -0
- package/dist/cjs/integrations/next.d.ts +11 -0
- package/dist/cjs/integrations/next.js +59 -0
- package/dist/cjs/integrations/prisma.d.ts +3 -0
- package/dist/cjs/integrations/prisma.js +33 -0
- package/dist/cjs/integrations/util.d.ts +9 -0
- package/dist/cjs/integrations/util.js +37 -0
- package/dist/cjs/jest.d.ts +21 -0
- package/dist/cjs/jest.js +45 -0
- package/dist/cjs/load.d.ts +1 -0
- package/dist/cjs/load.js +11 -0
- package/dist/cjs/metrics.d.ts +10 -0
- package/dist/cjs/metrics.js +81 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/payload.d.ts +42 -0
- package/dist/cjs/payload.js +145 -0
- package/dist/cjs/probes.d.ts +97 -0
- package/dist/cjs/probes.js +422 -0
- package/dist/cjs/profiling.d.ts +81 -0
- package/dist/cjs/profiling.js +253 -0
- package/dist/cjs/reporter-core.d.ts +32 -0
- package/dist/cjs/reporter-core.js +102 -0
- package/dist/cjs/test-plan.d.ts +93 -0
- package/dist/cjs/test-plan.js +262 -0
- package/dist/cjs/vitest.d.ts +27 -0
- package/dist/cjs/vitest.js +52 -0
- package/dist/esm/buffer.d.ts +49 -0
- package/dist/esm/buffer.js +92 -0
- package/dist/esm/errors.d.ts +17 -0
- package/dist/esm/errors.js +50 -0
- package/dist/esm/index.d.ts +120 -0
- package/dist/esm/index.js +251 -0
- package/dist/esm/integrations/azure-functions.d.ts +18 -0
- package/dist/esm/integrations/azure-functions.js +60 -0
- package/dist/esm/integrations/express.d.ts +25 -0
- package/dist/esm/integrations/express.js +54 -0
- package/dist/esm/integrations/fastify.d.ts +6 -0
- package/dist/esm/integrations/fastify.js +41 -0
- package/dist/esm/integrations/genai-agents.d.ts +36 -0
- package/dist/esm/integrations/genai-agents.js +118 -0
- package/dist/esm/integrations/genai-stream.d.ts +19 -0
- package/dist/esm/integrations/genai-stream.js +130 -0
- package/dist/esm/integrations/genai.d.ts +18 -0
- package/dist/esm/integrations/genai.js +138 -0
- package/dist/esm/integrations/koa.d.ts +19 -0
- package/dist/esm/integrations/koa.js +31 -0
- package/dist/esm/integrations/lambda.d.ts +11 -0
- package/dist/esm/integrations/lambda.js +32 -0
- package/dist/esm/integrations/logs.d.ts +10 -0
- package/dist/esm/integrations/logs.js +40 -0
- package/dist/esm/integrations/nestjs.d.ts +16 -0
- package/dist/esm/integrations/nestjs.js +26 -0
- package/dist/esm/integrations/next.d.ts +11 -0
- package/dist/esm/integrations/next.js +22 -0
- package/dist/esm/integrations/prisma.d.ts +3 -0
- package/dist/esm/integrations/prisma.js +30 -0
- package/dist/esm/integrations/util.d.ts +9 -0
- package/dist/esm/integrations/util.js +32 -0
- package/dist/esm/jest.d.ts +21 -0
- package/dist/esm/jest.js +41 -0
- package/dist/esm/load.d.ts +1 -0
- package/dist/esm/load.js +5 -0
- package/dist/esm/metrics.d.ts +10 -0
- package/dist/esm/metrics.js +44 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/payload.d.ts +42 -0
- package/dist/esm/payload.js +131 -0
- package/dist/esm/probes.d.ts +97 -0
- package/dist/esm/probes.js +412 -0
- package/dist/esm/profiling.d.ts +81 -0
- package/dist/esm/profiling.js +242 -0
- package/dist/esm/reporter-core.d.ts +32 -0
- package/dist/esm/reporter-core.js +63 -0
- package/dist/esm/test-plan.d.ts +93 -0
- package/dist/esm/test-plan.js +248 -0
- package/dist/esm/vitest.d.ts +27 -0
- package/dist/esm/vitest.js +48 -0
- package/package.json +219 -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,122 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @watchtowerobservability/node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/watchtowerobservability/watchtower-node/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
GitHub Packages needs a token with `read:packages` even for public packages:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @watchtowerobservability/node
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or install the attested tarball from a release without a token:
|
|
14
|
+
`npm install https://github.com/watchtowerobservability/watchtower-node/releases/download/v0.2.0/watchtowerobservability-node-0.2.0.tgz`.
|
|
15
|
+
|
|
16
|
+
Written in TypeScript and shipped as both ESM and CommonJS (`import` and `require` both work); the `.d.ts`
|
|
17
|
+
typings are generated from the source. A thin layer over the OpenTelemetry Node SDK (ruling L1): `Authorization: Bearer` header, endpoint default (`WT_OTLP_ENDPOINT`), disk offline buffer,
|
|
18
|
+
`wt.*`-safe resource attributes, redaction hook, `getPrompt`, `score`, `evaluate`, `observe`.
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import * as wt from '@watchtowerobservability/node'; // or: const wt = require('@watchtowerobservability/node');
|
|
22
|
+
wt.init({ apiKey: process.env.WT_INGEST_KEY, project: process.env.WT_PROJECT_ID, bufferDir: '.wt-buffer' });
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Quick start
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import * as wt from '@watchtowerobservability/node'; // or: const wt = require('@watchtowerobservability/node');
|
|
29
|
+
wt.init({}); // WT_INGEST_KEY, WT_SERVICE, WT_ENVIRONMENT, WT_RELEASE from env
|
|
30
|
+
const traceId = wt.captureException(new Error('oops')); // also: uncaught errors and unhandled rejections
|
|
31
|
+
wt.log('info', 'started', { port: 3000 }); // OTLP log, linked to the active trace
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`init` hooks `uncaughtException` and `unhandledRejection` (pass `captureProcessErrors: false` to opt out). It
|
|
35
|
+
flushes and exits with code 1 like Node does, only when no other handler is registered.
|
|
36
|
+
Request bodies, headers, query strings and query arguments are never recorded.
|
|
37
|
+
|
|
38
|
+
## Integrations
|
|
39
|
+
|
|
40
|
+
Each lives at its own subpath, so nothing is loaded that you do not import.
|
|
41
|
+
|
|
42
|
+
| Integration | Import | Use |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| Express | `@watchtowerobservability/node/express` | `app.use(requestHandler())` first, `app.use(errorHandler())` last |
|
|
45
|
+
| Fastify | `.../fastify` | `await app.register(plugin)` |
|
|
46
|
+
| Koa | `.../koa` | `app.use(middleware())` first |
|
|
47
|
+
| NestJS | `.../nestjs` | `app.useGlobalInterceptors(new WatchtowerInterceptor())` (add express or fastify integration for spans) |
|
|
48
|
+
| Next.js server | `.../next` | `instrumentation.js`: `module.exports = require('@watchtowerobservability/node/next')` (exports `register`, `onRequestError`) |
|
|
49
|
+
| Prisma | `.../prisma` | `prisma.$extends(watchtowerExtension())` |
|
|
50
|
+
| AWS Lambda | `.../lambda` | `exports.handler = wrapHandler(async (event, ctx) => ...)` (async handlers; flushes before freeze) |
|
|
51
|
+
| Azure Functions | `.../azure-functions` | `app.http('fn', { handler: wrapFunction(async (req, ctx) => ...) })` (cold start, trigger, invocation id; flushes) |
|
|
52
|
+
| pino | `.../logs` | `pino(opts, pinoStream())` |
|
|
53
|
+
| winston | `.../logs` | `logger.add(watchtowerTransport())` |
|
|
54
|
+
| openai | `.../genai` | `instrumentOpenAI(new OpenAI())` |
|
|
55
|
+
| anthropic | `.../genai` | `instrumentAnthropic(new Anthropic())` |
|
|
56
|
+
| Mistral, Ollama | `.../genai` | `instrumentMistral(new Mistral())`, `instrumentOllama(ollama)` |
|
|
57
|
+
| LlamaIndex.TS | `.../genai` | `instrumentLlamaIndex(Settings)` |
|
|
58
|
+
| OpenAI Agents SDK | `.../genai` | `instrumentOpenAIAgents(addTraceProcessor)` |
|
|
59
|
+
| Vercel AI SDK | `.../genai` | `generateText({ experimental_telemetry: vercelAiTelemetry() })` |
|
|
60
|
+
|
|
61
|
+
GenAI spans follow the OTel GenAI semantic conventions (model, token usage, finish reasons); prompt and
|
|
62
|
+
completion text is not recorded. Streaming calls end their span at creation, without token usage.
|
|
63
|
+
|
|
64
|
+
## Profiling
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { startProfiling } from '@watchtowerobservability/node/profiling';
|
|
68
|
+
await startProfiling({ service: 'api' }); // key and endpoint from WT_INGEST_KEY / WT_OTLP_ENDPOINT
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
V8's own CPU sampler (`node:inspector`, 100 Hz, no native addon) is folded and posted to the
|
|
72
|
+
gateway's `/ingest` every 15 s as `<service>.cpu`. Idle time is left out. `withSpan(() => work())`
|
|
73
|
+
labels samples with the active OpenTelemetry span, so a trace links to its exact profile. By default
|
|
74
|
+
only its synchronous part counts. `startProfiling({ asyncSpans: true })` (or
|
|
75
|
+
`enableAsyncSpanLabels()`) also labels code after each `await`, through AsyncLocalStorage and V8
|
|
76
|
+
promise hooks. It is opt-in because its overhead has not been measured. Plain callbacks it starts
|
|
77
|
+
(timers, events) are labeled only from their own `await`s on. Past 100 000 labeled intervals in one
|
|
78
|
+
upload period, the rest of that period is unlabeled.
|
|
79
|
+
|
|
80
|
+
## Configuration
|
|
81
|
+
|
|
82
|
+
| Option | Env var | Default |
|
|
83
|
+
| --- | --- | --- |
|
|
84
|
+
| `apiKey` | `WT_INGEST_KEY` | required, sent as `Authorization: Bearer`, masked in output |
|
|
85
|
+
| `endpoint` | `WT_OTLP_ENDPOINT` | `http://localhost:4318` |
|
|
86
|
+
| `serviceName` | `WT_SERVICE` | `app` |
|
|
87
|
+
| `environment` | `WT_ENVIRONMENT` | unset |
|
|
88
|
+
| `release` | `WT_RELEASE` | unset |
|
|
89
|
+
| `bufferDir` | | no offline buffer (spans, logs and metrics spool to `traces/`, `logs/` and `metrics/`, 500 batches each) |
|
|
90
|
+
| `logs` | `WATCHTOWER_LOGS` (`OTEL_LOGS_EXPORTER=none` also turns it off) | `on`: OTLP logs (`log()`, pino, winston) |
|
|
91
|
+
| `metrics` | `WATCHTOWER_METRICS` (`OTEL_METRICS_EXPORTER=none` also turns it off) | `on`: OTLP metrics, see below |
|
|
92
|
+
| `redact` | | none; called for every span and log attribute |
|
|
93
|
+
|
|
94
|
+
Metrics: `init` sets the global meter provider, so `metrics.getMeter('app')` (re-exported from
|
|
95
|
+
`@opentelemetry/api`) records to Watchtower. A periodic reader exports to `/v1/metrics` every
|
|
96
|
+
`OTEL_METRIC_EXPORT_INTERVAL` ms (default 60000); counters and histograms use delta temporality unless
|
|
97
|
+
`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` is set. Install the optional peer
|
|
98
|
+
`@opentelemetry/instrumentation-runtime-node` for event loop, GC and heap metrics.
|
|
99
|
+
|
|
100
|
+
Examples: [`examples/basic.ts`](examples/basic.ts), [`examples/express-app`](examples/express-app/server.js).
|
|
101
|
+
|
|
102
|
+
Development: `npm install`, `npm run typecheck`, `npm test` (vitest), `npm run build` (`tsc` to `dist/cjs` and `dist/esm`).
|
|
103
|
+
|
|
104
|
+
## Test reporters and resumable evals
|
|
105
|
+
|
|
106
|
+
Jest: `reporters: ['default', ['@watchtowerobservability/node/jest', {}]]`. Vitest: `reporters: ['default', ['@watchtowerobservability/node/vitest', {}]]`.
|
|
107
|
+
|
|
108
|
+
Test optimization (`WT_TEST_OPTIMIZATION=1`, same contract as the pytest plugin: disabled and unaffected tests are skipped, quarantined failures do not fail the run, new tests are retried `efd_retries` times; `WT_CI_RUN_ID` also uploads the results as JUnit). Add a global setup file `export { default } from '@watchtowerobservability/node/test-plan'`, then for Vitest a setup file `import { beforeAll, afterEach } from 'vitest'; import { vitestSetup } from '@watchtowerobservability/node/test-plan'; vitestSetup({ beforeAll, afterEach });`, for Jest `testEnvironment: './wt-env.js'` with `module.exports = require('@watchtowerobservability/node/test-plan').jestEnvironment(require('jest-environment-node').TestEnvironment)`. Go: `go test -json ./... | wtctl ci gotest --respect-quarantine ...` and `go test -skip "$(wtctl ci plan ... --go-skip)"`.
|
|
109
|
+
Each test becomes a span (`test.outcome`) and, with `WT_PROJECT_ID`, a `test_pass` score. Set `WT_INGEST_KEY`
|
|
110
|
+
(or pass `client`/`apiKey`); without a key the reporters do nothing.
|
|
111
|
+
|
|
112
|
+
`client.evaluateResume(dataset, task, scorers, previousRows)` re-runs only the cases that errored or are missing
|
|
113
|
+
(the Python SDK has `evaluate_resume`).
|
|
114
|
+
|
|
115
|
+
## Provenance
|
|
116
|
+
|
|
117
|
+
Every release artifact carries a GitHub build attestation. Verify one with
|
|
118
|
+
`gh attestation verify <file> --repo watchtowerobservability/watchtower-node`.
|
|
119
|
+
|
|
120
|
+
## License
|
|
121
|
+
|
|
122
|
+
Apache-2.0. Source of truth is the Watchtower monorepo; this repository is a published mirror.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base';
|
|
2
|
+
import type { LogRecordExporter, ReadableLogRecord } from '@opentelemetry/sdk-logs';
|
|
3
|
+
import { AggregationTemporality } from '@opentelemetry/sdk-metrics';
|
|
4
|
+
import type { InstrumentType, PushMetricExporter, ResourceMetrics } from '@opentelemetry/sdk-metrics';
|
|
5
|
+
type Done = Parameters<SpanExporter['export']>[1];
|
|
6
|
+
/** What the spool wraps: a span, log record or metric exporter; `B` is one export batch. */
|
|
7
|
+
export interface BatchExporter<B> {
|
|
8
|
+
export(batch: B, done: Done): void;
|
|
9
|
+
shutdown(): Promise<void>;
|
|
10
|
+
forceFlush?(): Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
export interface SpoolOptions<B = ReadableSpan[]> {
|
|
13
|
+
maxFiles?: number;
|
|
14
|
+
encode?: (batch: B) => Uint8Array;
|
|
15
|
+
}
|
|
16
|
+
/** OTLP/JSON encoders for the three signals. */
|
|
17
|
+
export declare const encodeSpans: (spans: ReadableSpan[]) => Uint8Array;
|
|
18
|
+
export declare const encodeLogs: (logs: ReadableLogRecord[]) => Uint8Array;
|
|
19
|
+
export declare const encodeMetrics: (rm: ResourceMetrics) => Uint8Array;
|
|
20
|
+
export declare class SpoolExporter<B = ReadableSpan[]> implements BatchExporter<B> {
|
|
21
|
+
private readonly inner;
|
|
22
|
+
private readonly dir;
|
|
23
|
+
private readonly url;
|
|
24
|
+
private readonly headers;
|
|
25
|
+
private readonly fetch;
|
|
26
|
+
private readonly maxFiles;
|
|
27
|
+
private readonly encode;
|
|
28
|
+
constructor(inner: BatchExporter<B>, dir: string, url: string, headers: Record<string, string>, fetch: typeof globalThis.fetch, opts?: SpoolOptions<B>);
|
|
29
|
+
private _files;
|
|
30
|
+
replay(): Promise<void>;
|
|
31
|
+
export(batch: B, done: Done): void;
|
|
32
|
+
private _spool;
|
|
33
|
+
shutdown(): Promise<void>;
|
|
34
|
+
forceFlush(): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
/** A spool for log records: same directory rules, `/v1/logs` replay. */
|
|
37
|
+
export declare const spoolLogs: (inner: LogRecordExporter, dir: string, url: string, headers: Record<string, string>, fetch: typeof globalThis.fetch, opts?: {
|
|
38
|
+
maxFiles?: number;
|
|
39
|
+
}) => SpoolExporter<ReadableLogRecord[]>;
|
|
40
|
+
/** A spool for metrics (`/v1/metrics` replay); the reader still asks the real exporter for temporality. */
|
|
41
|
+
export declare class MetricSpool extends SpoolExporter<ResourceMetrics> implements PushMetricExporter {
|
|
42
|
+
private readonly metricInner;
|
|
43
|
+
constructor(metricInner: PushMetricExporter, dir: string, url: string, headers: Record<string, string>, fetch: typeof globalThis.fetch, opts?: {
|
|
44
|
+
maxFiles?: number;
|
|
45
|
+
});
|
|
46
|
+
selectAggregationTemporality(t: InstrumentType): AggregationTemporality;
|
|
47
|
+
forceFlush(): Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
export {};
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.MetricSpool = exports.spoolLogs = exports.SpoolExporter = exports.encodeMetrics = exports.encodeLogs = exports.encodeSpans = void 0;
|
|
37
|
+
// Offline buffer: failed OTLP batches (spans, log records or metrics) are spooled to disk, at most
|
|
38
|
+
// `maxFiles` batches per signal directory (oldest dropped), and replayed oldest first before the
|
|
39
|
+
// next export, so they go out as soon as the endpoint is reachable again.
|
|
40
|
+
const fs = __importStar(require("node:fs"));
|
|
41
|
+
const path = __importStar(require("node:path"));
|
|
42
|
+
const crypto = __importStar(require("node:crypto"));
|
|
43
|
+
const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
|
|
44
|
+
const otlp_transformer_1 = require("@opentelemetry/otlp-transformer");
|
|
45
|
+
/** OTLP/JSON encoders for the three signals. */
|
|
46
|
+
const encodeSpans = (spans) => Buffer.from(otlp_transformer_1.JsonTraceSerializer.serializeRequest(spans));
|
|
47
|
+
exports.encodeSpans = encodeSpans;
|
|
48
|
+
const encodeLogs = (logs) => Buffer.from(otlp_transformer_1.JsonLogsSerializer.serializeRequest(logs));
|
|
49
|
+
exports.encodeLogs = encodeLogs;
|
|
50
|
+
const encodeMetrics = (rm) => Buffer.from(otlp_transformer_1.JsonMetricsSerializer.serializeRequest(rm));
|
|
51
|
+
exports.encodeMetrics = encodeMetrics;
|
|
52
|
+
class SpoolExporter {
|
|
53
|
+
inner;
|
|
54
|
+
dir;
|
|
55
|
+
url;
|
|
56
|
+
headers;
|
|
57
|
+
fetch;
|
|
58
|
+
maxFiles;
|
|
59
|
+
encode;
|
|
60
|
+
constructor(inner, dir, url, headers, fetch, opts) {
|
|
61
|
+
this.inner = inner;
|
|
62
|
+
this.dir = dir;
|
|
63
|
+
this.url = url;
|
|
64
|
+
this.headers = headers;
|
|
65
|
+
this.fetch = fetch;
|
|
66
|
+
this.maxFiles = (opts && opts.maxFiles) || 500;
|
|
67
|
+
this.encode = (opts && opts.encode) || exports.encodeSpans;
|
|
68
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
69
|
+
}
|
|
70
|
+
_files() {
|
|
71
|
+
return fs.readdirSync(this.dir)
|
|
72
|
+
.map((n) => ({ n, t: fs.statSync(path.join(this.dir, n)).mtimeMs }))
|
|
73
|
+
.sort((a, b) => a.t - b.t || a.n.localeCompare(b.n))
|
|
74
|
+
.map((f) => f.n);
|
|
75
|
+
}
|
|
76
|
+
async replay() {
|
|
77
|
+
for (const n of this._files()) {
|
|
78
|
+
const p = path.join(this.dir, n);
|
|
79
|
+
try {
|
|
80
|
+
const res = await this.fetch(this.url, {
|
|
81
|
+
method: 'POST',
|
|
82
|
+
headers: { ...this.headers, 'Content-Type': 'application/json' },
|
|
83
|
+
body: fs.readFileSync(p),
|
|
84
|
+
});
|
|
85
|
+
if (!res.ok)
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return; // still offline; keep order
|
|
90
|
+
}
|
|
91
|
+
fs.unlinkSync(p);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export(batch, done) {
|
|
95
|
+
void this.replay().then(() => this.inner.export(batch, (r) => {
|
|
96
|
+
if (r.code !== 0)
|
|
97
|
+
this._spool(this.encode(batch));
|
|
98
|
+
done(r);
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
_spool(payload) {
|
|
102
|
+
const files = this._files();
|
|
103
|
+
for (const old of files.slice(0, Math.max(0, files.length - this.maxFiles + 1))) {
|
|
104
|
+
fs.unlinkSync(path.join(this.dir, old)); // drop-oldest
|
|
105
|
+
}
|
|
106
|
+
fs.writeFileSync(path.join(this.dir, `${crypto.randomUUID()}.json`), payload);
|
|
107
|
+
}
|
|
108
|
+
shutdown() {
|
|
109
|
+
return this.inner.shutdown();
|
|
110
|
+
}
|
|
111
|
+
forceFlush() {
|
|
112
|
+
return this.inner.forceFlush ? this.inner.forceFlush() : Promise.resolve();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
exports.SpoolExporter = SpoolExporter;
|
|
116
|
+
/** A spool for log records: same directory rules, `/v1/logs` replay. */
|
|
117
|
+
const spoolLogs = (inner, dir, url, headers, fetch, opts) => new SpoolExporter(inner, dir, url, headers, fetch, { ...opts, encode: exports.encodeLogs });
|
|
118
|
+
exports.spoolLogs = spoolLogs;
|
|
119
|
+
/** A spool for metrics (`/v1/metrics` replay); the reader still asks the real exporter for temporality. */
|
|
120
|
+
class MetricSpool extends SpoolExporter {
|
|
121
|
+
metricInner;
|
|
122
|
+
constructor(metricInner, dir, url, headers, fetch, opts) {
|
|
123
|
+
super(metricInner, dir, url, headers, fetch, { ...opts, encode: exports.encodeMetrics });
|
|
124
|
+
this.metricInner = metricInner;
|
|
125
|
+
}
|
|
126
|
+
selectAggregationTemporality(t) {
|
|
127
|
+
const pick = this.metricInner.selectAggregationTemporality;
|
|
128
|
+
return pick ? pick.call(this.metricInner, t) : sdk_metrics_1.AggregationTemporality.CUMULATIVE; // the SDK default
|
|
129
|
+
}
|
|
130
|
+
forceFlush() {
|
|
131
|
+
return this.metricInner.forceFlush();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
exports.MetricSpool = MetricSpool;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface CaptureContext {
|
|
2
|
+
/** false for crashes (uncaught); default true. Keys starting with `wt.` are dropped. */
|
|
3
|
+
handled?: boolean;
|
|
4
|
+
attributes?: Record<string, string | number | boolean | undefined>;
|
|
5
|
+
}
|
|
6
|
+
/** The slice of `process` the hooks need; tests pass an EventEmitter. */
|
|
7
|
+
export interface ProcessLike {
|
|
8
|
+
on(event: string, listener: (arg: unknown) => void): unknown;
|
|
9
|
+
off(event: string, listener: (arg: unknown) => void): unknown;
|
|
10
|
+
listenerCount(event: string): number;
|
|
11
|
+
exit(code?: number): unknown;
|
|
12
|
+
}
|
|
13
|
+
export declare function dropReserved<T>(attrs?: Record<string, T>): Record<string, T>;
|
|
14
|
+
/** Record err on the active span (or a new `exception` span). Returns the trace id. */
|
|
15
|
+
export declare function captureException(err: unknown, ctx?: CaptureContext): string;
|
|
16
|
+
/** uncaughtException / unhandledRejection hooks. Exits like Node would, but only when we are the sole listener. */
|
|
17
|
+
export declare function installProcessHandlers(flush: () => Promise<unknown>, proc?: ProcessLike): () => void;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.dropReserved = dropReserved;
|
|
4
|
+
exports.captureException = captureException;
|
|
5
|
+
exports.installProcessHandlers = installProcessHandlers;
|
|
6
|
+
// Error capture: an exception becomes an OTel span event (exception.*) with trace and span ids.
|
|
7
|
+
const api_1 = require("@opentelemetry/api");
|
|
8
|
+
const captured = new WeakMap(); // error object -> traceId, so framework + process hooks never double-report
|
|
9
|
+
function dropReserved(attrs) {
|
|
10
|
+
return Object.fromEntries(Object.entries(attrs || {}).filter(([k]) => !k.startsWith('wt.')));
|
|
11
|
+
}
|
|
12
|
+
/** Record err on the active span (or a new `exception` span). Returns the trace id. */
|
|
13
|
+
function captureException(err, ctx) {
|
|
14
|
+
const o = ctx || {};
|
|
15
|
+
const e = err instanceof Error ? err : new Error(typeof err === 'string' ? err : JSON.stringify(err));
|
|
16
|
+
const seen = captured.get(e);
|
|
17
|
+
if (seen !== undefined)
|
|
18
|
+
return seen;
|
|
19
|
+
const attrs = { 'error.handled': o.handled !== false, ...dropReserved(o.attributes) };
|
|
20
|
+
const active = api_1.trace.getActiveSpan();
|
|
21
|
+
const span = active && active.isRecording() ? active : api_1.trace.getTracer('watchtower').startSpan('exception');
|
|
22
|
+
span.setAttributes(attrs);
|
|
23
|
+
span.recordException(e);
|
|
24
|
+
span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: e.message });
|
|
25
|
+
const traceId = span.spanContext().traceId;
|
|
26
|
+
if (span !== active)
|
|
27
|
+
span.end();
|
|
28
|
+
captured.set(e, traceId);
|
|
29
|
+
return traceId;
|
|
30
|
+
}
|
|
31
|
+
/** uncaughtException / unhandledRejection hooks. Exits like Node would, but only when we are the sole listener. */
|
|
32
|
+
function installProcessHandlers(flush, proc) {
|
|
33
|
+
const p = proc || process;
|
|
34
|
+
const exitAfterFlush = () => Promise.race([flush(), new Promise((r) => setTimeout(r, 2000).unref())]).finally(() => p.exit(1));
|
|
35
|
+
const onException = (e) => {
|
|
36
|
+
captureException(e, { handled: false, attributes: { 'error.mechanism': 'uncaughtException' } });
|
|
37
|
+
if (p.listenerCount('uncaughtException') > 1)
|
|
38
|
+
return;
|
|
39
|
+
console.error(e);
|
|
40
|
+
exitAfterFlush();
|
|
41
|
+
};
|
|
42
|
+
const onRejection = (reason) => {
|
|
43
|
+
captureException(reason, { handled: false, attributes: { 'error.mechanism': 'unhandledRejection' } });
|
|
44
|
+
if (p.listenerCount('unhandledRejection') > 1)
|
|
45
|
+
return;
|
|
46
|
+
console.error(reason);
|
|
47
|
+
exitAfterFlush();
|
|
48
|
+
};
|
|
49
|
+
p.on('uncaughtException', onException);
|
|
50
|
+
p.on('unhandledRejection', onRejection);
|
|
51
|
+
return () => {
|
|
52
|
+
p.off('uncaughtException', onException);
|
|
53
|
+
p.off('unhandledRejection', onRejection);
|
|
54
|
+
};
|
|
55
|
+
}
|