@libo11y/effect 0.8.0 → 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/logger.js CHANGED
@@ -1,10 +1,11 @@
1
- import { context, ROOT_CONTEXT, TraceFlags, trace } from "@opentelemetry/api";
1
+ import { context, ROOT_CONTEXT } from "@opentelemetry/api";
2
2
  import * as Cause from "effect/Cause";
3
3
  import * as Context from "effect/Context";
4
4
  import * as Inspectable from "effect/Inspectable";
5
5
  import * as Logger from "effect/Logger";
6
6
  import * as References from "effect/References";
7
7
  import * as Tracer from "effect/Tracer";
8
+ import { contextOfSpan, getPropagatedSpan } from "./span-context.js";
8
9
  const LEVELS = {
9
10
  All: "trace",
10
11
  Trace: "trace",
@@ -55,21 +56,6 @@ function messageText(message) {
55
56
  const parts = Array.isArray(message) ? message : [message];
56
57
  return parts.map((p) => (typeof p === "string" ? p : Inspectable.toStringUnknown(p))).join(" ");
57
58
  }
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
59
  function write(logger, level, msg, attrs) {
74
60
  switch (level) {
75
61
  case "trace":
@@ -92,12 +78,18 @@ function write(logger, level, msg, attrs) {
92
78
  return;
93
79
  }
94
80
  }
95
- /** An Effect Logger that writes every record through telemetry.logger. It never throws. */
96
- export function makeLogger(telemetry) {
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) {
97
86
  return Logger.make((options) => {
98
87
  const level = LEVELS[options.logLevel];
99
88
  if (level === undefined)
100
89
  return;
90
+ const telemetry = getTelemetry();
91
+ if (telemetry === undefined)
92
+ return;
101
93
  try {
102
94
  const attrs = {};
103
95
  const errors = Cause.prettyErrors(options.cause);
@@ -112,9 +104,9 @@ export function makeLogger(telemetry) {
112
104
  attrs[`effect.log_span.${label}`] = now - start;
113
105
  }
114
106
  const msg = messageText(options.message);
115
- const span = Context.getOrUndefined(options.fiber.context, Tracer.ParentSpan);
107
+ const span = getPropagatedSpan(Context.getOrUndefined(options.fiber.context, Tracer.ParentSpan));
116
108
  const active = context.active();
117
- const ctx = span === undefined ? active : contextOf(span, active === undefined ? ROOT_CONTEXT : active);
109
+ const ctx = span === undefined ? active : contextOfSpan(span, active === undefined ? ROOT_CONTEXT : active);
118
110
  context.with(ctx, () => write(telemetry.logger, level, msg, attrs));
119
111
  }
120
112
  catch {
@@ -122,6 +114,10 @@ export function makeLogger(telemetry) {
122
114
  }
123
115
  });
124
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
+ }
125
121
  /** A layer that installs makeLogger(telemetry) as Effect's logger. */
126
122
  export function loggerLayer(telemetry, options = {}) {
127
123
  return Logger.layer([makeLogger(telemetry)], { mergeWithExisting: options.mergeWithExisting ?? false });
package/dist/metrics.d.ts CHANGED
@@ -1,24 +1,37 @@
1
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:
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.
4
5
  *
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.
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.
13
12
  *
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.
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.
19
27
  */
20
28
  import type { Telemetry } from "@libo11y/core";
21
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>;
22
35
  /**
23
36
  * A layer that bridges Effect metrics to telemetry.meterProvider. Every layer for one telemetry
24
37
  * shares one registry, so building the layer again keeps the series it has.
package/dist/metrics.js CHANGED
@@ -1,28 +1,91 @@
1
1
  import * as Context from "effect/Context";
2
+ import { constVoid } from "effect/Function";
2
3
  import * as Layer from "effect/Layer";
3
4
  import * as Metric from "effect/Metric";
4
5
  import { VERSION } from "./version.js";
5
6
  /** The instrumentation scope of the bridged metrics. */
6
7
  const SCOPE = "@libo11y/effect";
7
- const EMPTY = Context.empty();
8
- function attributesOf(metadata) {
9
- return { ...(metadata.attributes ?? {}) };
8
+ function attributesOf(attributes) {
9
+ return { ...(attributes ?? {}) };
10
10
  }
11
11
  function numberOf(value) {
12
12
  return typeof value === "bigint" ? Number(value) : value;
13
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
+ }
14
22
  /**
15
23
  * 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.
24
+ * It is a Map, as Effect's registry is, so Metric.snapshot and Metric.snapshotUnsafe keep working.
18
25
  */
19
26
  class BridgeRegistry extends Map {
20
27
  meterInstance;
21
28
  provider;
22
29
  instruments = new Map();
23
- gauges = new Set();
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
+ }
24
69
  bind(provider) {
70
+ if (this.provider === provider)
71
+ return this;
72
+ this.detachBatchCallback();
25
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
+ }
26
89
  return this;
27
90
  }
28
91
  meter() {
@@ -32,13 +95,29 @@ class BridgeRegistry extends Map {
32
95
  return this.meterInstance;
33
96
  }
34
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);
35
106
  try {
36
- this.bridge(metadata);
107
+ this.bridge(key, metadata, pullOnly);
37
108
  }
38
109
  catch {
39
110
  // The metric still works in Effect; only its export is lost.
40
111
  }
41
- return super.set(key, metadata);
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();
42
121
  }
43
122
  instrument(key, make) {
44
123
  let instrument = this.instruments.get(key);
@@ -49,96 +128,224 @@ class BridgeRegistry extends Map {
49
128
  return instrument;
50
129
  }
51
130
  // 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.
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.
53
133
  wrap(metadata, record) {
134
+ if (this.wrappedMetadata.has(metadata))
135
+ return;
136
+ this.wrappedMetadata.add(metadata);
54
137
  const hooks = metadata.hooks;
55
138
  const update = hooks.update;
56
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
+ };
57
151
  const wrapped = {
58
152
  get: hooks.get,
59
153
  update: (input, ctx) => {
60
154
  update(input, ctx);
61
- try {
62
- record(input);
63
- }
64
- catch {
65
- // As in set.
66
- }
155
+ dispatch(input);
67
156
  },
68
157
  modify: modify === update
69
158
  ? (input, ctx) => {
70
159
  modify(input, ctx);
71
- try {
72
- record(input);
73
- }
74
- catch {
75
- // As in set.
76
- }
160
+ dispatch(input);
77
161
  }
78
162
  : modify,
79
163
  };
80
164
  metadata.hooks = wrapped;
81
165
  }
82
- bridge(metadata) {
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) {
83
273
  const meter = this.meter();
84
274
  if (meter === undefined)
85
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) {
86
293
  const { id, description } = metadata;
87
294
  const options = description === undefined ? {} : { description };
88
- const attrs = attributesOf(metadata);
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
+ }
89
306
  switch (metadata.type) {
90
307
  case "Counter": {
91
- const state = metadata.hooks.get(EMPTY);
308
+ const state = metadata.hooks.get(this.snapshotContext);
92
309
  if (state.incremental === true) {
93
- const counter = this.instrument(`counter:${id}`, () => meter.createCounter(id, options));
94
- this.wrap(metadata, (input) => {
310
+ this.wrap(metadata, (meter, input) => {
95
311
  const n = numberOf(input);
96
- if (n >= 0)
312
+ if (n >= 0) {
313
+ const counter = this.instrument(`counter:${id}`, () => meter.createCounter(id, options));
97
314
  counter.add(n, attrs);
315
+ }
98
316
  });
99
317
  }
100
318
  else {
101
- const counter = this.instrument(`updown:${id}`, () => meter.createUpDownCounter(id, options));
102
- this.wrap(metadata, (input) => counter.add(numberOf(input), attrs));
319
+ this.wrap(metadata, (meter, input) => {
320
+ const counter = this.instrument(`updown:${id}`, () => meter.createUpDownCounter(id, options));
321
+ counter.add(numberOf(input), attrs);
322
+ });
103
323
  }
104
324
  return;
105
325
  }
106
326
  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) }));
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
+ });
109
331
  return;
