@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/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, options.sql === undefined ? undefined : { sql: options.sql });
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,39 @@
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
+ /**
23
+ * Internal helper backing both makeLogger and dynamic clientLayer logging. Resolves the telemetry
24
+ * handle per record so late-bound client refs activate seamlessly once setup finishes.
25
+ */
26
+ export declare function makeDynamicLogger(getTelemetry: () => Telemetry | undefined): Logger.Logger<unknown, void>;
27
+ /** An Effect Logger that writes every record through telemetry.logger. It never throws. */
28
+ export declare function makeLogger(telemetry: Telemetry): Logger.Logger<unknown, void>;
29
+ /** Options for loggerLayer. */
30
+ export interface LoggerLayerOptions {
31
+ /**
32
+ * Keep the loggers already installed beside the libo11y logger. Default false, which replaces
33
+ * them: the libo11y logger has a console sink of its own, so Effect's default console logger
34
+ * would print every record twice.
35
+ */
36
+ readonly mergeWithExisting?: boolean;
37
+ }
38
+ /** A layer that installs makeLogger(telemetry) as Effect's logger. */
39
+ export declare function loggerLayer(telemetry: Telemetry, options?: LoggerLayerOptions): Layer.Layer<never>;
package/dist/logger.js ADDED
@@ -0,0 +1,124 @@
1
+ import { context, ROOT_CONTEXT } 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
+ import { contextOfSpan, getPropagatedSpan } from "./span-context.js";
9
+ const LEVELS = {
10
+ All: "trace",
11
+ Trace: "trace",
12
+ Debug: "debug",
13
+ Info: "info",
14
+ Warn: "warn",
15
+ Error: "error",
16
+ Fatal: "fatal",
17
+ None: undefined,
18
+ };
19
+ const MAX_DEPTH = 8;
20
+ function isPlainObject(v) {
21
+ const proto = Object.getPrototypeOf(v);
22
+ return proto === Object.prototype || proto === null;
23
+ }
24
+ /** Converts an annotation value to a value the libo11y logger takes. */
25
+ function toLogValue(value, depth = 0) {
26
+ switch (typeof value) {
27
+ case "string":
28
+ case "number":
29
+ case "boolean":
30
+ case "bigint":
31
+ case "undefined":
32
+ return value;
33
+ case "symbol":
34
+ case "function":
35
+ return Inspectable.toStringUnknown(value);
36
+ }
37
+ if (value === null)
38
+ return null;
39
+ if (value instanceof Uint8Array || value instanceof Error)
40
+ return value;
41
+ if (value instanceof Date)
42
+ return Number.isNaN(value.getTime()) ? String(value) : value.toISOString();
43
+ if (depth >= MAX_DEPTH)
44
+ return Inspectable.toStringUnknown(value);
45
+ if (Array.isArray(value))
46
+ return value.map((v) => toLogValue(v, depth + 1));
47
+ if (isPlainObject(value)) {
48
+ const out = {};
49
+ for (const [k, v] of Object.entries(value))
50
+ out[k] = toLogValue(v, depth + 1);
51
+ return out;
52
+ }
53
+ return Inspectable.toStringUnknown(value);
54
+ }
55
+ function messageText(message) {
56
+ const parts = Array.isArray(message) ? message : [message];
57
+ return parts.map((p) => (typeof p === "string" ? p : Inspectable.toStringUnknown(p))).join(" ");
58
+ }
59
+ function write(logger, level, msg, attrs) {
60
+ switch (level) {
61
+ case "trace":
62
+ logger.trace(msg, attrs);
63
+ return;
64
+ case "debug":
65
+ logger.debug(msg, attrs);
66
+ return;
67
+ case "info":
68
+ logger.info(msg, attrs);
69
+ return;
70
+ case "warn":
71
+ logger.warn(msg, attrs);
72
+ return;
73
+ case "error":
74
+ logger.error(msg, attrs);
75
+ return;
76
+ case "fatal":
77
+ logger.fatal(msg, attrs);
78
+ return;
79
+ }
80
+ }
81
+ /**
82
+ * Internal helper backing both makeLogger and dynamic clientLayer logging. Resolves the telemetry
83
+ * handle per record so late-bound client refs activate seamlessly once setup finishes.
84
+ */
85
+ export function makeDynamicLogger(getTelemetry) {
86
+ return Logger.make((options) => {
87
+ const level = LEVELS[options.logLevel];
88
+ if (level === undefined)
89
+ return;
90
+ const telemetry = getTelemetry();
91
+ if (telemetry === undefined)
92
+ return;
93
+ try {
94
+ const attrs = {};
95
+ const errors = Cause.prettyErrors(options.cause);
96
+ // First, so it is the Error the libo11y logger expands into exception.*.
97
+ if (errors[0] !== undefined)
98
+ attrs.exception = errors[0];
99
+ for (const [key, value] of Object.entries(options.fiber.getRef(References.CurrentLogAnnotations))) {
100
+ attrs[key] = toLogValue(value);
101
+ }
102
+ const now = options.date.getTime();
103
+ for (const [label, start] of options.fiber.getRef(References.CurrentLogSpans)) {
104
+ attrs[`effect.log_span.${label}`] = now - start;
105
+ }
106
+ const msg = messageText(options.message);
107
+ const span = getPropagatedSpan(Context.getOrUndefined(options.fiber.context, Tracer.ParentSpan));
108
+ const active = context.active();
109
+ const ctx = span === undefined ? active : contextOfSpan(span, active === undefined ? ROOT_CONTEXT : active);
110
+ context.with(ctx, () => write(telemetry.logger, level, msg, attrs));
111
+ }
112
+ catch {
113
+ // A telemetry library never fails its host: the libo11y logger reports its own failures.
114
+ }
115
+ });
116
+ }
117
+ /** An Effect Logger that writes every record through telemetry.logger. It never throws. */
118
+ export function makeLogger(telemetry) {
119
+ return makeDynamicLogger(() => telemetry);
120
+ }
121
+ /** A layer that installs makeLogger(telemetry) as Effect's logger. */
122
+ export function loggerLayer(telemetry, options = {}) {
123
+ return Logger.layer([makeLogger(telemetry)], { mergeWithExisting: options.mergeWithExisting ?? false });
124
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Effect metrics on a libo11y telemetry's meter provider. All access to Effect's MetricRegistry
3
+ * internals (metadata.hooks wrapping and Metric.registerUnsafe pull-only detection) is isolated in
4
+ * this module; see metrics-internals.test.ts for the runtime upgrade canary.
5
+ *
6
+ * Push series (updated via Metric.update / Metric.modify):
7
+ * - Counter: adds to an OpenTelemetry Counter (incremental) or UpDownCounter (non-incremental).
8
+ * - Frequency: adds 1 to an OpenTelemetry Counter with attribute "key" set to the word.
9
+ * - Histogram: records in an OpenTelemetry Histogram with the Effect histogram's boundaries.
10
+ * - Summary: records in an OpenTelemetry Histogram with default boundaries (OTel has no Summary).
11
+ * - Gauge: observed at each collection via an OpenTelemetry ObservableGauge.
12
+ *
13
+ * Pull-only series (registered via Metric.registerUnsafe, where Effect installs constVoid hooks):
14
+ * - Counter (incremental): bridged via ObservableCounter.
15
+ * - Counter (non-incremental): bridged via ObservableUpDownCounter.
16
+ * - Frequency: bridged via ObservableCounter emitting per-key counts under attribute "key".
17
+ * - Gauge: bridged via ObservableGauge.
18
+ * - Histogram / Summary: OpenTelemetry JS has no observable histogram or summary instrument, so
19
+ * pull-only Histogram and Summary registrations are not bridged.
20
+ *
21
+ * All observable instruments share a single Meter.addBatchObservableCallback so Metric.snapshotUnsafe
22
+ * runs at most once per collection cycle (O(N) rather than O(N^2)), and callbacks are detached via
23
+ * Meter.removeBatchObservableCallback whenever a dynamic TelemetryRef clears or switches providers.
24
+ *
25
+ * Measurements run on telemetry.meterProvider (the policy-wrapping provider), so attributes pass
26
+ * the sensitivity policy and measurements inside sampled Effect spans carry exemplars.
27
+ */
28
+ import type { Telemetry } from "@libo11y/core";
29
+ import * as Layer from "effect/Layer";
30
+ /**
31
+ * Internal helper backing clientLayer: maintains one BridgeRegistry per dynamic telemetry source
32
+ * and binds/re-binds its meterProvider as the telemetry ref attaches or changes.
33
+ */
34
+ export declare function dynamicMetricsLayer(key: object, getTelemetry: () => Telemetry | undefined, subscribe?: (listener: (telemetry: Telemetry | undefined) => void) => void): Layer.Layer<never>;
35
+ /**
36
+ * A layer that bridges Effect metrics to telemetry.meterProvider. Every layer for one telemetry
37
+ * shares one registry, so building the layer again keeps the series it has.
38
+ */
39
+ export declare function metricsLayer(telemetry: Telemetry): Layer.Layer<never>;
@@ -0,0 +1,393 @@
1
+ import * as Context from "effect/Context";
2
+ import { constVoid } from "effect/Function";
3
+ import * as Layer from "effect/Layer";
4
+ import * as Metric from "effect/Metric";
5
+ import { VERSION } from "./version.js";
6
+ /** The instrumentation scope of the bridged metrics. */
7
+ const SCOPE = "@libo11y/effect";
8
+ function attributesOf(attributes) {
9
+ return { ...(attributes ?? {}) };
10
+ }
11
+ function numberOf(value) {
12
+ return typeof value === "bigint" ? Number(value) : value;
13
+ }
14
+ /**
15
+ * Effect 4.2's Metric.registerUnsafe stores `{ get: hooks.get, update: constVoid, modify: constVoid }`
16
+ * in MetricRegistry. Identifying that exact pair distinguishes pull-only registrations from
17
+ * standard push metrics without depending on private fields.
18
+ */
19
+ function isPullOnlyHooks(hooks) {
20
+ return hooks.update === constVoid && hooks.modify === constVoid;
21
+ }
22
+ /**
23
+ * A MetricRegistry that bridges each series to OpenTelemetry instruments as Effect registers it.
24
+ * It is a Map, as Effect's registry is, so Metric.snapshot and Metric.snapshotUnsafe keep working.
25
+ */
26
+ class BridgeRegistry extends Map {
27
+ meterInstance;
28
+ provider;
29
+ instruments = new Map();
30
+ observableHandles = new Map();
31
+ pullOnlyKeys = new Set();
32
+ wrappedMetadata = new WeakSet();
33
+ snapshotContext;
34
+ activeBatchMeter;
35
+ activeBatchCallback;
36
+ activeBatchObservables = [];
37
+ constructor() {
38
+ super();
39
+ this.snapshotContext = Context.make(Metric.MetricRegistry, this);
40
+ }
41
+ detachBatchCallback() {
42
+ if (this.activeBatchMeter !== undefined &&
43
+ this.activeBatchCallback !== undefined &&
44
+ this.activeBatchObservables.length > 0) {
45
+ try {
46
+ this.activeBatchMeter.removeBatchObservableCallback(this.activeBatchCallback, this.activeBatchObservables);
47
+ }
48
+ catch {
49
+ // Detaching from a shut-down meter must never throw.
50
+ }
51
+ }
52
+ this.activeBatchMeter = undefined;
53
+ this.activeBatchCallback = undefined;
54
+ this.activeBatchObservables = [];
55
+ }
56
+ syncBatchCallback(meter) {
57
+ this.detachBatchCallback();
58
+ if (this.observableHandles.size === 0)
59
+ return;
60
+ const observables = [...this.observableHandles.values()];
61
+ const callback = (batchResult) => {
62
+ this.collectAllObservables(batchResult);
63
+ };
64
+ meter.addBatchObservableCallback(callback, observables);
65
+ this.activeBatchMeter = meter;
66
+ this.activeBatchCallback = callback;
67
+ this.activeBatchObservables = observables;
68
+ }
69
+ bind(provider) {
70
+ if (this.provider === provider)
71
+ return this;
72
+ this.detachBatchCallback();
73
+ this.provider = provider;
74
+ this.meterInstance = undefined;
75
+ this.instruments.clear();
76
+ this.observableHandles.clear();
77
+ const meter = this.meter();
78
+ if (meter !== undefined) {
79
+ for (const [key, metadata] of this.entries()) {
80
+ try {
81
+ this.bridgeObservable(key, metadata, false);
82
+ }
83
+ catch {
84
+ // A metric that cannot be bridged still works in Effect.
85
+ }
86
+ }
87
+ this.syncBatchCallback(meter);
88
+ }
89
+ return this;
90
+ }
91
+ meter() {
92
+ if (this.meterInstance === undefined && this.provider !== undefined) {
93
+ this.meterInstance = this.provider.getMeter(SCOPE, VERSION);
94
+ }
95
+ return this.meterInstance;
96
+ }
97
+ set(key, metadata) {
98
+ const pullOnly = isPullOnlyHooks(metadata.hooks);
99
+ if (pullOnly) {
100
+ this.pullOnlyKeys.add(key);
101
+ }
102
+ else {
103
+ this.pullOnlyKeys.delete(key);
104
+ }
105
+ super.set(key, metadata);
106
+ try {
107
+ this.bridge(key, metadata, pullOnly);
108
+ }
109
+ catch {
110
+ // The metric still works in Effect; only its export is lost.
111
+ }
112
+ return this;
113
+ }
114
+ delete(key) {
115
+ this.pullOnlyKeys.delete(key);
116
+ return super.delete(key);
117
+ }
118
+ clear() {
119
+ this.pullOnlyKeys.clear();
120
+ super.clear();
121
+ }
122
+ instrument(key, make) {
123
+ let instrument = this.instruments.get(key);
124
+ if (instrument === undefined) {
125
+ instrument = make();
126
+ this.instruments.set(key, instrument);
127
+ }
128
+ return instrument;
129
+ }
130
+ // Effect reads metadata.hooks right after it stores the metadata, so wrapping them in place is
131
+ // what makes the first update reach the instrument too. Resolving the meter lazily inside record
132
+ // lets metrics registered before a dynamic TelemetryRef attaches begin exporting once attached.
133
+ wrap(metadata, record) {
134
+ if (this.wrappedMetadata.has(metadata))
135
+ return;
136
+ this.wrappedMetadata.add(metadata);
137
+ const hooks = metadata.hooks;
138
+ const update = hooks.update;
139
+ const modify = hooks.modify;
140
+ const dispatch = (input) => {
141
+ const meter = this.meter();
142
+ if (meter === undefined)
143
+ return;
144
+ try {
145
+ record(meter, input);
146
+ }
147
+ catch {
148
+ // As in set.
149
+ }
150
+ };
151
+ const wrapped = {
152
+ get: hooks.get,
153
+ update: (input, ctx) => {
154
+ update(input, ctx);
155
+ dispatch(input);
156
+ },
157
+ modify: modify === update
158
+ ? (input, ctx) => {
159
+ modify(input, ctx);
160
+ dispatch(input);
161
+ }
162
+ : modify,
163
+ };
164
+ metadata.hooks = wrapped;
165
+ }
166
+ observeEntry(batchResult, type, id, attributes, state) {
167
+ switch (type) {
168
+ case "Gauge": {
169
+ const handle = this.observableHandles.get(`gauge:${id}`);
170
+ const value = state?.value;
171
+ if (handle !== undefined && value !== undefined) {
172
+ batchResult.observe(handle, numberOf(value), attributes);
173
+ }
174
+ return;
175
+ }
176
+ case "Counter": {
177
+ const counterState = state;
178
+ if (counterState === undefined || counterState.count === undefined)
179
+ return;
180
+ const kind = counterState.incremental === true ? "counter-inc" : "counter-updown";
181
+ const handle = this.observableHandles.get(`${kind}:${id}`);
182
+ if (handle !== undefined) {
183
+ batchResult.observe(handle, numberOf(counterState.count), attributes);
184
+ }
185
+ return;
186
+ }
187
+ case "Frequency": {
188
+ const handle = this.observableHandles.get(`frequency:${id}`);
189
+ const occurrences = state
190
+ ?.occurrences;
191
+ if (handle === undefined || !(occurrences instanceof Map))
192
+ return;
193
+ for (const [word, count] of occurrences) {
194
+ batchResult.observe(handle, count, { ...attributes, key: word });
195
+ }
196
+ return;
197
+ }
198
+ default:
199
+ return;
200
+ }
201
+ }
202
+ /**
203
+ * Collects all bridged observable instruments in a single O(N) pass using Effect's documented
204
+ * Metric.snapshotUnsafe(context) when no push+pull id conflict exists and all getters succeed,
205
+ * falling back to a single per-entry isolated pass if any getter throws or mixes push and pull.
206
+ */
207
+ collectAllObservables(batchResult) {
208
+ let hasMixedPushAndPull = false;
209
+ for (const [key, series] of this.entries()) {
210
+ if (series.type === "Counter") {
211
+ const hasPullHandle = this.observableHandles.has(`counter-inc:${series.id}`) ||
212
+ this.observableHandles.has(`counter-updown:${series.id}`);
213
+ if (hasPullHandle && !this.pullOnlyKeys.has(key)) {
214
+ hasMixedPushAndPull = true;
215
+ break;
216
+ }
217
+ }
218
+ else if (series.type === "Frequency") {
219
+ if (this.observableHandles.has(`frequency:${series.id}`) && !this.pullOnlyKeys.has(key)) {
220
+ hasMixedPushAndPull = true;
221
+ break;
222
+ }
223
+ }
224
+ }
225
+ if (!hasMixedPushAndPull) {
226
+ try {
227
+ const snapshots = Metric.snapshotUnsafe(this.snapshotContext);
228
+ for (const snap of snapshots) {
229
+ this.observeEntry(batchResult, snap.type, snap.id, attributesOf(snap.attributes), snap.state);
230
+ }
231
+ return;
232
+ }
233
+ catch {
234
+ // One throwing getter must not drop healthy series; fall back to per-series isolation.
235
+ }
236
+ }
237
+ for (const [key, series] of this.entries()) {
238
+ if (series.type !== "Gauge" && !this.pullOnlyKeys.has(key))
239
+ continue;
240
+ try {
241
+ const state = series.hooks.get(this.snapshotContext);
242
+ this.observeEntry(batchResult, series.type, series.id, attributesOf(series.attributes), state);
243
+ }
244
+ catch {
245
+ // A series that cannot be read is left out of this collection.
246
+ }
247
+ }
248
+ }
249
+ registerObservable(kind, id, description, meter, sync) {
250
+ const key = `${kind}:${id}`;
251
+ if (this.observableHandles.has(key))
252
+ return;
253
+ const options = description === undefined ? {} : { description };
254
+ let observable;
255
+ switch (kind) {
256
+ case "gauge":
257
+ observable = meter.createObservableGauge(id, options);
258
+ break;
259
+ case "counter-inc":
260
+ case "frequency":
261
+ observable = meter.createObservableCounter(id, options);
262
+ break;
263
+ case "counter-updown":
264
+ observable = meter.createObservableUpDownCounter(id, options);
265
+ break;
266
+ }
267
+ this.observableHandles.set(key, observable);
268
+ if (sync) {
269
+ this.syncBatchCallback(meter);
270
+ }
271
+ }
272
+ bridgeObservable(key, metadata, sync) {
273
+ const meter = this.meter();
274
+ if (meter === undefined)
275
+ return;
276
+ const pullOnly = this.pullOnlyKeys.has(key);
277
+ if (metadata.type === "Gauge") {
278
+ this.registerObservable("gauge", metadata.id, metadata.description, meter, sync);
279
+ return;
280
+ }
281
+ if (!pullOnly)
282
+ return;
283
+ if (metadata.type === "Counter") {
284
+ const state = metadata.hooks.get(this.snapshotContext);
285
+ this.registerObservable(state?.incremental === true ? "counter-inc" : "counter-updown", metadata.id, metadata.description, meter, sync);
286
+ return;
287
+ }
288
+ if (metadata.type === "Frequency") {
289
+ this.registerObservable("frequency", metadata.id, metadata.description, meter, sync);
290
+ }
291
+ }
292
+ bridge(key, metadata, pullOnly) {
293
+ const { id, description } = metadata;
294
+ const options = description === undefined ? {} : { description };
295
+ const attrs = attributesOf(metadata.attributes);
296
+ if (metadata.type === "Gauge") {
297
+ const meter = this.meter();
298
+ if (meter !== undefined)
299
+ this.registerObservable("gauge", id, description, meter, true);
300
+ return;
301
+ }
302
+ if (pullOnly) {
303
+ this.bridgeObservable(key, metadata, true);
304
+ return;
305
+ }
306
+ switch (metadata.type) {
307
+ case "Counter": {
308
+ const state = metadata.hooks.get(this.snapshotContext);
309
+ if (state.incremental === true) {
310
+ this.wrap(metadata, (meter, input) => {
311
+ const n = numberOf(input);
312
+ if (n >= 0) {
313
+ const counter = this.instrument(`counter:${id}`, () => meter.createCounter(id, options));
314
+ counter.add(n, attrs);
315
+ }
316
+ });
317
+ }
318
+ else {
319
+ this.wrap(metadata, (meter, input) => {
320
+ const counter = this.instrument(`updown:${id}`, () => meter.createUpDownCounter(id, options));
321
+ counter.add(numberOf(input), attrs);
322
+ });
323
+ }
324
+ return;
325
+ }
326
+ case "Frequency": {
327
+ this.wrap(metadata, (meter, input) => {
328
+ const counter = this.instrument(`counter:${id}`, () => meter.createCounter(id, options));
329
+ counter.add(1, { ...attrs, key: String(input) });
330
+ });
331
+ return;
332
+ }
333
+ case "Histogram": {
334
+ const state = metadata.hooks.get(this.snapshotContext);
335
+ const boundaries = (state.buckets ?? []).map(([boundary]) => boundary);
336
+ this.wrap(metadata, (meter, input) => {
337
+ const histogram = this.instrument(`histogram:${id}`, () => meter.createHistogram(id, {
338
+ ...options,
339
+ ...(boundaries.length === 0 ? {} : { advice: { explicitBucketBoundaries: boundaries } }),
340
+ }));
341
+ histogram.record(numberOf(input), attrs);
342
+ });
343
+ return;
344
+ }
345
+ case "Summary": {
346
+ this.wrap(metadata, (meter, input) => {
347
+ const histogram = this.instrument(`histogram:${id}`, () => meter.createHistogram(id, options));
348
+ histogram.record(numberOf(input[0]), attrs);
349
+ });
350
+ return;
351
+ }
352
+ }
353
+ }
354
+ }
355
+ // One registry per meter provider, as Effect's default registry is one per program: a layer that is
356
+ // built again, as one provided per invocation is, keeps the series and their gauges, and registers
357
+ // no second gauge callback.
358
+ const registries = new WeakMap();
359
+ function registryFor(provider) {
360
+ let registry = registries.get(provider);
361
+ if (registry === undefined) {
362
+ registry = new BridgeRegistry().bind(provider);
363
+ registries.set(provider, registry);
364
+ }
365
+ return registry;
366
+ }
367
+ /**
368
+ * Internal helper backing clientLayer: maintains one BridgeRegistry per dynamic telemetry source
369
+ * and binds/re-binds its meterProvider as the telemetry ref attaches or changes.
370
+ */
371
+ export function dynamicMetricsLayer(key, getTelemetry, subscribe) {
372
+ return Layer.sync(Metric.MetricRegistry, () => {
373
+ let registry = registries.get(key);
374
+ if (registry === undefined) {
375
+ registry = new BridgeRegistry().bind(getTelemetry()?.meterProvider);
376
+ registries.set(key, registry);
377
+ subscribe?.((telemetry) => {
378
+ registry?.bind(telemetry?.meterProvider);
379
+ });
380
+ }
381
+ else {
382
+ registry.bind(getTelemetry()?.meterProvider);
383
+ }
384
+ return registry;
385
+ });
386
+ }
387
+ /**
388
+ * A layer that bridges Effect metrics to telemetry.meterProvider. Every layer for one telemetry
389
+ * shares one registry, so building the layer again keeps the series it has.
390
+ */
391
+ export function metricsLayer(telemetry) {
392
+ return Layer.sync(Metric.MetricRegistry, () => registryFor(telemetry.meterProvider));
393
+ }
@@ -0,0 +1,15 @@
1
+ import { type Context as OtelContext } from "@opentelemetry/api";
2
+ import * as Tracer from "effect/Tracer";
3
+ /**
4
+ * Walks past spans annotated with Tracer.DisablePropagation, matching OtelTracer's
5
+ * getPropagatedSpan (and Effect's internal filterDisablePropagation).
6
+ */
7
+ export declare function getPropagatedSpan(span: Tracer.AnySpan | undefined): Tracer.AnySpan | undefined;
8
+ /** Active propagated Effect span on the current fiber, if any. */
9
+ export declare function activePropagatedSpan(): Tracer.AnySpan | undefined;
10
+ /**
11
+ * Attaches an Effect span onto an OpenTelemetry Context when its span context is valid.
12
+ * Preserves the underlying OpenTelemetry Span object when present (e.g. OtelSpan), and preserves
13
+ * OtelTraceFlags and OtelTraceState annotations on ExternalSpan values.
14
+ */
15
+ export declare function contextOfSpan(span: Tracer.AnySpan, base: OtelContext): OtelContext;