@libo11y/effect 0.0.0-stage → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE 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,217 @@
1
- # Temporary Holding Version
1
+ # @libo11y/effect
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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, or
7
+ [`@libo11y/web`](https://github.com/libo11y/libo11y/tree/main/ts/packages/web) in browsers. Effect spans, logs and metrics are
8
+ then exported, correlated and redacted with everything else the telemetry
9
+ exports.
10
+
11
+ ```sh
12
+ npm install @libo11y/effect effect @effect/opentelemetry
13
+ ```
14
+
15
+ The package first ships in `ts/v0.8.0`. Until its first npm publish,
16
+ install it from the tarball on the
17
+ [`ts/v0.8.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.8.0):
18
+ `npm install https://github.com/libo11y/libo11y/releases/download/ts/v0.8.0/libo11y-effect-0.8.0.tgz`.
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
+ libo11y wraps setup, not instrumentation, so the package is layers and two
26
+ small helpers, and no span or metric wrapper types. Write Effect as usual:
27
+ `Effect.withSpan`, `Effect.log`, `Effect.annotateLogs`, `Metric.counter`.
28
+
29
+ ## Quick start
30
+
31
+ ```ts
32
+ import { layer } from "@libo11y/effect";
33
+ import { setup } from "@libo11y/server";
34
+ import { Effect } from "effect";
35
+
36
+ const telemetry = await setup({ serviceName: "checkout", environment: "production" });
37
+
38
+ const program = Effect.log("order placed").pipe(
39
+ Effect.annotateLogs({ "order.id": "ord-42" }),
40
+ Effect.withSpan("checkout.place"),
41
+ );
42
+
43
+ await Effect.runPromise(program.pipe(Effect.provide(layer(telemetry))));
44
+ await telemetry.shutdown();
45
+ ```
46
+
47
+ ## What the layer installs
48
+
49
+ `layer(telemetry, options?)` merges three layers, each also exported on
50
+ its own:
51
+
52
+ - `tracerLayer(telemetry)`: the Effect `Tracer` over
53
+ `telemetry.tracerProvider`, from `@effect/opentelemetry`'s `OtelTracer`.
54
+ Effect spans, including those of Effect's `HttpServer`, `HttpClient`, RPC
55
+ and SQL modules, become OpenTelemetry spans of that provider, so they pass
56
+ libo11y's sampler and redaction and land in the same traces as other
57
+ spans. An inbound W3C `traceparent` that Effect's `HttpServer` reads
58
+ becomes the parent of its server span, and an Effect span started inside
59
+ an active OpenTelemetry span is its child. While a traced effect runs, its
60
+ span is the active OpenTelemetry span, so `instrumentFetch` and other
61
+ OpenTelemetry code see it. The instrumentation scope is `effect`.
62
+ - `loggerLayer(telemetry)`: an Effect `Logger` (`makeLogger(telemetry)`)
63
+ that writes each record through `telemetry.logger`, to the console sink
64
+ and the OTLP leg. Records carry the trace and span IDs of the fiber's
65
+ Effect span. Log annotations become attributes, plain objects staying
66
+ groups; log spans become `effect.log_span.<label>` in milliseconds; a
67
+ failure or defect in the cause becomes `exception.type`,
68
+ `exception.message` and `exception.stacktrace`. The sensitivity policy
69
+ drops secret and PII attributes by key, as for every libo11y record.
70
+ Effect's `MinimumLogLevel` filters first, then libo11y's `logLevel`.
71
+ - `metricsLayer(telemetry)`: Effect metrics on `telemetry.meterProvider`.
72
+ Counters and frequencies add to OpenTelemetry counters (a counter that is
73
+ not incremental becomes an up-down counter, and a frequency's word is the
74
+ attribute `key`), histograms record with their own boundaries, summaries
75
+ record into a histogram, and gauges are observed at each collection. A
76
+ measurement inside a sampled Effect span carries an exemplar of it.
77
+
78
+ By default the libo11y logger replaces Effect's loggers. It has a console
79
+ sink of its own, so Effect's default console logger would print every record
80
+ a second time. `options.logger` is `"replace"` (the default), `"merge"` to
81
+ keep the loggers already installed, or `"none"`. `options.metrics: false`
82
+ leaves metrics out.
83
+
84
+ `layer` also provides `Libo11yTelemetry`, the telemetry as a service, and
85
+ `@effect/opentelemetry`'s `OtelTracer` service.
86
+
87
+ ## Owning the telemetry
88
+
89
+ `layerScoped(acquire, options?)` sets the telemetry up with `acquire` and
90
+ shuts it down when the layer's scope closes, with `options.shutdown` as the
91
+ deadline. A setup that rejects fails the layer with `Cause.UnknownError`
92
+ whose cause is the `O11yError`:
93
+
94
+ ```ts
95
+ import { flush, layerScoped } from "@libo11y/effect";
96
+ import { setup } from "@libo11y/server";
97
+ import { Effect, Layer } from "effect";
98
+
99
+ const Observability = layerScoped(() => setup({ serviceName: "worker", environment: "production" }));
100
+
101
+ await Effect.runPromise(
102
+ Effect.gen(function* () {
103
+ yield* Effect.log("job done").pipe(Effect.withSpan("job"));
104
+ yield* flush;
105
+ }).pipe(Effect.provide(Observability)),
106
+ );
107
+ ```
108
+
109
+ `flush` is an Effect that calls `forceFlush` on the `Libo11yTelemetry` in
110
+ context and succeeds with its `SignalReport`; `flushWith(options)` takes a
111
+ deadline. Neither fails.
112
+
113
+ ## Cloudflare Workers
114
+
115
+ Build the app once per isolate and flush after every request through
116
+ `waitUntil`. Effect's `HttpServer` makes the server span, so call `setup`
117
+ and `scheduleFlush` from `@libo11y/workers` rather than `instrument`:
118
+
119
+ ```ts
120
+ import { layer } from "@libo11y/effect";
121
+ import { scheduleFlush, setup, type WorkersOptions } from "@libo11y/workers";
122
+ import { Effect, Layer } from "effect";
123
+ import { HttpRouter, HttpServerResponse } from "effect/http";
124
+
125
+ interface Env {
126
+ readonly ENVIRONMENT: string;
127
+ readonly OTLP: Fetcher; // a service binding or a Workers VPC binding to the collector
128
+ }
129
+
130
+ const Routes = HttpRouter.add(
131
+ "GET",
132
+ "/items/:id",
133
+ Effect.gen(function* () {
134
+ yield* Effect.log("looking up");
135
+ return HttpServerResponse.text("found");
136
+ }),
137
+ );
138
+
139
+ const options = (env: Env): WorkersOptions => ({
140
+ serviceName: "api",
141
+ environment: env.ENVIRONMENT,
142
+ env,
143
+ exporter: {
144
+ endpoint: "http://alloy.o11y.svc.cluster.local:4318",
145
+ fetch: (req) => env.OTLP.fetch(req),
146
+ },
147
+ });
148
+
149
+ let app: { readonly handler: (request: Request) => Promise<Response> } | undefined;
150
+
151
+ export default {
152
+ async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
153
+ const telemetry = await setup(options(env));
154
+ app ??= HttpRouter.toWebHandler(Layer.mergeAll(Routes, layer(telemetry)));
155
+ try {
156
+ return await app.handler(request);
157
+ } finally {
158
+ scheduleFlush(ctx, telemetry);
159
+ }
160
+ },
161
+ } satisfies ExportedHandler<Env>;
162
+ ```
163
+
164
+ A queue consumer or a Durable Object runs its effects with a runtime built
165
+ once per isolate:
166
+
167
+ ```ts
168
+ import { type Libo11yServices, layer } from "@libo11y/effect";
169
+ import { ManagedRuntime } from "effect";
170
+
171
+ let runtime: ManagedRuntime.ManagedRuntime<Libo11yServices, never> | undefined;
172
+
173
+ export default {
174
+ async queue(batch: MessageBatch, env: Env, ctx: ExecutionContext): Promise<void> {
175
+ const telemetry = await setup(options(env));
176
+ runtime ??= ManagedRuntime.make(layer(telemetry));
177
+ try {
178
+ await runtime.runPromise(
179
+ Effect.forEach(batch.messages, (m) => handle(m)).pipe(
180
+ Effect.withSpan(`process ${batch.queue}`, { kind: "consumer" }),
181
+ ),
182
+ );
183
+ } finally {
184
+ scheduleFlush(ctx, telemetry);
185
+ }
186
+ },
187
+ } satisfies ExportedHandler<Env>;
188
+ ```
189
+
190
+ In a Durable Object, flush through the object's own state:
191
+ `scheduleFlush(this.ctx, telemetry)`.
192
+
193
+ ## Testing
194
+
195
+ Pass a [`@libo11y/test`](https://github.com/libo11y/libo11y/tree/main/ts/packages/test) recorder's telemetry to `layer` and
196
+ assert on what the program emitted:
197
+
198
+ ```ts
199
+ import { createRecorder } from "@libo11y/test";
200
+
201
+ const rec = await createRecorder();
202
+ await Effect.runPromise(program.pipe(Effect.provide(layer(rec.telemetry))));
203
+ rec.assertCorrelated();
204
+ await rec.assertTriangle({ metric: "orders" });
205
+ await rec.shutdown();
206
+ ```
207
+
208
+ ## Known limitations
209
+
210
+ - The metrics bridge provides Effect's `MetricRegistry` with a registry that
211
+ wraps each series' update hook as Effect registers it. A series registered
212
+ with `Metric.registerUnsafe` reports through its read hook only, so only
213
+ gauges registered that way are exported.
214
+ - Effect metrics have no unit, so the instruments have none.
215
+ - Without a global OpenTelemetry context manager, as with a telemetry from
216
+ `createTelemetry` and no recorder, log records are not correlated. The
217
+ `setup` of every platform package installs one.
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The libo11y bridge for Effect 4. It wraps setup, not instrumentation: layers that report an
3
+ * Effect program to a libo11y telemetry from any platform package (@libo11y/server,
4
+ * @libo11y/workers, @libo11y/web), so Effect spans, logs and metrics are exported, correlated and
5
+ * redacted with everything else the telemetry exports.
6
+ */
7
+ export { flush, flushWith, type LayerOptions, type Libo11yServices, Libo11yTelemetry, layer, layerScoped, type ScopedLayerOptions, } from "./layer.ts";
8
+ export { type LoggerLayerOptions, loggerLayer, makeLogger } from "./logger.ts";
9
+ export { metricsLayer } from "./metrics.ts";
10
+ export { tracerLayer } from "./tracer.ts";
11
+ export { VERSION } from "./version.ts";
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The libo11y bridge for Effect 4. It wraps setup, not instrumentation: layers that report an
3
+ * Effect program to a libo11y telemetry from any platform package (@libo11y/server,
4
+ * @libo11y/workers, @libo11y/web), so Effect spans, logs and metrics are exported, correlated and
5
+ * redacted with everything else the telemetry exports.
6
+ */
7
+ export { flush, flushWith, Libo11yTelemetry, layer, layerScoped, } from "./layer.js";
8
+ export { loggerLayer, makeLogger } from "./logger.js";
9
+ export { metricsLayer } from "./metrics.js";
10
+ export { tracerLayer } from "./tracer.js";
11
+ export { VERSION } from "./version.js";
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The layers that join an Effect program to a libo11y telemetry: the tracer, the logger and the
3
+ * metrics bridge together, with the telemetry itself as a service so flush can reach it.
4
+ */
5
+ import type * as OtelTracer from "@effect/opentelemetry/OtelTracer";
6
+ import type { LifecycleOptions, SignalReport, Telemetry } from "@libo11y/core";
7
+ import type * as Cause from "effect/Cause";
8
+ import * as Context from "effect/Context";
9
+ import * as Effect from "effect/Effect";
10
+ import * as Layer from "effect/Layer";
11
+ /** The identifier of the Libo11yTelemetry service in an Effect context. */
12
+ export interface Libo11yTelemetry {
13
+ readonly "~@libo11y/effect/Libo11yTelemetry": "~@libo11y/effect/Libo11yTelemetry";
14
+ }
15
+ /** The libo11y telemetry an Effect program reports to, as layer and layerScoped provide it. */
16
+ export declare const Libo11yTelemetry: Context.Service<Libo11yTelemetry, Telemetry>;
17
+ /** Options for layer and layerScoped. */
18
+ export interface LayerOptions {
19
+ /**
20
+ * How the libo11y logger joins Effect's loggers. "replace" (the default) installs it alone: it
21
+ * has a console sink of its own, so Effect's default console logger would print every record a
22
+ * second time. "merge" keeps the loggers already installed beside it. "none" installs no logger.
23
+ */
24
+ readonly logger?: "replace" | "merge" | "none";
25
+ /** Bridge Effect metrics to the telemetry's meter provider. Default true. */
26
+ readonly metrics?: boolean;
27
+ }
28
+ /** What layer provides: the telemetry, and the OtelTracer service of `@effect/opentelemetry`. */
29
+ export type Libo11yServices = Libo11yTelemetry | OtelTracer.OtelTracer;
30
+ /**
31
+ * A layer that reports an Effect program to telemetry: the Effect Tracer over its tracer provider,
32
+ * the Effect Logger over its logger (replacing Effect's default logger unless options.logger says
33
+ * otherwise) and Effect metrics on its meter provider. The telemetry is set up and shut down by
34
+ * its owner; layerScoped owns it instead.
35
+ */
36
+ export declare function layer(telemetry: Telemetry, options?: LayerOptions): Layer.Layer<Libo11yServices>;
37
+ /** Options for layerScoped. */
38
+ export interface ScopedLayerOptions extends LayerOptions {
39
+ /** The deadline of the shutdown when the scope closes. Default core's, 5000 ms. */
40
+ readonly shutdown?: LifecycleOptions;
41
+ }
42
+ /**
43
+ * A layer that sets telemetry up with acquire, such as `() => setup({ ... })` from
44
+ * `@libo11y/server` or `@libo11y/workers`, reports the program to it as layer does, and shuts it down
45
+ * when the layer's scope closes. A setup that rejects fails the layer with Cause.UnknownError,
46
+ * whose cause is the O11yError, and the program decides whether to carry on without telemetry.
47
+ */
48
+ export declare function layerScoped(acquire: () => Promise<Telemetry>, options?: ScopedLayerOptions): Layer.Layer<Libo11yServices, Cause.UnknownError>;
49
+ /** Exports everything the telemetry has buffered, with options' deadline. Never fails. */
50
+ export declare function flushWith(options?: LifecycleOptions): Effect.Effect<SignalReport, never, Libo11yTelemetry>;
51
+ /** Exports everything the telemetry has buffered, with core's default deadline. Never fails. */
52
+ export declare const flush: Effect.Effect<SignalReport, never, Libo11yTelemetry>;
package/dist/layer.js ADDED
@@ -0,0 +1,39 @@
1
+ import * as Context from "effect/Context";
2
+ import * as Effect from "effect/Effect";
3
+ import * as Layer from "effect/Layer";
4
+ import { loggerLayer } from "./logger.js";
5
+ import { metricsLayer } from "./metrics.js";
6
+ import { tracerLayer } from "./tracer.js";
7
+ /** The libo11y telemetry an Effect program reports to, as layer and layerScoped provide it. */
8
+ export const Libo11yTelemetry = Context.Service("@libo11y/effect/Libo11yTelemetry");
9
+ /**
10
+ * A layer that reports an Effect program to telemetry: the Effect Tracer over its tracer provider,
11
+ * the Effect Logger over its logger (replacing Effect's default logger unless options.logger says
12
+ * otherwise) and Effect metrics on its meter provider. The telemetry is set up and shut down by
13
+ * its owner; layerScoped owns it instead.
14
+ */
15
+ export function layer(telemetry, options = {}) {
16
+ const service = Layer.succeed(Libo11yTelemetry, telemetry);
17
+ const tracer = tracerLayer(telemetry);
18
+ const logger = options.logger === "none"
19
+ ? Layer.empty
20
+ : loggerLayer(telemetry, { mergeWithExisting: options.logger === "merge" });
21
+ const metrics = options.metrics === false ? Layer.empty : metricsLayer(telemetry);
22
+ return Layer.mergeAll(service, tracer, logger, metrics);
23
+ }
24
+ /**
25
+ * A layer that sets telemetry up with acquire, such as `() => setup({ ... })` from
26
+ * `@libo11y/server` or `@libo11y/workers`, reports the program to it as layer does, and shuts it down
27
+ * when the layer's scope closes. A setup that rejects fails the layer with Cause.UnknownError,
28
+ * whose cause is the O11yError, and the program decides whether to carry on without telemetry.
29
+ */
30
+ export function layerScoped(acquire, options = {}) {
31
+ const telemetry = Effect.acquireRelease(Effect.tryPromise(() => acquire()), (t) => Effect.promise(() => t.shutdown(options.shutdown)));
32
+ return Layer.unwrap(Effect.map(telemetry, (t) => layer(t, options)));
33
+ }
34
+ /** Exports everything the telemetry has buffered, with options' deadline. Never fails. */
35
+ export function flushWith(options) {
36
+ return Effect.flatMap(Effect.service(Libo11yTelemetry), (t) => Effect.promise(() => t.forceFlush(options)));
37
+ }
38
+ /** Exports everything the telemetry has buffered, with core's default deadline. Never fails. */
39
+ export const flush = flushWith();
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The Effect Logger over a libo11y telemetry. Each Effect log record goes through telemetry.logger,
3
+ * the libo11y logger, so it reaches both of its sinks (the console sink and the OTLP leg) through
4
+ * one pipeline: the level gate, the attribute replacer and the sensitivity policy, which drops
5
+ * secret and PII attributes by key. The record is written in the OpenTelemetry context of the
6
+ * fiber's current Effect span, so it carries that span's trace and span IDs.
7
+ *
8
+ * - The message is the log's text: a string message as it is, any other part rendered with
9
+ * Effect's Inspectable, parts joined by a space.
10
+ * - The level maps one to one (Trace, Debug, Info, Warn, Error, Fatal); All is trace and None is
11
+ * not logged. libo11y's own logLevel still applies after Effect's MinimumLogLevel.
12
+ * - Log annotations become attributes under their own keys. Plain objects stay groups, so the
13
+ * policy judges each member on its dotted key.
14
+ * - Log spans become effect.log_span.<label> attributes holding their duration in milliseconds, as
15
+ * @effect/opentelemetry's logger records them.
16
+ * - A failure or defect in the cause becomes exception.type, exception.message and
17
+ * exception.stacktrace, from the first of Cause.prettyErrors.
18
+ */
19
+ import type { Telemetry } from "@libo11y/core";
20
+ import type * as Layer from "effect/Layer";
21
+ import * as Logger from "effect/Logger";
22
+ /** An Effect Logger that writes every record through telemetry.logger. It never throws. */
23
+ export declare function makeLogger(telemetry: Telemetry): Logger.Logger<unknown, void>;
24
+ /** Options for loggerLayer. */
25
+ export interface LoggerLayerOptions {
26
+ /**
27
+ * Keep the loggers already installed beside the libo11y logger. Default false, which replaces
28
+ * them: the libo11y logger has a console sink of its own, so Effect's default console logger
29
+ * would print every record twice.
30
+ */
31
+ readonly mergeWithExisting?: boolean;
32
+ }
33
+ /** A layer that installs makeLogger(telemetry) as Effect's logger. */
34
+ export declare function loggerLayer(telemetry: Telemetry, options?: LoggerLayerOptions): Layer.Layer<never>;
package/dist/logger.js ADDED
@@ -0,0 +1,128 @@
1
+ import { context, ROOT_CONTEXT, TraceFlags, trace } from "@opentelemetry/api";
2
+ import * as Cause from "effect/Cause";
3
+ import * as Context from "effect/Context";
4
+ import * as Inspectable from "effect/Inspectable";
5
+ import * as Logger from "effect/Logger";
6
+ import * as References from "effect/References";
7
+ import * as Tracer from "effect/Tracer";
8
+ const LEVELS = {
9
+ All: "trace",
10
+ Trace: "trace",
11
+ Debug: "debug",
12
+ Info: "info",
13
+ Warn: "warn",
14
+ Error: "error",
15
+ Fatal: "fatal",
16
+ None: undefined,
17
+ };
18
+ const MAX_DEPTH = 8;
19
+ function isPlainObject(v) {
20
+ const proto = Object.getPrototypeOf(v);
21
+ return proto === Object.prototype || proto === null;
22
+ }
23
+ /** Converts an annotation value to a value the libo11y logger takes. */
24
+ function toLogValue(value, depth = 0) {
25
+ switch (typeof value) {
26
+ case "string":
27
+ case "number":
28
+ case "boolean":
29
+ case "bigint":
30
+ case "undefined":
31
+ return value;
32
+ case "symbol":
33
+ case "function":
34
+ return Inspectable.toStringUnknown(value);
35
+ }
36
+ if (value === null)
37
+ return null;
38
+ if (value instanceof Uint8Array || value instanceof Error)
39
+ return value;
40
+ if (value instanceof Date)
41
+ return Number.isNaN(value.getTime()) ? String(value) : value.toISOString();
42
+ if (depth >= MAX_DEPTH)
43
+ return Inspectable.toStringUnknown(value);
44
+ if (Array.isArray(value))
45
+ return value.map((v) => toLogValue(v, depth + 1));
46
+ if (isPlainObject(value)) {
47
+ const out = {};
48
+ for (const [k, v] of Object.entries(value))
49
+ out[k] = toLogValue(v, depth + 1);
50
+ return out;
51
+ }
52
+ return Inspectable.toStringUnknown(value);
53
+ }
54
+ function messageText(message) {
55
+ const parts = Array.isArray(message) ? message : [message];
56
+ return parts.map((p) => (typeof p === "string" ? p : Inspectable.toStringUnknown(p))).join(" ");
57
+ }
58
+ /** The OpenTelemetry context of an Effect span: its own span when it is an OpenTelemetry one. */
59
+ function contextOf(span, base) {
60
+ const otel = span.span;
61
+ if (typeof otel === "object" &&
62
+ otel !== null &&
63
+ typeof otel.spanContext === "function") {
64
+ return trace.setSpan(base, otel);
65
+ }
66
+ return trace.setSpanContext(base, {
67
+ traceId: span.traceId,
68
+ spanId: span.spanId,
69
+ traceFlags: span.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
70
+ isRemote: span._tag === "ExternalSpan",
71
+ });
72
+ }
73
+ function write(logger, level, msg, attrs) {
74
+ switch (level) {
75
+ case "trace":
76
+ logger.trace(msg, attrs);
77
+ return;
78
+ case "debug":
79
+ logger.debug(msg, attrs);
80
+ return;
81
+ case "info":
82
+ logger.info(msg, attrs);
83
+ return;
84
+ case "warn":
85
+ logger.warn(msg, attrs);
86
+ return;
87
+ case "error":
88
+ logger.error(msg, attrs);
89
+ return;
90
+ case "fatal":
91
+ logger.fatal(msg, attrs);
92
+ return;
93
+ }
94
+ }
95
+ /** An Effect Logger that writes every record through telemetry.logger. It never throws. */
96
+ export function makeLogger(telemetry) {
97
+ return Logger.make((options) => {
98
+ const level = LEVELS[options.logLevel];
99
+ if (level === undefined)
100
+ return;
101
+ try {
102
+ const attrs = {};
103
+ const errors = Cause.prettyErrors(options.cause);
104
+ // First, so it is the Error the libo11y logger expands into exception.*.
105
+ if (errors[0] !== undefined)
106
+ attrs.exception = errors[0];
107
+ for (const [key, value] of Object.entries(options.fiber.getRef(References.CurrentLogAnnotations))) {
108
+ attrs[key] = toLogValue(value);
109
+ }
110
+ const now = options.date.getTime();
111
+ for (const [label, start] of options.fiber.getRef(References.CurrentLogSpans)) {
112
+ attrs[`effect.log_span.${label}`] = now - start;
113
+ }
114
+ const msg = messageText(options.message);
115
+ const span = Context.getOrUndefined(options.fiber.context, Tracer.ParentSpan);
116
+ const active = context.active();
117
+ const ctx = span === undefined ? active : contextOf(span, active === undefined ? ROOT_CONTEXT : active);
118
+ context.with(ctx, () => write(telemetry.logger, level, msg, attrs));
119
+ }
120
+ catch {
121
+ // A telemetry library never fails its host: the libo11y logger reports its own failures.
122
+ }
123
+ });
124
+ }
125
+ /** A layer that installs makeLogger(telemetry) as Effect's logger. */
126
+ export function loggerLayer(telemetry, options = {}) {
127
+ return Logger.layer([makeLogger(telemetry)], { mergeWithExisting: options.mergeWithExisting ?? false });
128
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Effect metrics on a libo11y telemetry's meter provider. The layer provides Effect's
3
+ * MetricRegistry with a registry that bridges each series as Effect registers it:
4
+ *
5
+ * - Counter: each update adds to an OpenTelemetry counter, or an up-down counter when the Effect
6
+ * counter is not incremental.
7
+ * - Frequency: each occurrence adds 1 to a counter, with the word under the attribute "key", as
8
+ * @effect/opentelemetry reports it.
9
+ * - Histogram: each value is recorded in a histogram with the Effect histogram's boundaries.
10
+ * - Summary: each value is recorded in a histogram with the default boundaries; OpenTelemetry has
11
+ * no summary.
12
+ * - Gauge: an observable gauge reads the Effect gauge's value at each collection.
13
+ *
14
+ * The measurements are taken on telemetry.meterProvider, the policy-wrapping one, so their
15
+ * attributes pass the sensitivity policy, and a measurement inside a sampled Effect span carries
16
+ * an exemplar of it. An Effect metric's own attributes, and those Metric.withAttributes adds, are
17
+ * the measurement's attributes. A series registered with Metric.registerUnsafe reports through its
18
+ * get hook only, so only gauges registered that way are bridged.
19
+ */
20
+ import type { Telemetry } from "@libo11y/core";
21
+ import * as Layer from "effect/Layer";
22
+ /**
23
+ * A layer that bridges Effect metrics to telemetry.meterProvider. Every layer for one telemetry
24
+ * shares one registry, so building the layer again keeps the series it has.
25
+ */
26
+ export declare function metricsLayer(telemetry: Telemetry): Layer.Layer<never>;
@@ -0,0 +1,166 @@
1
+ import * as Context from "effect/Context";
2
+ import * as Layer from "effect/Layer";
3
+ import * as Metric from "effect/Metric";
4
+ import { VERSION } from "./version.js";
5
+ /** The instrumentation scope of the bridged metrics. */
6
+ const SCOPE = "@libo11y/effect";
7
+ const EMPTY = Context.empty();
8
+ function attributesOf(metadata) {
9
+ return { ...(metadata.attributes ?? {}) };
10
+ }
11
+ function numberOf(value) {
12
+ return typeof value === "bigint" ? Number(value) : value;
13
+ }
14
+ /**
15
+ * A MetricRegistry that bridges each series to OpenTelemetry instruments as Effect registers it.
16
+ * It is a Map, as Effect's registry is, so Metric.snapshot and anything else that reads the
17
+ * registry keeps working.
18
+ */
19
+ class BridgeRegistry extends Map {
20
+ meterInstance;
21
+ provider;
22
+ instruments = new Map();
23
+ gauges = new Set();
24
+ bind(provider) {
25
+ this.provider = provider;
26
+ return this;
27
+ }
28
+ meter() {
29
+ if (this.meterInstance === undefined && this.provider !== undefined) {
30
+ this.meterInstance = this.provider.getMeter(SCOPE, VERSION);
31
+ }
32
+ return this.meterInstance;
33
+ }
34
+ set(key, metadata) {
35
+ try {
36
+ this.bridge(metadata);
37
+ }
38
+ catch {
39
+ // The metric still works in Effect; only its export is lost.
40
+ }
41
+ return super.set(key, metadata);
42
+ }
43
+ instrument(key, make) {
44
+ let instrument = this.instruments.get(key);
45
+ if (instrument === undefined) {
46
+ instrument = make();
47
+ this.instruments.set(key, instrument);
48
+ }
49
+ return instrument;
50
+ }
51
+ // Effect reads metadata.hooks right after it stores the metadata, so wrapping them in place is
52
+ // what makes the first update reach the instrument too.
53
+ wrap(metadata, record) {
54
+ const hooks = metadata.hooks;
55
+ const update = hooks.update;
56
+ const modify = hooks.modify;
57
+ const wrapped = {
58
+ get: hooks.get,
59
+ update: (input, ctx) => {
60
+ update(input, ctx);
61
+ try {
62
+ record(input);
63
+ }
64
+ catch {
65
+ // As in set.
66
+ }
67
+ },
68
+ modify: modify === update
69
+ ? (input, ctx) => {
70
+ modify(input, ctx);
71
+ try {
72
+ record(input);
73
+ }
74
+ catch {
75
+ // As in set.
76
+ }
77
+ }
78
+ : modify,
79
+ };
80
+ metadata.hooks = wrapped;
81
+ }
82
+ bridge(metadata) {
83
+ const meter = this.meter();
84
+ if (meter === undefined)
85
+ return;
86
+ const { id, description } = metadata;
87
+ const options = description === undefined ? {} : { description };
88
+ const attrs = attributesOf(metadata);
89
+ switch (metadata.type) {
90
+ case "Counter": {
91
+ const state = metadata.hooks.get(EMPTY);
92
+ if (state.incremental === true) {
93
+ const counter = this.instrument(`counter:${id}`, () => meter.createCounter(id, options));
94
+ this.wrap(metadata, (input) => {
95
+ const n = numberOf(input);
96
+ if (n >= 0)
97
+ counter.add(n, attrs);
98
+ });
99
+ }
100
+ else {
101
+ const counter = this.instrument(`updown:${id}`, () => meter.createUpDownCounter(id, options));
102
+ this.wrap(metadata, (input) => counter.add(numberOf(input), attrs));
103
+ }
104
+ return;
105
+ }
106
+ case "Frequency": {
107
+ const counter = this.instrument(`counter:${id}`, () => meter.createCounter(id, options));
108
+ this.wrap(metadata, (input) => counter.add(1, { ...attrs, key: String(input) }));
109
+ return;
110
+ }
111
+ case "Histogram": {
112
+ const state = metadata.hooks.get(EMPTY);
113
+ const boundaries = (state.buckets ?? []).map(([boundary]) => boundary);
114
+ const histogram = this.instrument(`histogram:${id}`, () => meter.createHistogram(id, {
115
+ ...options,
116
+ ...(boundaries.length === 0 ? {} : { advice: { explicitBucketBoundaries: boundaries } }),
117
+ }));
118
+ this.wrap(metadata, (input) => histogram.record(numberOf(input), attrs));
119
+ return;
120
+ }
121
+ case "Summary": {
122
+ const histogram = this.instrument(`histogram:${id}`, () => meter.createHistogram(id, options));
123
+ this.wrap(metadata, (input) => histogram.record(numberOf(input[0]), attrs));
124
+ return;
125
+ }
126
+ case "Gauge": {
127
+ if (this.gauges.has(id))
128
+ return;
129
+ this.gauges.add(id);
130
+ meter.createObservableGauge(id, options).addCallback((result) => {
131
+ for (const series of this.values()) {
132
+ if (series.id !== id || series.type !== "Gauge")
133
+ continue;
134
+ try {
135
+ const state = series.hooks.get(EMPTY);
136
+ result.observe(numberOf(state.value), attributesOf(series));
137
+ }
138
+ catch {
139
+ // A gauge that cannot be read is left out of this collection.
140
+ }
141
+ }
142
+ });
143
+ return;
144
+ }
145
+ }
146
+ }
147
+ }
148
+ // One registry per meter provider, as Effect's default registry is one per program: a layer that is
149
+ // built again, as one provided per invocation is, keeps the series and their gauges, and registers
150
+ // no second gauge callback.
151
+ const registries = new WeakMap();
152
+ function registryFor(provider) {
153
+ let registry = registries.get(provider);
154
+ if (registry === undefined) {
155
+ registry = new BridgeRegistry().bind(provider);
156
+ registries.set(provider, registry);
157
+ }
158
+ return registry;
159
+ }
160
+ /**
161
+ * A layer that bridges Effect metrics to telemetry.meterProvider. Every layer for one telemetry
162
+ * shares one registry, so building the layer again keeps the series it has.
163
+ */
164
+ export function metricsLayer(telemetry) {
165
+ return Layer.sync(Metric.MetricRegistry, () => registryFor(telemetry.meterProvider));
166
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The Effect Tracer over a libo11y telemetry: @effect/opentelemetry's OtelTracer, given the
3
+ * telemetry's tracer provider. Effect spans, including those of Effect's HttpServer, HttpClient,
4
+ * RPC and SQL modules, become OpenTelemetry spans of that provider, so they pass libo11y's
5
+ * redaction and sampling and land in the same traces as the spans of plain OpenTelemetry code.
6
+ * While a traced effect runs the tracer keeps its span active in the OpenTelemetry context, so
7
+ * libo11y's logger and instrumentFetch see it.
8
+ */
9
+ import * as OtelTracer from "@effect/opentelemetry/OtelTracer";
10
+ import type { Telemetry } from "@libo11y/core";
11
+ import * as Layer from "effect/Layer";
12
+ /**
13
+ * A layer that installs the Effect Tracer over telemetry.tracerProvider, with the instrumentation
14
+ * scope "effect". It also provides the OtelTracer service of `@effect/opentelemetry`.
15
+ */
16
+ export declare function tracerLayer(telemetry: Telemetry): Layer.Layer<OtelTracer.OtelTracer>;
package/dist/tracer.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The Effect Tracer over a libo11y telemetry: @effect/opentelemetry's OtelTracer, given the
3
+ * telemetry's tracer provider. Effect spans, including those of Effect's HttpServer, HttpClient,
4
+ * RPC and SQL modules, become OpenTelemetry spans of that provider, so they pass libo11y's
5
+ * redaction and sampling and land in the same traces as the spans of plain OpenTelemetry code.
6
+ * While a traced effect runs the tracer keeps its span active in the OpenTelemetry context, so
7
+ * libo11y's logger and instrumentFetch see it.
8
+ */
9
+ import * as OtelTracer from "@effect/opentelemetry/OtelTracer";
10
+ import * as Layer from "effect/Layer";
11
+ /**
12
+ * A layer that installs the Effect Tracer over telemetry.tracerProvider, with the instrumentation
13
+ * scope "effect". It also provides the OtelTracer service of `@effect/opentelemetry`.
14
+ */
15
+ export function tracerLayer(telemetry) {
16
+ return OtelTracer.layer.pipe(Layer.provide(Layer.succeed(OtelTracer.OtelTracerProvider, telemetry.tracerProvider)));
17
+ }
@@ -0,0 +1,2 @@
1
+ /** The libo11y Effect bridge's package version. scripts/release.ts keeps it equal to package.json. */
2
+ export declare const VERSION = "0.8.0";
@@ -0,0 +1,2 @@
1
+ /** The libo11y Effect bridge's package version. scripts/release.ts keeps it equal to package.json. */
2
+ export const VERSION = "0.8.0";
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@libo11y/effect",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.8.0",
4
+ "description": "The libo11y bridge for Effect 4: layers that install an Effect Tracer over a libo11y telemetry's tracer provider, an Effect Logger that writes through the libo11y logger with trace correlation and redaction, and Effect metrics on its meter provider. Runtime-neutral: over @libo11y/server, @libo11y/workers or @libo11y/web.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/libo11y/libo11y.git",
17
+ "directory": "ts/packages/effect"
18
+ },
19
+ "dependencies": {
20
+ "@libo11y/core": "0.8.0"
21
+ },
22
+ "peerDependencies": {
23
+ "@effect/opentelemetry": "^4.2.0",
24
+ "@opentelemetry/api": ">=1.10.0 <1.11.0",
25
+ "effect": "^4.2.0"
26
+ },
27
+ "devDependencies": {
28
+ "@effect/opentelemetry": "4.2.0",
29
+ "@libo11y/spec": "0.8.0",
30
+ "@libo11y/test": "0.8.0",
31
+ "@opentelemetry/api": "1.10.0",
32
+ "effect": "4.2.0"
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "README.md",
37
+ "LICENSE"
38
+ ],
39
+ "publishConfig": {
40
+ "access": "public",
41
+ "provenance": true
42
+ }
43
+ }