110
332
  }
111
333
  case "Histogram": {
112
- const state = metadata.hooks.get(EMPTY);
334
+ const state = metadata.hooks.get(this.snapshotContext);
113
335
  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));
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
+ });
119
343
  return;
120
344
  }
121
345
  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
- }
346
+ this.wrap(metadata, (meter, input) => {
347
+ const histogram = this.instrument(`histogram:${id}`, () => meter.createHistogram(id, options));
348
+ histogram.record(numberOf(input[0]), attrs);
142
349
  });
143
350
  return;
144
351
  }
@@ -157,6 +364,26 @@ function registryFor(provider) {
157
364
  }
158
365
  return registry;
159
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
+ }
160
387
  /**
161
388
  * A layer that bridges Effect metrics to telemetry.meterProvider. Every layer for one telemetry
162
389
  * shares one registry, so building the layer again keeps the series it has.
@@ -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;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Internal helpers for resolving the active propagated Effect span and mapping it onto an
3
+ * OpenTelemetry Context while skipping Tracer.DisablePropagation frames and invalid span contexts.
4
+ */
5
+ import * as OtelTracer from "@effect/opentelemetry/OtelTracer";
6
+ import { isSpanContextValid, TraceFlags, trace, } from "@opentelemetry/api";
7
+ import * as Context from "effect/Context";
8
+ import * as Fiber from "effect/Fiber";
9
+ import * as Option from "effect/Option";
10
+ import * as Tracer from "effect/Tracer";
11
+ /**
12
+ * Walks past spans annotated with Tracer.DisablePropagation, matching OtelTracer's
13
+ * getPropagatedSpan (and Effect's internal filterDisablePropagation).
14
+ */
15
+ export function getPropagatedSpan(span) {
16
+ let current = span;
17
+ while (current !== undefined && Context.get(current.annotations, Tracer.DisablePropagation)) {
18
+ current = current._tag === "Span" ? Option.getOrUndefined(current.parent) : undefined;
19
+ }
20
+ return current;
21
+ }
22
+ /** Active propagated Effect span on the current fiber, if any. */
23
+ export function activePropagatedSpan() {
24
+ const fiber = Fiber.getCurrent();
25
+ if (fiber === undefined)
26
+ return undefined;
27
+ return getPropagatedSpan(Context.getOrUndefined(fiber.context, Tracer.ParentSpan));
28
+ }
29
+ /**
30
+ * Attaches an Effect span onto an OpenTelemetry Context when its span context is valid.
31
+ * Preserves the underlying OpenTelemetry Span object when present (e.g. OtelSpan), and preserves
32
+ * OtelTraceFlags and OtelTraceState annotations on ExternalSpan values.
33
+ */
34
+ export function contextOfSpan(span, base) {
35
+ const otel = span.span;
36
+ if (typeof otel === "object" &&
37
+ otel !== null &&
38
+ typeof otel.spanContext === "function") {
39
+ const otelSpan = otel;
40
+ if (!isSpanContextValid(otelSpan.spanContext()))
41
+ return base;
42
+ return trace.setSpan(base, otelSpan);
43
+ }
44
+ const annotatedFlags = Context.getOrUndefined(span.annotations, OtelTracer.OtelTraceFlags);
45
+ const annotatedState = Context.getOrUndefined(span.annotations, OtelTracer.OtelTraceState);
46
+ const sc = {
47
+ traceId: span.traceId,
48
+ spanId: span.spanId,
49
+ traceFlags: annotatedFlags ?? (span.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE),
50
+ isRemote: span._tag === "ExternalSpan",
51
+ ...(annotatedState === undefined ? {} : { traceState: annotatedState }),
52
+ };
53
+ if (!isSpanContextValid(sc))
54
+ return base;
55
+ return trace.setSpanContext(base, sc);
56
+ }
package/dist/tracer.d.ts CHANGED
@@ -9,8 +9,28 @@
9
9
  import * as OtelTracer from "@effect/opentelemetry/OtelTracer";
