@libo11y/effect 0.0.0-stage → 0.9.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 +280 -2
- package/dist/client.d.ts +176 -0
- package/dist/client.js +583 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +13 -0
- package/dist/layer.d.ts +55 -0
- package/dist/layer.js +39 -0
- package/dist/logger.d.ts +39 -0
- package/dist/logger.js +124 -0
- package/dist/metrics.d.ts +39 -0
- package/dist/metrics.js +393 -0
- package/dist/span-context.d.ts +15 -0
- package/dist/span-context.js +56 -0
- package/dist/tracer.d.ts +36 -0
- package/dist/tracer.js +51 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/dist/workers.d.ts +101 -0
- package/dist/workers.js +352 -0
- package/package.json +41 -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,281 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @libo11y/effect
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The libo11y bridge for [Effect](https://effect.website) 4. It reports an
|
|
4
|
+
Effect program to a libo11y telemetry from any platform package:
|
|
5
|
+
[`@libo11y/server`](https://github.com/libo11y/libo11y/tree/main/ts/packages/server) on Bun and Node,
|
|
6
|
+
[`@libo11y/workers`](https://github.com/libo11y/libo11y/tree/main/ts/packages/workers) on Cloudflare Workers,
|
|
7
|
+
[`@libo11y/web`](https://github.com/libo11y/libo11y/tree/main/ts/packages/web) / [`@libo11y/rum`](https://github.com/libo11y/libo11y/tree/main/ts/packages/rum) in browsers, or
|
|
8
|
+
[`@libo11y/react-native`](https://github.com/libo11y/libo11y/tree/main/ts/packages/react-native) in React Native.
|
|
9
|
+
Effect spans, logs and metrics are exported, correlated and redacted with
|
|
10
|
+
everything else the telemetry exports.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @libo11y/effect effect @effect/opentelemetry
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
The package first ships in `ts/v0.8.0` and is published on npm at `0.9.0`
|
|
17
|
+
(and attached as a tarball to the
|
|
18
|
+
[`ts/v0.9.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.9.0)).
|
|
19
|
+
|
|
20
|
+
`effect` and `@effect/opentelemetry` (both `^4.2.0`) and
|
|
21
|
+
`@opentelemetry/api` (`>=1.10.0 <1.11.0`) are peer dependencies.
|
|
22
|
+
`@effect/opentelemetry` 4.2.0 is the first release built on OpenTelemetry
|
|
23
|
+
JS 3.x, which libo11y uses. Only its `OtelTracer` module is loaded.
|
|
24
|
+
|
|
25
|
+
Write Effect as usual: `Effect.withSpan`, `Effect.log`,
|
|
26
|
+
`Effect.annotateLogs`, `Metric.counter`.
|
|
27
|
+
|
|
28
|
+
## Quick start
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { layer } from "@libo11y/effect";
|
|
32
|
+
import { setup } from "@libo11y/server";
|
|
33
|
+
import { Effect } from "effect";
|
|
34
|
+
|
|
35
|
+
const telemetry = await setup({ serviceName: "checkout", environment: "production" });
|
|
36
|
+
|
|
37
|
+
const program = Effect.log("order placed").pipe(
|
|
38
|
+
Effect.annotateLogs({ "order.id": "ord-42" }),
|
|
39
|
+
Effect.withSpan("checkout.place"),
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
await Effect.runPromise(program.pipe(Effect.provide(layer(telemetry))));
|
|
43
|
+
await telemetry.shutdown();
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## What the layer installs
|
|
47
|
+
|
|
48
|
+
`layer(telemetry, options?)` merges three layers, each also exported on
|
|
49
|
+
its own:
|
|
50
|
+
|
|
51
|
+
- `tracerLayer(telemetry, options?)`: the Effect `Tracer` over
|
|
52
|
+
`telemetry.tracerProvider`, from `@effect/opentelemetry`'s `OtelTracer`.
|
|
53
|
+
Effect spans, including those of Effect's `HttpServer`, `HttpClient`, RPC
|
|
54
|
+
and SQL modules, become OpenTelemetry spans of that provider, so they pass
|
|
55
|
+
libo11y's sampler and redaction and land in the same traces as other
|
|
56
|
+
spans. An inbound W3C `traceparent` that Effect's `HttpServer` reads
|
|
57
|
+
becomes the parent of its server span, and an Effect span started inside
|
|
58
|
+
an active OpenTelemetry span is its child. While a traced effect runs, its
|
|
59
|
+
span is the active OpenTelemetry span, so `instrumentFetch` and other
|
|
60
|
+
OpenTelemetry code see it. The instrumentation scope is `effect`.
|
|
61
|
+
Pass `sql: { parentConnectSpans: true }` (on `layer` or `tracerLayer`) to
|
|
62
|
+
re-parent `@effect/sql-pg`'s detached `sql.connect` root spans onto the
|
|
63
|
+
active propagated Effect span and enable `Statement.SpanPropagationEnabled`.
|
|
64
|
+
- `loggerLayer(telemetry)`: an Effect `Logger` (`makeLogger(telemetry)`)
|
|
65
|
+
that writes each record through `telemetry.logger`, to the console sink
|
|
66
|
+
and the OTLP leg. Records carry the trace and span IDs of the fiber's
|
|
67
|
+
propagated Effect span (walking past `Tracer.DisablePropagation` spans).
|
|
68
|
+
Log annotations become attributes, plain objects staying groups; log spans
|
|
69
|
+
become `effect.log_span.<label>` in milliseconds; a failure or defect in
|
|
70
|
+
the cause becomes `exception.type`, `exception.message` and
|
|
71
|
+
`exception.stacktrace`. The sensitivity policy drops secret and PII
|
|
72
|
+
attributes by key, as for every libo11y record. Effect's
|
|
73
|
+
`MinimumLogLevel` filters first, then libo11y's `logLevel`.
|
|
74
|
+
- `metricsLayer(telemetry)`: Effect metrics on `telemetry.meterProvider`.
|
|
75
|
+
Counters and frequencies add to OpenTelemetry counters (a counter that is
|
|
76
|
+
not incremental becomes an up-down counter, and a frequency's word is the
|
|
77
|
+
attribute `key`), histograms record with their own boundaries, summaries
|
|
78
|
+
record into a histogram, and gauges are observed at each collection.
|
|
79
|
+
Pull-only `Counter`, `Frequency` and `Gauge` series registered through
|
|
80
|
+
`Metric.registerUnsafe` are bridged via `ObservableCounter`,
|
|
81
|
+
`ObservableUpDownCounter` and `ObservableGauge`. A measurement inside a
|
|
82
|
+
sampled Effect span carries an exemplar of it.
|
|
83
|
+
|
|
84
|
+
By default the libo11y logger replaces Effect's loggers. It has a console
|
|
85
|
+
sink of its own, so Effect's default console logger would print every record
|
|
86
|
+
a second time. `options.logger` is `"replace"` (the default), `"merge"` to
|
|
87
|
+
keep the loggers already installed, or `"none"`. `options.metrics: false`
|
|
88
|
+
leaves metrics out.
|
|
89
|
+
|
|
90
|
+
`layer` also provides `Libo11yTelemetry`, the telemetry as a service, and
|
|
91
|
+
`@effect/opentelemetry`'s `OtelTracer` service.
|
|
92
|
+
|
|
93
|
+
## Owning the telemetry
|
|
94
|
+
|
|
95
|
+
`layerScoped(acquire, options?)` sets the telemetry up with `acquire` and
|
|
96
|
+
shuts it down when the layer's scope closes, with `options.shutdown` as the
|
|
97
|
+
deadline. A setup that rejects fails the layer with `Cause.UnknownError`
|
|
98
|
+
whose cause is the `O11yError`:
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import { flush, layerScoped } from "@libo11y/effect";
|
|
102
|
+
import { setup } from "@libo11y/server";
|
|
103
|
+
import { Effect } from "effect";
|
|
104
|
+
|
|
105
|
+
const Observability = layerScoped(() => setup({ serviceName: "worker", environment: "production" }));
|
|
106
|
+
|
|
107
|
+
await Effect.runPromise(
|
|
108
|
+
Effect.gen(function* () {
|
|
109
|
+
yield* Effect.log("job done").pipe(Effect.withSpan("job"));
|
|
110
|
+
yield* flush;
|
|
111
|
+
}).pipe(Effect.provide(Observability)),
|
|
112
|
+
);
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`flush` is an Effect that calls `forceFlush` on the `Libo11yTelemetry` in
|
|
116
|
+
context and succeeds with its `SignalReport`; `flushWith(options)` takes a
|
|
117
|
+
deadline. Neither fails.
|
|
118
|
+
|
|
119
|
+
## Client tracing and single-carrier RPC propagation
|
|
120
|
+
|
|
121
|
+
Browser and React Native clients often load telemetry lazily after first
|
|
122
|
+
paint and gate trace propagation on consent, kill switches and allowed
|
|
123
|
+
origins. `@libo11y/effect` provides late-bound client layers that enforce
|
|
124
|
+
one gated carrier per hop:
|
|
125
|
+
|
|
126
|
+
- `createTelemetryRef(initial?)`: mutable reference to a `Telemetry` handle.
|
|
127
|
+
While unset, spans, logs, metrics and outbound trace propagation stay dark;
|
|
128
|
+
calling `ref.set(telemetry)` activates them seamlessly.
|
|
129
|
+
- `clientLayer(telemetryOrRef, options?)`: installs Effect's Tracer (via
|
|
130
|
+
`OtelTracer.layerWithoutOtelTracer`, creating no duplicate SDK), Logger
|
|
131
|
+
and Metrics over a concrete `Telemetry` or live `TelemetryRef`.
|
|
132
|
+
- `httpClientLayer(telemetryOrRef, options?)`: wraps `FetchHttpClient.layer`
|
|
133
|
+
with `HttpClient.TracerPropagationEnabled = false` (suppressing Effect's
|
|
134
|
+
`b3` and ungated `traceparent` while keeping Effect's `CLIENT` HTTP span),
|
|
135
|
+
uses the platform's untraced `fetch` (`pristineFetch` on web, depth-guarded
|
|
136
|
+
`untracedFetch` on bare React Native so XHR instrumentation emits no
|
|
137
|
+
duplicate span), strips all configured `propagator.fields()` (plus
|
|
138
|
+
`options.propagatorFields` / W3C defaults) before injection and on blocked
|
|
139
|
+
requests, and applies runtime-explicit redirect handling:
|
|
140
|
+
- Server (`"server"`, Node, Bun, Workers): hop-by-hop validation using
|
|
141
|
+
`redirect: "manual"`, stripping propagation headers (and cross-origin
|
|
142
|
+
`authorization`/`cookie`) on unapproved or ignored hops.
|
|
143
|
+
- Browser (`"browser"`): keeps `redirect: "follow"` by default on generic
|
|
144
|
+
`httpClientLayer` (overridable to `"error"`), and defaults to
|
|
145
|
+
`redirect: "error"` on `rpcProtocolHttpLayer` (overridable to
|
|
146
|
+
`"follow"`).
|
|
147
|
+
- React Native (`"react-native"`): runs over `untracedFetch` (`whatwg-fetch`
|
|
148
|
+
over XHR ignores `redirect` mode in JS; list only trusted non-redirecting
|
|
149
|
+
API origins in `propagateTo`).
|
|
150
|
+
- `stripHttpRpcSerialization(serializationLayer)` and
|
|
151
|
+
`rpcProtocolHttpLayer(telemetryOrRef, options)`: strip `{ traceId, spanId, sampled }`
|
|
152
|
+
from HTTP RPC `Request` bodies at the `RpcSerialization` encode boundary
|
|
153
|
+
so HTTP headers are the sole carrier while preserving direct parent
|
|
154
|
+
ancestry on unbatched HTTP RPC and `RpcClient.batch` span links on batched
|
|
155
|
+
HTTP RPC.
|
|
156
|
+
- `webSocketConstructorLayer(telemetryOrRef, options?)`,
|
|
157
|
+
`gateWebSocketConstructor(ctor, telemetryOrRef, options?)` and
|
|
158
|
+
`gateSocketRpcProtocol(protocolLayer, telemetryOrRef, options)`: evaluate
|
|
159
|
+
recording and destination gates synchronously right before wire `ws.send()`
|
|
160
|
+
(after Effect's `Socket.fromWebSocket` `latch.whenOpen` resumes) so frames
|
|
161
|
+
queued while opening or reconnecting have `{ traceId, spanId, sampled }`
|
|
162
|
+
scrubbed if consent is revoked or the `ws:`/`wss:` origin is disallowed.
|
|
163
|
+
Use `gateSocketRpcProtocol` for custom transports or binary serializations.
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
import {
|
|
167
|
+
clientLayer,
|
|
168
|
+
createTelemetryRef,
|
|
169
|
+
rpcProtocolHttpLayer,
|
|
170
|
+
webSocketConstructorLayer,
|
|
171
|
+
} from "@libo11y/effect";
|
|
172
|
+
import { Layer } from "effect";
|
|
173
|
+
|
|
174
|
+
export const telemetryRef = createTelemetryRef();
|
|
175
|
+
export const ClientTelemetry = clientLayer(telemetryRef);
|
|
176
|
+
export const ApiRpcProtocol = rpcProtocolHttpLayer(telemetryRef, {
|
|
177
|
+
url: "https://api.example.com/rpc",
|
|
178
|
+
});
|
|
179
|
+
export const ChannelWebSocket = webSocketConstructorLayer(telemetryRef);
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
## Cloudflare Workers and detached context
|
|
183
|
+
|
|
184
|
+
Build the app once per isolate and flush after every request through
|
|
185
|
+
`waitUntil`. Effect's `HttpServer` makes the server span, so call `setup`
|
|
186
|
+
and `scheduleFlush` from `@libo11y/workers` (or `instrument(handler, { serve: false })`):
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
import { layer } from "@libo11y/effect";
|
|
190
|
+
import { scheduleFlush, setup, type WorkersOptions } from "@libo11y/workers";
|
|
191
|
+
import { Effect, Layer } from "effect";
|
|
192
|
+
import { HttpRouter, HttpServerResponse } from "effect/http";
|
|
193
|
+
|
|
194
|
+
interface Env {
|
|
195
|
+
readonly ENVIRONMENT: string;
|
|
196
|
+
readonly OTLP: Fetcher; // a service binding or a Workers VPC binding to the collector
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const Routes = HttpRouter.add(
|
|
200
|
+
"GET",
|
|
201
|
+
"/items/:id",
|
|
202
|
+
Effect.gen(function* () {
|
|
203
|
+
yield* Effect.log("looking up");
|
|
204
|
+
return HttpServerResponse.text("found");
|
|
205
|
+
}),
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
const options = (env: Env): WorkersOptions => ({
|
|
209
|
+
serviceName: "api",
|
|
210
|
+
environment: env.ENVIRONMENT,
|
|
211
|
+
env,
|
|
212
|
+
exporter: {
|
|
213
|
+
endpoint: "http://alloy.o11y.svc.cluster.local:4318",
|
|
214
|
+
fetch: (req) => env.OTLP.fetch(req),
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
let app: { readonly handler: (request: Request) => Promise<Response> } | undefined;
|
|
219
|
+
|
|
220
|
+
export default {
|
|
221
|
+
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
|
222
|
+
const telemetry = await setup(options(env));
|
|
223
|
+
app ??= HttpRouter.toWebHandler(Layer.mergeAll(Routes, layer(telemetry)));
|
|
224
|
+
try {
|
|
225
|
+
return await app.handler(request);
|
|
226
|
+
} finally {
|
|
227
|
+
scheduleFlush(ctx, telemetry);
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
} satisfies ExportedHandler<Env>;
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
For Durable Objects, alarms, cron triggers, queues and outbox handoffs,
|
|
234
|
+
`@libo11y/effect` provides thin Effect combinators over `@libo11y/core`'s
|
|
235
|
+
detached `Carrier` and `@libo11y/core/edge`'s semconv 1.41.0 span builders:
|
|
236
|
+
|
|
237
|
+
- `captureContext`: captures the active fiber's propagated span context and
|
|
238
|
+
egress-filtered baggage into a detached `Carrier`.
|
|
239
|
+
- `withLinkedContext(carrier, name, options?)` and `linkCarriers(carriers)`:
|
|
240
|
+
start a linked root span with merged carrier baggage, or attach deduplicated
|
|
241
|
+
carrier links onto the active span.
|
|
242
|
+
- `traceDurableObjectMethods(className, methods)`,
|
|
243
|
+
`traceDurableObjectCall(className, method)`,
|
|
244
|
+
`traceDurableObjectStub(className, stub)` (preserving dual Effect/Stream
|
|
245
|
+
return values) and `enrichDurableObjectRpc(className, handlers)`: emit or
|
|
246
|
+
enrich semconv 1.41.0 Durable Object spans (`<Class>/<method>`,
|
|
247
|
+
`rpc.system.name: "cloudflare_durable_object"`, `o11y.durable_object.class`).
|
|
248
|
+
- `withAlarmSpan(className, callback, links?)`: root `SERVER` alarm span
|
|
249
|
+
with `faas.trigger: "timer"` and optional carrier links.
|
|
250
|
+
- `withCronSpan(cron, jobOrOptions?)`: root `SERVER` scheduled span with
|
|
251
|
+
`faas.trigger: "timer"`, `faas.cron` and optional ISO `faas.time`.
|
|
252
|
+
- `withQueueBatchSpan(queue, options?)`: wraps a streaming queue consumer in
|
|
253
|
+
a root `CONSUMER` span (`process <queue>`), extracting deduplicated `_o11y`
|
|
254
|
+
carriers as span links, recording `messaging.batch.message_count`, and
|
|
255
|
+
invoking `options.onBatchCount(count)`.
|
|
256
|
+
|
|
257
|
+
## Testing
|
|
258
|
+
|
|
259
|
+
Pass a [`@libo11y/test`](https://github.com/libo11y/libo11y/tree/main/ts/packages/test) recorder's telemetry to `layer` and
|
|
260
|
+
assert on what the program emitted:
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
import { createRecorder } from "@libo11y/test";
|
|
264
|
+
|
|
265
|
+
const rec = await createRecorder();
|
|
266
|
+
await Effect.runPromise(program.pipe(Effect.provide(layer(rec.telemetry))));
|
|
267
|
+
rec.assertCorrelated();
|
|
268
|
+
await rec.assertTriangle({ metric: "orders" });
|
|
269
|
+
await rec.shutdown();
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
## Known limitations
|
|
273
|
+
|
|
274
|
+
- Pull-only `Histogram` and `Summary` series registered via
|
|
275
|
+
`Metric.registerUnsafe` are not bridged because OpenTelemetry JS has no
|
|
276
|
+
observable histogram or summary instrument (`Counter`, `Frequency` and
|
|
277
|
+
`Gauge` registrations are bridged via `Observable*` instruments).
|
|
278
|
+
- Effect metrics have no unit, so the instruments have none.
|
|
279
|
+
- Without a global OpenTelemetry context manager, as with a telemetry from
|
|
280
|
+
`createTelemetry` and no recorder, log records are not correlated. The
|
|
281
|
+
`setup` of every platform package installs one.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Effect 4 client telemetry and single-carrier gated propagation layers:
|
|
3
|
+
*
|
|
4
|
+
* - createTelemetryRef / clientLayer: late-bound Effect Tracer, Logger, and Metrics layers built on
|
|
5
|
+
* @effect/opentelemetry's OtelTracer.layerWithoutOtelTracer (never creating a duplicate SDK) so
|
|
6
|
+
* module-level runtimes activate seamlessly once lazy browser RUM or native setup finishes.
|
|
7
|
+
* - httpClientLayer / stripHttpRpcSerialization / rpcProtocolHttpLayer: enforces one gated carrier
|
|
8
|
+
* per HTTP hop. Injects configured propagator headers inside FetchHttpClient.Fetch with
|
|
9
|
+
* HttpClient.TracerPropagationEnabled = false, uses PropagationConfig.fetch (pristineFetch on
|
|
10
|
+
* web, depth-guarded untracedFetch on bare React Native), strips all propagator fields before
|
|
11
|
+
* injection and on blocked requests, applies runtime-explicit redirect handling, and strips
|
|
12
|
+
* { traceId, spanId, sampled } from HTTP RPC request bodies at the RpcSerialization boundary.
|
|
13
|
+
* - gateWebSocketConstructor / webSocketConstructorLayer / gateSocketRpcProtocol: enforces
|
|
14
|
+
* write-time consent and destination gating on WebSocket RPC envelopes right before wire send
|
|
15
|
+
* (after Socket.fromWebSocket's latch.whenOpen resumes), plus protocol-level gating for custom
|
|
16
|
+
* or binary socket serializations.
|
|
17
|
+
*/
|
|
18
|
+
import * as OtelTracer from "@effect/opentelemetry/OtelTracer";
|
|
19
|
+
import type { Telemetry } from "@libo11y/core";
|
|
20
|
+
import type * as Duration from "effect/Duration";
|
|
21
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
22
|
+
import * as Layer from "effect/Layer";
|
|
23
|
+
import * as RpcClient from "effect/rpc/RpcClient";
|
|
24
|
+
import * as RpcSerialization from "effect/rpc/RpcSerialization";
|
|
25
|
+
import * as Socket from "effect/socket/Socket";
|
|
26
|
+
/** Runtime category controlling HTTP redirect handling when trace headers are injected. */
|
|
27
|
+
export type ClientRuntime = "browser" | "react-native" | "server";
|
|
28
|
+
/** Fetch redirect handling mode. */
|
|
29
|
+
export type RedirectMode = "error" | "follow" | "manual";
|
|
30
|
+
/**
|
|
31
|
+
* Mutable reference to a libo11y Telemetry handle for late-bound client setups (such as
|
|
32
|
+
* after-first-paint dynamic RUM loading in browsers). While unset (undefined), telemetry stays dark
|
|
33
|
+
* and outbound trace propagation is suppressed.
|
|
34
|
+
*/
|
|
35
|
+
export interface TelemetryRef {
|
|
36
|
+
get(): Telemetry | undefined;
|
|
37
|
+
set(telemetry: Telemetry | undefined): void;
|
|
38
|
+
}
|
|
39
|
+
/** Either a concrete Telemetry handle or a live TelemetryRef. */
|
|
40
|
+
export type TelemetrySource = Telemetry | TelemetryRef;
|
|
41
|
+
/** Creates a live TelemetryRef, optionally seeded with an already-initialized Telemetry handle. */
|
|
42
|
+
export declare function createTelemetryRef(initial?: Telemetry): TelemetryRef;
|
|
43
|
+
/** Options for {@link clientLayer}. */
|
|
44
|
+
export interface ClientLayerOptions {
|
|
45
|
+
/**
|
|
46
|
+
* How the libo11y logger joins Effect's loggers. "replace" (default) replaces Effect's loggers,
|
|
47
|
+
* "merge" keeps existing loggers beside it, and "none" installs no logger.
|
|
48
|
+
*/
|
|
49
|
+
readonly logger?: "replace" | "merge" | "none";
|
|
50
|
+
/** Bridge Effect metrics to the telemetry's meter provider once loaded. Default true. */
|
|
51
|
+
readonly metrics?: boolean;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Installs an Effect Tracer, Logger, and Metrics bridge over a concrete Telemetry or live
|
|
55
|
+
* TelemetryRef using `@effect/opentelemetry`'s `OtelTracer.layerWithoutOtelTracer` (never creating
|
|
56
|
+
* a duplicate SDK or touching globals). When backed by a TelemetryRef that starts undefined, spans
|
|
57
|
+
* and logs stay silent until `ref.set(telemetry)` runs and activate seamlessly thereafter.
|
|
58
|
+
*/
|
|
59
|
+
export declare function clientLayer(telemetryOrRef: TelemetrySource, options?: ClientLayerOptions): Layer.Layer<OtelTracer.OtelTracer>;
|
|
60
|
+
/** Options for {@link httpClientLayer}. */
|
|
61
|
+
export interface HttpClientLayerOptions {
|
|
62
|
+
/**
|
|
63
|
+
* Additional propagation header names to strip before injection and on blocked requests, even
|
|
64
|
+
* before a lazy TelemetryRef finishes loading. Always unioned with `telemetry.propagator.fields()`
|
|
65
|
+
* (or `["traceparent", "tracestate", "baggage"]` while dark/unloaded).
|
|
66
|
+
*/
|
|
67
|
+
readonly propagatorFields?: readonly string[];
|
|
68
|
+
/**
|
|
69
|
+
* Fetch redirect mode override. On server runtimes (`"server"`), `"follow"` (default) validates
|
|
70
|
+
* redirects hop-by-hop with `redirect: "manual"` so disallowed hops never receive trace headers.
|
|
71
|
+
* On browsers (`"browser"`), generic `httpClientLayer` defaults to `"follow"` (overridable to
|
|
72
|
+
* `"error"`), while `rpcProtocolHttpLayer` defaults to `"error"` (overridable to `"follow"`).
|
|
73
|
+
*/
|
|
74
|
+
readonly redirect?: RedirectMode;
|
|
75
|
+
/** Maximum redirect hops followed in server hop-by-hop mode. Default 20. */
|
|
76
|
+
readonly maxRedirects?: number;
|
|
77
|
+
/** Explicit runtime override when the Telemetry handle carries no PropagationConfig metadata. */
|
|
78
|
+
readonly runtime?: ClientRuntime;
|
|
79
|
+
/** Optional additional destination gate predicate (ANDed with Telemetry's PropagationConfig). */
|
|
80
|
+
readonly shouldPropagate?: (url: URL) => boolean;
|
|
81
|
+
/** Optional additional ignore predicate (ORed with Telemetry's PropagationConfig). */
|
|
82
|
+
readonly isIgnored?: (url: URL) => boolean;
|
|
83
|
+
/** Optional fetch implementation override (takes precedence over PropagationConfig.fetch). */
|
|
84
|
+
readonly fetch?: typeof fetch;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Provides an Effect `HttpClient` over `FetchHttpClient` with gated single-carrier propagation:
|
|
88
|
+
*
|
|
89
|
+
* - Disables Effect's built-in `b3` + ungated `traceparent` injection
|
|
90
|
+
* (`HttpClient.TracerPropagationEnabled = false`) while keeping Effect's `CLIENT` HTTP span.
|
|
91
|
+
* - Uses `PropagationConfig.fetch` (`pristineFetch` on web, `depth`-guarded `untracedFetch` on
|
|
92
|
+
* bare React Native) so global RUM fetch/XHR patches never emit duplicate spans or headers.
|
|
93
|
+
* - Strips all configured `propagator.fields()` (plus `options.propagatorFields` / W3C defaults)
|
|
94
|
+
* before injection and on blocked requests.
|
|
95
|
+
* - Applies runtime-explicit redirect handling (`"server"`: hop-by-hop manual validation;
|
|
96
|
+
* `"browser"`: preserves `"follow"` by default, overridable via `redirect: "error"`;
|
|
97
|
+
* `"react-native"`: runs over `untracedFetch`).
|
|
98
|
+
*/
|
|
99
|
+
export declare function httpClientLayer(telemetryOrRef: TelemetrySource, options?: HttpClientLayerOptions): Layer.Layer<HttpClient.HttpClient>;
|
|
100
|
+
/**
|
|
101
|
+
* Wraps an Effect `RpcSerialization` layer so HTTP RPC requests omit `{ traceId, spanId, sampled }`
|
|
102
|
+
* from encoded `Request` envelopes (single or batched arrays) right before wire serialization.
|
|
103
|
+
*
|
|
104
|
+
* Preserves Effect's `HttpClient` spans and batched `RpcClient.batch` `withBatchSpan` links
|
|
105
|
+
* (unlike `Tracer.DisablePropagation`, which turns spans into no-ops).
|
|
106
|
+
*/
|
|
107
|
+
export declare function stripHttpRpcSerialization<E, R>(serializationLayer: Layer.Layer<RpcSerialization.RpcSerialization, E, R>): Layer.Layer<RpcSerialization.RpcSerialization, E, R>;
|
|
108
|
+
/** Options for {@link rpcProtocolHttpLayer}. */
|
|
109
|
+
export interface RpcProtocolHttpLayerOptions<E = never, R = never> extends HttpClientLayerOptions {
|
|
110
|
+
/** Target HTTP RPC endpoint URL. */
|
|
111
|
+
readonly url: string;
|
|
112
|
+
/** Optional HttpClient transformer (for example, attaching auth headers). */
|
|
113
|
+
readonly transformClient?: <CE, CR>(client: HttpClient.HttpClient.With<CE, CR>) => HttpClient.HttpClient.With<CE, CR>;
|
|
114
|
+
/** Optional HTTP RPC batching configuration. */
|
|
115
|
+
readonly batch?: {
|
|
116
|
+
readonly window: Duration.Input;
|
|
117
|
+
readonly maxSize?: number | undefined;
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* RPC serialization layer wrapped with {@link stripHttpRpcSerialization}.
|
|
121
|
+
* Defaults to `RpcSerialization.layerNdjson`.
|
|
122
|
+
*/
|
|
123
|
+
readonly serialization?: Layer.Layer<RpcSerialization.RpcSerialization, E, R>;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Convenience layer for Effect HTTP RPC clients enforcing the single-carrier invariant:
|
|
127
|
+
*
|
|
128
|
+
* - Combines {@link httpClientLayer} (with `redirect: "error"` by default on `"browser"` so Effect
|
|
129
|
+
* HTTP RPC POSTs never carry trace headers across redirects, overridable via `redirect: "follow"`,
|
|
130
|
+
* and hop-by-hop manual redirect validation on `"server"`)
|
|
131
|
+
* - With {@link stripHttpRpcSerialization} (defaulting to `RpcSerialization.layerNdjson`) so HTTP
|
|
132
|
+
* RPC request bodies carry no `{ traceId, spanId, sampled }` fields.
|
|
133
|
+
*/
|
|
134
|
+
export declare function rpcProtocolHttpLayer<E = never, R = never>(telemetryOrRef: TelemetrySource, options: RpcProtocolHttpLayerOptions<E, R>): Layer.Layer<RpcClient.Protocol, E, R>;
|
|
135
|
+
/** Options for WebSocket write-time trace gating. */
|
|
136
|
+
export interface WebSocketGateOptions {
|
|
137
|
+
/** Optional additional destination gate predicate (ANDed with Telemetry's PropagationConfig). */
|
|
138
|
+
readonly shouldPropagate?: (url: URL) => boolean;
|
|
139
|
+
/** Optional additional ignore predicate (ORed with Telemetry's PropagationConfig). */
|
|
140
|
+
readonly isIgnored?: (url: URL) => boolean;
|
|
141
|
+
}
|
|
142
|
+
/** Function signature of Effect's `Socket.WebSocketConstructor` service. */
|
|
143
|
+
export type WebSocketConstructorFn = Socket.WebSocketConstructor["Service"];
|
|
144
|
+
/**
|
|
145
|
+
* Wraps a `Socket.WebSocketConstructor` function so every opened `WebSocketLike` evaluates the
|
|
146
|
+
* telemetry recording and destination gate synchronously at `ws.send()` time (after Effect's
|
|
147
|
+
* `Socket.fromWebSocket` `latch.whenOpen` resumes).
|
|
148
|
+
*
|
|
149
|
+
* When the gate is closed (before setup, pending consent, revoked while opening/reconnecting,
|
|
150
|
+
* killed/safe mode, or disallowed/ignored `ws:`/`wss:` origin), strips `{ traceId, spanId, sampled }`
|
|
151
|
+
* from outbound JSON and NDJSON RPC Request frames right before wire transmission. For binary
|
|
152
|
+
* serializations, pair with {@link gateSocketRpcProtocol}.
|
|
153
|
+
*/
|
|
154
|
+
export declare function gateWebSocketConstructor(ctor: WebSocketConstructorFn, telemetryOrRef: TelemetrySource, options?: WebSocketGateOptions): WebSocketConstructorFn;
|
|
155
|
+
/** Options for {@link webSocketConstructorLayer}. */
|
|
156
|
+
export interface WebSocketConstructorLayerOptions extends WebSocketGateOptions {
|
|
157
|
+
/** Custom underlying WebSocket constructor. Defaults to `globalThis.WebSocket`. */
|
|
158
|
+
readonly webSocketConstructor?: WebSocketConstructorFn;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Drop-in replacement for `Socket.layerWebSocketConstructorGlobal` that enforces write-time
|
|
162
|
+
* propagation gating on every WebSocket RPC frame right before `ws.send()`.
|
|
163
|
+
*/
|
|
164
|
+
export declare function webSocketConstructorLayer(telemetryOrRef: TelemetrySource, options?: WebSocketConstructorLayerOptions): Layer.Layer<Socket.WebSocketConstructor>;
|
|
165
|
+
/** Options for {@link gateSocketRpcProtocol}. */
|
|
166
|
+
export interface SocketRpcProtocolGateOptions extends WebSocketGateOptions {
|
|
167
|
+
/** Target WebSocket endpoint URL (or lazy getter) evaluated against the destination gate. */
|
|
168
|
+
readonly url: string | URL | (() => string | URL);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Wraps an Effect `RpcClient.Protocol` layer to gate `{ traceId, spanId, sampled }` at
|
|
172
|
+
* `Protocol.send` before serialization. Use for custom socket protocols or binary RPC
|
|
173
|
+
* serializations (where wire-level JSON/NDJSON scrubbing in `webSocketConstructorLayer` does not
|
|
174
|
+
* inspect binary frames).
|
|
175
|
+
*/
|
|
176
|
+
export declare function gateSocketRpcProtocol<E, R>(protocolLayer: Layer.Layer<RpcClient.Protocol, E, R>, telemetryOrRef: TelemetrySource, options: SocketRpcProtocolGateOptions): Layer.Layer<RpcClient.Protocol, E, R>;
|