@libo11y/test 0.0.0-stage → 0.1.1
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 +120 -2
- package/dist/assertions.d.ts +47 -0
- package/dist/assertions.js +170 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/otlp-schema.d.ts +20 -0
- package/dist/otlp-schema.js +294 -0
- package/dist/protowire.d.ts +68 -0
- package/dist/protowire.js +299 -0
- package/dist/recorder.d.ts +94 -0
- package/dist/recorder.js +301 -0
- package/dist/sink.d.ts +48 -0
- package/dist/sink.js +199 -0
- package/package.json +38 -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,121 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @libo11y/test
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The libo11y test harness for TypeScript, the counterpart of Go's
|
|
4
|
+
`o11ytest`. It has a hermetic recorder that captures spans, logs and
|
|
5
|
+
metrics in memory, assertions for the libo11y specification and for
|
|
6
|
+
correlation, and an in-process OTLP/HTTP sink. It runs on Bun and Node,
|
|
7
|
+
including Playwright's Node test runner. It does not run in browsers.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install --save-dev @libo11y/test
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick start
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createRecorder } from "@libo11y/test";
|
|
17
|
+
|
|
18
|
+
const rec = await createRecorder({ serviceName: "checkout" });
|
|
19
|
+
const service = new CheckoutService(rec.telemetry); // inject the providers or the logger
|
|
20
|
+
await service.handle(order);
|
|
21
|
+
|
|
22
|
+
rec.spans(); // ended spans, in end order, already redacted
|
|
23
|
+
rec.logs(); // log records as the OTLP leg emitted them, already classified
|
|
24
|
+
await rec.exemplars("http.server.request.duration");
|
|
25
|
+
|
|
26
|
+
await rec.assertConforms(); // tier-0 identity, no secrets, event contracts
|
|
27
|
+
rec.assertCorrelated(); // every log emitted inside a span carries its trace ID
|
|
28
|
+
await rec.assertTriangle({ metric: "http.server.request.duration" });
|
|
29
|
+
await rec.shutdown();
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
To record HTTP telemetry, pass `{ telemetry: rec.telemetry }` to
|
|
33
|
+
`instrumentServe` or `instrumentFetch` from `@libo11y/server`.
|
|
34
|
+
|
|
35
|
+
## The recorder
|
|
36
|
+
|
|
37
|
+
`createRecorder(options?)` builds a telemetry with `hermetic: true`, so no
|
|
38
|
+
`OTEL_*` variable has any effect, and it never installs a provider
|
|
39
|
+
globally. It takes every `TelemetryOptions` field except the injected
|
|
40
|
+
pipeline (`spanExporter`, `spanProcessor`, `metricReader`, `logExporter`,
|
|
41
|
+
`logProcessor`, `logExport`) and `hermetic`. Caller options win over these
|
|
42
|
+
defaults:
|
|
43
|
+
|
|
44
|
+
| Option | Recorder default |
|
|
45
|
+
| ---------------- | ---------------- |
|
|
46
|
+
| `serviceName` | `"test"` |
|
|
47
|
+
| `environment` | `"test"` |
|
|
48
|
+
| `logLevel` | `"debug"` |
|
|
49
|
+
| `console` | `false` |
|
|
50
|
+
| `runtimeMetrics` | `false` |
|
|
51
|
+
| `startupSummary` | `false` |
|
|
52
|
+
| `sampler` | always on |
|
|
53
|
+
| `exemplarFilter` | `"trace_based"` |
|
|
54
|
+
|
|
55
|
+
| Member | What it does |
|
|
56
|
+
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
57
|
+
| `telemetry` | the hermetic telemetry. Inject its providers, propagator or logger into the code under test |
|
|
58
|
+
| `spans()` | every span ended so far, in end order, already redacted |
|
|
59
|
+
| `logs()` | every log record the OTLP leg emitted so far, already classified |
|
|
60
|
+
| `metrics()` | collects every instrument through a manual reader, with exemplars attached |
|
|
61
|
+
| `metricNames()` | the names of every instrument with recorded data |
|
|
62
|
+
| `exemplars(instrument)` | the exemplars on the named instrument, across its data points |
|
|
63
|
+
| `assertConforms()` | throws unless the tier-0 resource keys are present, no secret-classified attribute was counted or is visible in a log or span, and every registered event carries the attributes its contract requires. Call it before `shutdown` |
|
|
64
|
+
| `assertCorrelated()` | throws unless every log recorded inside a span carries that span's trace ID |
|
|
65
|
+
| `assertTriangle({ metric })` | throws unless a span, a log with its trace and span IDs, and an exemplar on `metric` with the same trace ID were all recorded |
|
|
66
|
+
| `shutdown()` | shuts the telemetry down. What was recorded stays readable |
|
|
67
|
+
|
|
68
|
+
The assertions throw `AssertionError` from `node:assert`.
|
|
69
|
+
|
|
70
|
+
OpenTelemetry JS keeps its context manager process-wide. When none is
|
|
71
|
+
registered, the recorder installs an `AsyncLocalStorageContextManager`,
|
|
72
|
+
and it removes that manager when the last recorder shuts down. That is the
|
|
73
|
+
only global it touches.
|
|
74
|
+
|
|
75
|
+
## The OTLP sink
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { startOtlpSink } from "@libo11y/test";
|
|
79
|
+
|
|
80
|
+
const sink = await startOtlpSink();
|
|
81
|
+
process.env.OTEL_EXPORTER_OTLP_ENDPOINT = sink.url;
|
|
82
|
+
// ... run the code under test ...
|
|
83
|
+
await sink.waitFor("traces");
|
|
84
|
+
sink.traces(); // each request decoded into its OTLP/JSON shape
|
|
85
|
+
await sink.close();
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The sink listens on `127.0.0.1` and accepts `POST /v1/traces`,
|
|
89
|
+
`/v1/metrics` and `/v1/logs` as `application/json` or
|
|
90
|
+
`application/x-protobuf`, plain or gzip.
|
|
91
|
+
|
|
92
|
+
| Option | Effect |
|
|
93
|
+
| ------------ | -------------------------------------------------------------------------------- |
|
|
94
|
+
| `status` | the status every signal request gets. Default 200. Only a 200 stores the request |
|
|
95
|
+
| `retryAfter` | a `Retry-After` header on every signal response |
|
|
96
|
+
|
|
97
|
+
Pass `{ status: 429, retryAfter: "1" }` to simulate a refusing collector.
|
|
98
|
+
`waitFor(signal, count?, timeoutMillis?)` resolves once the signal has
|
|
99
|
+
`count` accepted requests, 1 by default, and rejects after `timeoutMillis`,
|
|
100
|
+
5000 ms by default. `close()` stops the server and rejects pending
|
|
101
|
+
`waitFor` calls.
|
|
102
|
+
`requests()` lists every request with its path, media type, encoding and
|
|
103
|
+
size, whatever its outcome. `decodeOtlpProtobuf` and `normalizeOtlp` are
|
|
104
|
+
exported for tests that decode bodies themselves.
|
|
105
|
+
|
|
106
|
+
## Limits
|
|
107
|
+
|
|
108
|
+
- **JSON bodies are stored as parsed.** Protobuf bodies decode to the
|
|
109
|
+
representation upstream's JSON serializers use, where 64-bit integers
|
|
110
|
+
are numbers when they are safe integers. A producer that follows the
|
|
111
|
+
proto3 JSON mapping and writes them as strings, such as `"count": "3"`,
|
|
112
|
+
does not compare equal to the protobuf decoding under `normalizeOtlp`.
|
|
113
|
+
- **Bodies are capped at 32 MiB**, before and after inflating. A larger
|
|
114
|
+
body gets a 413 and is not stored.
|
|
115
|
+
- **Protobuf messages may nest at most 100 deep.**
|
|
116
|
+
|
|
117
|
+
## Parity
|
|
118
|
+
|
|
119
|
+
[docs/PARITY.md](https://github.com/jamesainslie/libo11y/blob/main/docs/PARITY.md)
|
|
120
|
+
lists where the TypeScript packages match Go and where they differ, with
|
|
121
|
+
the reasons.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { ResourceMetricsWithExemplars } from "@libo11y/core";
|
|
2
|
+
import type { Attributes, SpanContext } from "@opentelemetry/api";
|
|
3
|
+
import type { ReadableSpan } from "@opentelemetry/sdk-trace";
|
|
4
|
+
import type { RecordedExemplar, RecordedLog } from "./recorder.ts";
|
|
5
|
+
/** A recorded log with the valid span context active when it was emitted, as Go's logCapture keeps it. */
|
|
6
|
+
export interface CapturedLog {
|
|
7
|
+
readonly log: RecordedLog;
|
|
8
|
+
readonly active: SpanContext | undefined;
|
|
9
|
+
}
|
|
10
|
+
/** Throws one AssertionError whose message is every problem, one per line. */
|
|
11
|
+
export declare function fail(problems: readonly string[]): never;
|
|
12
|
+
/**
|
|
13
|
+
* The dotted key of every leaf under attributes, joining group names with "." as the library's
|
|
14
|
+
* classification does. An empty-key group is inlined into its parent; arrays and bytes are leaves.
|
|
15
|
+
*/
|
|
16
|
+
export declare function leafKeys(attributes: Readonly<Record<string, unknown>>, prefix?: string): string[];
|
|
17
|
+
/**
|
|
18
|
+
* Every way a record for the named event, carrying keys, violates its registered contract, as Go's
|
|
19
|
+
* conformance.CheckEvent reports it. An unregistered name has no contract.
|
|
20
|
+
*/
|
|
21
|
+
export declare function checkEvent(name: string, keys: readonly string[]): string[];
|
|
22
|
+
/** The positive o11y.schema.violations counts for rule, summed by o11y.signal. */
|
|
23
|
+
export declare function violationsBySignal(rm: ResourceMetricsWithExemplars, rule: string): Map<string, number>;
|
|
24
|
+
/** What assertConforms checks. metrics is absent when collecting failed. */
|
|
25
|
+
export interface ConformanceInput {
|
|
26
|
+
readonly resource: Attributes;
|
|
27
|
+
readonly metrics?: ResourceMetricsWithExemplars;
|
|
28
|
+
readonly logs: readonly RecordedLog[];
|
|
29
|
+
readonly spans: readonly ReadableSpan[];
|
|
30
|
+
/** Problems found before the checks, such as a failed flush, reported after the tier-0 keys. */
|
|
31
|
+
readonly preflight?: readonly string[];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Go AssertConforms after its flush: tier-0 resource keys, secret_attribute violations by signal,
|
|
35
|
+
* spec-table secrets in the clear on logs and span attributes, and registered event contracts.
|
|
36
|
+
*/
|
|
37
|
+
export declare function conformanceProblems(input: ConformanceInput): string[];
|
|
38
|
+
/**
|
|
39
|
+
* Go AssertCorrelated: a record emitted while a span was active must carry that span's trace ID.
|
|
40
|
+
* "active" is the caller's active span at emission, not the context the emitter passed.
|
|
41
|
+
*/
|
|
42
|
+
export declare function correlationProblems(logs: readonly CapturedLog[]): string[];
|
|
43
|
+
/**
|
|
44
|
+
* The correlation triangle: a recorded span, a log carrying its trace and span IDs, and an
|
|
45
|
+
* exemplar on metric carrying that trace ID.
|
|
46
|
+
*/
|
|
47
|
+
export declare function triangleProblems(metric: string, spans: readonly ReadableSpan[], logs: readonly RecordedLog[], exemplars: readonly RecordedExemplar[]): string[];
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The checks behind the recorder's assertions, as pure functions over recorded telemetry. Each
|
|
3
|
+
* returns its problems as messages in the wording of Go's o11ytest and internal/conformance; the
|
|
4
|
+
* recorder throws them together as one AssertionError.
|
|
5
|
+
*/
|
|
6
|
+
import { AssertionError } from "node:assert";
|
|
7
|
+
import { ATTR_RULE, ATTR_SIGNAL, EVENTS, goQuote, METRIC_SCHEMA_VIOLATIONS, REQUIRED_TIER0, SENSITIVITY_OF, SIGNAL_VALUE_RESOURCE, } from "@libo11y/spec";
|
|
8
|
+
/** The rule o11y.schema.violations records when classification removes a secret attribute. */
|
|
9
|
+
const SECRET_ATTRIBUTE_RULE = "secret_attribute";
|
|
10
|
+
/** Throws one AssertionError whose message is every problem, one per line. */
|
|
11
|
+
export function fail(problems) {
|
|
12
|
+
throw new AssertionError({ message: problems.join("\n") });
|
|
13
|
+
}
|
|
14
|
+
function isGroup(v) {
|
|
15
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Uint8Array);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The dotted key of every leaf under attributes, joining group names with "." as the library's
|
|
19
|
+
* classification does. An empty-key group is inlined into its parent; arrays and bytes are leaves.
|
|
20
|
+
*/
|
|
21
|
+
export function leafKeys(attributes, prefix = "") {
|
|
22
|
+
const out = [];
|
|
23
|
+
for (const [k, v] of Object.entries(attributes)) {
|
|
24
|
+
const key = k === "" ? prefix : prefix === "" ? k : `${prefix}.${k}`;
|
|
25
|
+
if (isGroup(v))
|
|
26
|
+
out.push(...leafKeys(v, key));
|
|
27
|
+
else
|
|
28
|
+
out.push(key);
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Every way a record for the named event, carrying keys, violates its registered contract, as Go's
|
|
34
|
+
* conformance.CheckEvent reports it. An unregistered name has no contract.
|
|
35
|
+
*/
|
|
36
|
+
export function checkEvent(name, keys) {
|
|
37
|
+
const info = EVENTS.get(name);
|
|
38
|
+
if (info === undefined)
|
|
39
|
+
return [];
|
|
40
|
+
const present = new Set(keys);
|
|
41
|
+
const problems = [];
|
|
42
|
+
for (const req of info.required) {
|
|
43
|
+
if (!present.has(req))
|
|
44
|
+
problems.push(`event ${name}: missing required attribute ${req}`);
|
|
45
|
+
}
|
|
46
|
+
for (const tmpl of info.requiredTemplates) {
|
|
47
|
+
const prefix = `${tmpl}.`;
|
|
48
|
+
// A bare "<template>." carries no key, so it does not satisfy the template.
|
|
49
|
+
if (!keys.some((k) => k.length > prefix.length && k.startsWith(prefix))) {
|
|
50
|
+
problems.push(`event ${name}: missing required template attribute ${prefix}<key>`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return problems;
|
|
54
|
+
}
|
|
55
|
+
function isSecret(key) {
|
|
56
|
+
return SENSITIVITY_OF.get(key) === "secret";
|
|
57
|
+
}
|
|
58
|
+
/** The positive o11y.schema.violations counts for rule, summed by o11y.signal. */
|
|
59
|
+
export function violationsBySignal(rm, rule) {
|
|
60
|
+
const totals = new Map();
|
|
61
|
+
for (const sm of rm.scopeMetrics) {
|
|
62
|
+
for (const metric of sm.metrics) {
|
|
63
|
+
if (metric.descriptor.name !== METRIC_SCHEMA_VIOLATIONS)
|
|
64
|
+
continue;
|
|
65
|
+
for (const point of metric.dataPoints) {
|
|
66
|
+
const value = point.value;
|
|
67
|
+
if (point.attributes[ATTR_RULE] !== rule || typeof value !== "number" || value <= 0)
|
|
68
|
+
continue;
|
|
69
|
+
const signal = String(point.attributes[ATTR_SIGNAL] ?? "");
|
|
70
|
+
totals.set(signal, (totals.get(signal) ?? 0) + value);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return totals;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Go AssertConforms after its flush: tier-0 resource keys, secret_attribute violations by signal,
|
|
78
|
+
* spec-table secrets in the clear on logs and span attributes, and registered event contracts.
|
|
79
|
+
*/
|
|
80
|
+
export function conformanceProblems(input) {
|
|
81
|
+
const problems = [];
|
|
82
|
+
for (const key of REQUIRED_TIER0) {
|
|
83
|
+
if (!Object.hasOwn(input.resource, key)) {
|
|
84
|
+
problems.push(`o11ytest: resource missing required tier-0 attribute ${goQuote(key)}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
problems.push(...(input.preflight ?? []));
|
|
88
|
+
if (input.metrics !== undefined) {
|
|
89
|
+
const bySignal = violationsBySignal(input.metrics, SECRET_ATTRIBUTE_RULE);
|
|
90
|
+
for (const signal of [...bySignal.keys()].sort()) {
|
|
91
|
+
const n = bySignal.get(signal) ?? 0;
|
|
92
|
+
if (signal === SIGNAL_VALUE_RESOURCE) {
|
|
93
|
+
problems.push("o11ytest: options passed to createRecorder put a secret-classified attribute on the resource " +
|
|
94
|
+
`(${n} redaction(s) counted); it was redacted, but secrets must never be emitted`);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
problems.push(`o11ytest: the code under test emitted secret-classified attributes on ${signal} ` +
|
|
98
|
+
`(${n} redaction(s) counted); they were redacted, but secrets must never be emitted`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// These read only the specification table, so a key an application registry classifies secret
|
|
102
|
+
// is not checked here. The violation count above does see it.
|
|
103
|
+
for (const log of input.logs) {
|
|
104
|
+
const keys = leafKeys(log.attributes);
|
|
105
|
+
for (const key of keys) {
|
|
106
|
+
if (isSecret(key)) {
|
|
107
|
+
problems.push(`o11ytest: log record ${goQuote(log.body)} carries secret-classified attribute ${goQuote(key)} in the clear`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (log.eventName !== undefined) {
|
|
111
|
+
for (const problem of checkEvent(log.eventName, keys))
|
|
112
|
+
problems.push(`o11ytest: ${problem}`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
for (const span of input.spans) {
|
|
116
|
+
for (const key of Object.keys(span.attributes)) {
|
|
117
|
+
if (isSecret(key)) {
|
|
118
|
+
problems.push(`o11ytest: span ${goQuote(span.name)} carries secret-classified attribute ${goQuote(key)} in the clear`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return problems;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Go AssertCorrelated: a record emitted while a span was active must carry that span's trace ID.
|
|
126
|
+
* "active" is the caller's active span at emission, not the context the emitter passed.
|
|
127
|
+
*/
|
|
128
|
+
export function correlationProblems(logs) {
|
|
129
|
+
const problems = [];
|
|
130
|
+
for (const { log, active } of logs) {
|
|
131
|
+
if (active === undefined)
|
|
132
|
+
continue;
|
|
133
|
+
if (log.traceId === undefined) {
|
|
134
|
+
problems.push(`o11ytest: correlated record ${goQuote(log.body)} has no trace_id attribute`);
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (log.traceId !== active.traceId) {
|
|
138
|
+
problems.push(`o11ytest: record ${goQuote(log.body)} trace_id ${goQuote(log.traceId)} does not match its span ` +
|
|
139
|
+
goQuote(active.traceId));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return problems;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* The correlation triangle: a recorded span, a log carrying its trace and span IDs, and an
|
|
146
|
+
* exemplar on metric carrying that trace ID.
|
|
147
|
+
*/
|
|
148
|
+
export function triangleProblems(metric, spans, logs, exemplars) {
|
|
149
|
+
if (spans.length === 0)
|
|
150
|
+
return ["o11ytest: triangle: no span was recorded"];
|
|
151
|
+
const traceOf = new Map(spans.map((s) => [s.spanContext().spanId, s.spanContext().traceId]));
|
|
152
|
+
const traces = new Set(logs
|
|
153
|
+
.filter((l) => l.spanId !== undefined && l.traceId !== undefined && traceOf.get(l.spanId) === l.traceId)
|
|
154
|
+
.map((l) => l.traceId));
|
|
155
|
+
if (traces.size === 0) {
|
|
156
|
+
return [
|
|
157
|
+
`o11ytest: triangle: none of ${logs.length} log record(s) carries the trace and span IDs of one of ` +
|
|
158
|
+
`${spans.length} recorded span(s)`,
|
|
159
|
+
];
|
|
160
|
+
}
|
|
161
|
+
if (exemplars.length === 0)
|
|
162
|
+
return [`o11ytest: triangle: no exemplar recorded on ${goQuote(metric)}`];
|
|
163
|
+
if (!exemplars.some((e) => e.traceId !== undefined && traces.has(e.traceId))) {
|
|
164
|
+
return [
|
|
165
|
+
`o11ytest: triangle: none of ${exemplars.length} exemplar(s) on ${goQuote(metric)} carries the trace ID ` +
|
|
166
|
+
"of a span with a correlated log record",
|
|
167
|
+
];
|
|
168
|
+
}
|
|
169
|
+
return [];
|
|
170
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The libo11y test harness: a hermetic recorder over in-memory signals, with conformance and
|
|
3
|
+
* correlation assertions, and an in-process OTLP/HTTP sink. Runs on Bun and Node, never in browsers.
|
|
4
|
+
*/
|
|
5
|
+
export { decodeOtlpProtobuf, normalizeOtlp, type OtlpSignal } from "./otlp-schema.ts";
|
|
6
|
+
export { createRecorder, type RecordedExemplar, type RecordedLog, type Recorder, type RecorderOptions, } from "./recorder.ts";
|
|
7
|
+
export { type OtlpRequestInfo, type OtlpSink, type OtlpSinkOptions, startOtlpSink } from "./sink.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The libo11y test harness: a hermetic recorder over in-memory signals, with conformance and
|
|
3
|
+
* correlation assertions, and an in-process OTLP/HTTP sink. Runs on Bun and Node, never in browsers.
|
|
4
|
+
*/
|
|
5
|
+
export { decodeOtlpProtobuf, normalizeOtlp } from "./otlp-schema.js";
|
|
6
|
+
export { createRecorder, } from "./recorder.js";
|
|
7
|
+
export { startOtlpSink } from "./sink.js";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** An OTLP signal, as the sink's paths name it. */
|
|
2
|
+
export type OtlpSignal = "traces" | "metrics" | "logs";
|
|
3
|
+
/**
|
|
4
|
+
* Decodes an OTLP/HTTP protobuf request body for signal into its OTLP/JSON shape: IDs are lowercase
|
|
5
|
+
* hex, *UnixNano timestamps decimal strings, other 64-bit integers numbers when safe (else decimal
|
|
6
|
+
* strings), bytes values base64 and enums numbers. Throws on malformed input.
|
|
7
|
+
*/
|
|
8
|
+
export declare function decodeOtlpProtobuf(signal: OtlpSignal, body: Uint8Array): Record<string, unknown>;
|
|
9
|
+
/**
|
|
10
|
+
* Normalizes an OTLP/JSON-shaped value so a decoded protobuf payload and the equivalent JSON
|
|
11
|
+
* payload compare equal:
|
|
12
|
+
* - a plain scalar field whose value is a proto3 default (0, false, ""), an empty list or an empty
|
|
13
|
+
* object after normalization is removed, because protobuf does not carry it and upstream's JSON
|
|
14
|
+
* serializers write some of them. A oneof member or proto3 optional field keeps its zero value,
|
|
15
|
+
* since there zero is data; only undefined and null are removed;
|
|
16
|
+
* - `schemaUrl` inside a `resource` is removed: upstream's JSON writes it there as well as on the
|
|
17
|
+
* Resource* message, but the OTLP Resource message has no such field.
|
|
18
|
+
* List elements are normalized but never removed, so bucket counts keep their zeros.
|
|
19
|
+
*/
|
|
20
|
+
export declare function normalizeOtlp(value: unknown): unknown;
|