10
10
  import type { Telemetry } from "@libo11y/core";
11
11
  import * as Layer from "effect/Layer";
12
+ import * as Tracer from "effect/Tracer";
13
+ /** SQL tracing options for tracerLayer and layer. */
14
+ export interface SqlLayerOptions {
15
+ /**
16
+ * Re-parent detached `sql.connect` root spans (emitted by `@effect/sql-pg` `PgPool`) onto the
17
+ * current fiber's active propagated Effect span and set `Statement.SpanPropagationEnabled = true`.
18
+ * Default false.
19
+ */
20
+ readonly parentConnectSpans?: boolean;
21
+ }
22
+ /** Options for tracerLayer. */
23
+ export interface TracerLayerOptions {
24
+ /** Optional SQL span parenting behavior. */
25
+ readonly sql?: SqlLayerOptions;
26
+ }
27
+ /**
28
+ * Wraps an Effect Tracer so detached `sql.connect` root spans (`options.root && Option.isNone(options.parent)`)
29
+ * attach to the active propagated Effect span (skipping Tracer.DisablePropagation frames).
30
+ */
31
+ export declare function wrapSqlConnectTracer(base: Tracer.Tracer): Tracer.Tracer;
12
32
  /**
13
33
  * A layer that installs the Effect Tracer over telemetry.tracerProvider, with the instrumentation
14
34
  * scope "effect". It also provides the OtelTracer service of `@effect/opentelemetry`.
15
35
  */
16
- export declare function tracerLayer(telemetry: Telemetry): Layer.Layer<OtelTracer.OtelTracer>;
36
+ export declare function tracerLayer(telemetry: Telemetry, options?: TracerLayerOptions): Layer.Layer<OtelTracer.OtelTracer>;