@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.
@@ -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
+ }
@@ -0,0 +1,36 @@
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
+ 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;
32
+ /**
33
+ * A layer that installs the Effect Tracer over telemetry.tracerProvider, with the instrumentation
34
+ * scope "effect". It also provides the OtelTracer service of `@effect/opentelemetry`.
35
+ */
36
+ export declare function tracerLayer(telemetry: Telemetry, options?: TracerLayerOptions): Layer.Layer<OtelTracer.OtelTracer>;
package/dist/tracer.js ADDED
@@ -0,0 +1,51 @@
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 Effect from "effect/Effect";
11
+ import * as Layer from "effect/Layer";
12
+ import * as Option from "effect/Option";
13
+ import * as Statement from "effect/sql/Statement";
14
+ import * as Tracer from "effect/Tracer";
15
+ import { activePropagatedSpan } from "./span-context.js";
16
+ /**
17
+ * Wraps an Effect Tracer so detached `sql.connect` root spans (`options.root && Option.isNone(options.parent)`)
18
+ * attach to the active propagated Effect span (skipping Tracer.DisablePropagation frames).
19
+ */
20
+ export function wrapSqlConnectTracer(base) {
21
+ return Tracer.make({
22
+ span(options) {
23
+ if (options.name === "sql.connect" && options.root && Option.isNone(options.parent)) {
24
+ const parent = activePropagatedSpan();
25
+ if (parent !== undefined) {
26
+ return base.span({
27
+ ...options,
28
+ root: false,
29
+ parent: Option.some(parent),
30
+ sampled: parent.sampled ? options.sampled : false,
31
+ });
32
+ }
33
+ }
34
+ return base.span(options);
35
+ },
36
+ ...(base.context === undefined ? {} : { context: base.context }),
37
+ });
38
+ }
39
+ /**
40
+ * A layer that installs the Effect Tracer over telemetry.tracerProvider, with the instrumentation
41
+ * scope "effect". It also provides the OtelTracer service of `@effect/opentelemetry`.
42
+ */
43
+ export function tracerLayer(telemetry, options = {}) {
44
+ if (options.sql?.parentConnectSpans !== true) {
45
+ return OtelTracer.layer.pipe(Layer.provide(Layer.succeed(OtelTracer.OtelTracerProvider, telemetry.tracerProvider)));
46
+ }
47
+ const otelTracerLayer = OtelTracer.layerTracer.pipe(Layer.provide(Layer.succeed(OtelTracer.OtelTracerProvider, telemetry.tracerProvider)));
48
+ const effectTracerLayer = Layer.effect(Tracer.Tracer, Effect.map(OtelTracer.make, wrapSqlConnectTracer));
49
+ const sqlPropagationLayer = Layer.succeed(Statement.SpanPropagationEnabled, true);
50
+ return Layer.merge(effectTracerLayer, sqlPropagationLayer).pipe(Layer.provideMerge(otelTracerLayer));
51
+ }
@@ -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.9.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.9.0";
@@ -0,0 +1,101 @@
1
+ import { type Carrier } from "@libo11y/core";
2
+ import { type ScheduledSpanOptions } from "@libo11y/core/edge";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Stream from "effect/Stream";
5
+ import * as Tracer from "effect/Tracer";
6
+ /** One detached Carrier or an iterable of Carriers (nullish entries are ignored). */
7
+ export type CarrierInput = Carrier | null | undefined | Iterable<Carrier | null | undefined>;
8
+ /**
9
+ * Captures the active Effect fiber's propagated OpenTelemetry span context and egress-filtered
10
+ * baggage (using `Libo11yTelemetry` when present in context) into a detached `@libo11y/core`
11
+ * `Carrier`. Returns `ZERO_CARRIER` when no valid span is active or telemetry is disabled.
12
+ */
13
+ export declare const captureContext: Effect.Effect<Carrier>;
14
+ /**
15
+ * Attaches deduplicated OpenTelemetry span links from detached carriers onto the current active
16
+ * Effect span (a no-op when no span is active or no carriers contain valid span contexts).
17
+ */
18
+ export declare function linkCarriers(carriers: CarrierInput): Effect.Effect<void>;
19
+ /** Options for {@link withLinkedContext}. */
20
+ export type LinkedContextOptions = Omit<Tracer.SpanOptionsNoTrace, "root">;
21
+ /**
22
+ * Runs an Effect inside a new root span linked to one or more detached `@libo11y/core` `Carrier`s,
23
+ * preserving caller ambient baggage while merging carrier baggage (carrier keys overwrite matching
24
+ * caller keys).
25
+ */
26
+ export declare const withLinkedContext: {
27
+ (carrier: CarrierInput, name: string, options?: LinkedContextOptions): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
28
+ <A, E, R>(effect: Effect.Effect<A, E, R>, carrier: CarrierInput, name: string, options?: LinkedContextOptions): Effect.Effect<A, E, R>;
29
+ };
30
+ /**
31
+ * Wraps each Effect/Stream-returning method of a Durable Object implementation in a semconv 1.41.0
32
+ * `SERVER` span named `${className}/${method}` with `rpc.system.name: "cloudflare_durable_object"`,
33
+ * `rpc.method: "${className}/${method}"`, and `o11y.durable_object.class: className`.
34
+ */
35
+ export declare function traceDurableObjectMethods<T extends Record<string, unknown>>(className: string, methods: T): T;
36
+ /**
37
+ * Wraps a caller-side Durable Object RPC Effect in a semconv 1.41.0 `CLIENT` span named
38
+ * `${className}/${method}` with `rpc.system.name: "cloudflare_durable_object"`,
39
+ * `rpc.method: "${className}/${method}"`, and `o11y.durable_object.class: className`.
40
+ */
41
+ export declare const traceDurableObjectCall: {
42
+ (className: string, method: string): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
43
+ <A, E, R>(effect: Effect.Effect<A, E, R>, className: string, method: string): Effect.Effect<A, E, R>;
44
+ };
45
+ /**
46
+ * Wraps a Durable Object stub (including proxy-based stubs whose methods return dual Effect/Stream
47
+ * values) so every Effect or Stream call runs inside a semconv 1.41.0 `CLIENT` span while
48
+ * preserving both `Effect` and `Stream` capabilities.
49
+ */
50
+ export declare function traceDurableObjectStub<T extends object>(className: string, stub: T): T;
51
+ /**
52
+ * Enriches Effect RPC handler functions inside a Durable Object by annotating the active Effect
53
+ * RPC server span with `o11y.durable_object.class: className` without opening a duplicate span.
54
+ */
55
+ export declare function enrichDurableObjectRpc<T extends Record<string, unknown>>(className: string, handlers: T): T;
56
+ /** Options for {@link withAlarmSpan}. */
57
+ export interface AlarmSpanOptions {
58
+ /** Detached originating carriers to link onto the alarm root span (deduplicated). */
59
+ readonly links?: CarrierInput;
60
+ /** Additional span attributes to record on the alarm span. */
61
+ readonly attributes?: Readonly<Record<string, unknown>>;
62
+ }
63
+ /**
64
+ * Runs a Durable Object alarm callback in a root `SERVER` span (`${className} alarm ${callback}`)
65
+ * with `o11y.durable_object.class` and `faas.trigger: "timer"`, optionally linked to originating
66
+ * detached carriers.
67
+ */
68
+ export declare const withAlarmSpan: {
69
+ (className: string, callback: string, linksOrOptions?: CarrierInput | AlarmSpanOptions): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
70
+ <A, E, R>(effect: Effect.Effect<A, E, R>, className: string, callback: string, linksOrOptions?: CarrierInput | AlarmSpanOptions): Effect.Effect<A, E, R>;
71
+ };
72
+ /**
73
+ * Runs a Cloudflare Workers scheduled/cron job in a root `SERVER` span (`scheduled ${job ?? cron}`)
74
+ * with `faas.trigger: "timer"`, `faas.cron`, and optional ISO `faas.time`.
75
+ */
76
+ export declare const withCronSpan: {
77
+ (cron: string, jobOrOptions?: string | ScheduledSpanOptions): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
78
+ <A, E, R>(effect: Effect.Effect<A, E, R>, cron: string, jobOrOptions?: string | ScheduledSpanOptions): Effect.Effect<A, E, R>;
79
+ };
80
+ /** Options for {@link withQueueBatchSpan}. */
81
+ export interface QueueBatchSpanOptions<M = unknown> {
82
+ /** Property name carrying the serialized detached Carrier on each message body. Default "_o11y". */
83
+ readonly carrierField?: string;
84
+ /**
85
+ * Custom carrier extractor per streamed message. Defaults to extracting `carrierField` from
86
+ * `message` or `message.body` via `@libo11y/core/edge`'s `extractQueueCarrier`.
87
+ */
88
+ readonly extractCarrier?: (message: M) => Carrier | null | undefined;
89
+ /**
90
+ * Optional callback invoked with the final streamed message count before the batch span ends
91
+ * (for example, to record an application batch-size histogram).
92
+ */
93
+ readonly onBatchCount?: (count: number) => Effect.Effect<void> | void;
94
+ }
95
+ /**
96
+ * Wraps a streaming Cloudflare Queues consumer `(messages: Stream<M>) => Effect<A, E, R>` in a
97
+ * root `CONSUMER` span (`process ${queue}`), extracting deduplicated `_o11y` detached carriers
98
+ * from each message as span links, recording `messaging.batch.message_count`, and invoking
99
+ * `options.onBatchCount` before the span ends.
100
+ */
101
+ export declare function withQueueBatchSpan<M = unknown>(queue: string, options?: QueueBatchSpanOptions<M>): <SE, SR, A, E, R>(consume: (messages: Stream.Stream<M, SE, SR>) => Effect.Effect<A, E, R>) => (messages: Stream.Stream<M, SE, SR>) => Effect.Effect<A, E, R>;
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Server and Cloudflare Workers Effect 4 combinators built directly on `@libo11y/core` detached
3
+ * context (`Carrier`) and `@libo11y/core/edge` single-owner Workers, Durable Object, alarm,
4
+ * scheduled, and Queues span specifications and queue carrier codec.
5
+ *
6
+ * Every combinator preserves Effect and Stream types (including dual Effect/Stream Durable Object
7
+ * stubs) and emits spans through Effect's Tracer (scope "effect" via OtelTracer).
8
+ */
9
+ import * as OtelTracer from "@effect/opentelemetry/OtelTracer";
10
+ import { captureContext as coreCaptureContext, linksFromCarriers, startLinkedSpan, } from "@libo11y/core";
11
+ import { alarmSpanSpec, DEFAULT_CARRIER_FIELD, durableObjectEnrichAttributes, durableObjectSpanSpec, extractQueueCarrier, queueBatchSpanSpec, scheduledSpanSpec, } from "@libo11y/core/edge";
12
+ import { INVALID_SPAN_CONTEXT, SpanKind as OtelSpanKind, context as otelContext, propagation as otelPropagation, trace as otelTrace, } from "@opentelemetry/api";
13
+ import * as Context from "effect/Context";
14
+ import * as Effect from "effect/Effect";
15
+ import { dual } from "effect/Function";
16
+ import * as Option from "effect/Option";
17
+ import * as Stream from "effect/Stream";
18
+ import * as Tracer from "effect/Tracer";
19
+ import { Libo11yTelemetry } from "./layer.js";
20
+ import { contextOfSpan, getPropagatedSpan } from "./span-context.js";
21
+ function isCarrierIterable(input) {
22
+ return input !== null && input !== undefined && typeof input === "object" && Symbol.iterator in input;
23
+ }
24
+ function normalizeCarriers(input) {
25
+ if (input === null || input === undefined)
26
+ return [];
27
+ return isCarrierIterable(input) ? [...input] : [input];
28
+ }
29
+ function toEffectSpanKind(kind) {
30
+ switch (kind) {
31
+ case OtelSpanKind.CLIENT:
32
+ return "client";
33
+ case OtelSpanKind.SERVER:
34
+ return "server";
35
+ case OtelSpanKind.PRODUCER:
36
+ return "producer";
37
+ case OtelSpanKind.CONSUMER:
38
+ return "consumer";
39
+ default:
40
+ return "internal";
41
+ }
42
+ }
43
+ function toEffectSpanLinks(links) {
44
+ return links.map((link) => ({
45
+ span: OtelTracer.makeExternalSpan({
46
+ traceId: link.context.traceId,
47
+ spanId: link.context.spanId,
48
+ traceFlags: link.context.traceFlags,
49
+ ...(link.context.traceState === undefined ? {} : { traceState: link.context.traceState }),
50
+ }),
51
+ attributes: (link.attributes ?? {}),
52
+ }));
53
+ }
54
+ function specToSpanOptions(spec, extra) {
55
+ return {
56
+ kind: toEffectSpanKind(spec.kind),
57
+ attributes: {
58
+ ...spec.attributes,
59
+ ...(extra?.attributes ?? {}),
60
+ },
61
+ ...(extra?.root === undefined ? {} : { root: extra.root }),
62
+ ...(extra?.links !== undefined && extra.links.length > 0 ? { links: extra.links } : {}),
63
+ };
64
+ }
65
+ // Inert Telemetry passed to @libo11y/core's startLinkedSpan strictly to reuse core's exact
66
+ // Go-compatible W3C baggage parsing and caller-baggage merge rules without creating a real span.
67
+ const BAGGAGE_MERGE_TELEMETRY = {
68
+ tracerProvider: {
69
+ getTracer: () => ({
70
+ startSpan: () => otelTrace.wrapSpanContext(INVALID_SPAN_CONTEXT),
71
+ }),
72
+ },
73
+ };
74
+ function mergeCarrierBaggage(carriers) {
75
+ let hasCarrierBaggage = false;
76
+ for (const c of carriers) {
77
+ if (c?.baggage !== undefined && c.baggage !== "") {
78
+ hasCarrierBaggage = true;
79
+ break;
80
+ }
81
+ }
82
+ if (!hasCarrierBaggage)
83
+ return undefined;
84
+ let ctx = otelContext.active();
85
+ for (const c of carriers) {
86
+ if (c?.baggage === undefined || c.baggage === "")
87
+ continue;
88
+ ctx = startLinkedSpan(BAGGAGE_MERGE_TELEMETRY, c, "baggage", { context: ctx }).context;
89
+ }
90
+ return otelPropagation.getBaggage(ctx);
91
+ }
92
+ const wrappedTracerToRoot = new WeakMap();
93
+ function wrapTracerWithBaggage(base, baggage) {
94
+ const root = wrappedTracerToRoot.get(base) ?? base;
95
+ const wrapped = Tracer.make({
96
+ span: (options) => root.span(options),
97
+ context(primitive, fiber) {
98
+ const active = otelContext.active();
99
+ const withBag = otelPropagation.setBaggage(active, baggage);
100
+ return otelContext.with(withBag, () => root.context !== undefined
101
+ ? root.context(primitive, fiber)
102
+ : primitive["~effect/Effect/evaluate"](fiber));
103
+ },
104
+ });
105
+ wrappedTracerToRoot.set(wrapped, root);
106
+ return wrapped;
107
+ }
108
+ function applySpanToValue(value, name, options) {
109
+ const isEff = Effect.isEffect(value);
110
+ const isStr = Stream.isStream(value);
111
+ if (isEff && isStr) {
112
+ const tracedEffect = Effect.withSpan(value, name, options);
113
+ const tracedStream = Stream.withSpan(value, name, options);
114
+ return Object.assign(tracedEffect, {
115
+ [Stream.TypeId]: tracedStream[Stream.TypeId],
116
+ channel: tracedStream.channel,
117
+ });
118
+ }
119
+ if (isEff)
120
+ return Effect.withSpan(value, name, options);
121
+ if (isStr)
122
+ return Stream.withSpan(value, name, options);
123
+ return value;
124
+ }
125
+ function annotateValue(value, attrs) {
126
+ const isEff = Effect.isEffect(value);
127
+ const isStr = Stream.isStream(value);
128
+ if (isEff && isStr) {
129
+ const annotatedEffect = Effect.annotateCurrentSpan(attrs).pipe(Effect.andThen(value));
130
+ const annotatedStream = Stream.unwrap(Effect.annotateCurrentSpan(attrs).pipe(Effect.as(value)));
131
+ return Object.assign(annotatedEffect, {
132
+ [Stream.TypeId]: annotatedStream[Stream.TypeId],
133
+ channel: annotatedStream.channel,
134
+ });
135
+ }
136
+ if (isEff)
137
+ return Effect.annotateCurrentSpan(attrs).pipe(Effect.andThen(value));
138
+ if (isStr)
139
+ return Stream.unwrap(Effect.annotateCurrentSpan(attrs).pipe(Effect.as(value)));
140
+ return value;
141
+ }
142
+ /**
143
+ * Captures the active Effect fiber's propagated OpenTelemetry span context and egress-filtered
144
+ * baggage (using `Libo11yTelemetry` when present in context) into a detached `@libo11y/core`
145
+ * `Carrier`. Returns `ZERO_CARRIER` when no valid span is active or telemetry is disabled.
146
+ */
147
+ export const captureContext = Effect.withFiber((fiber) => Effect.sync(() => {
148
+ const telemetry = Context.getOrUndefined(fiber.context, Libo11yTelemetry);
149
+ let ctx = otelContext.active();
150
+ const span = getPropagatedSpan(Context.getOrUndefined(fiber.context, Tracer.ParentSpan));
151
+ if (span !== undefined) {
152
+ ctx = contextOfSpan(span, ctx);
153
+ }
154
+ return coreCaptureContext(telemetry, ctx);
155
+ }));
156
+ /**
157
+ * Attaches deduplicated OpenTelemetry span links from detached carriers onto the current active
158
+ * Effect span (a no-op when no span is active or no carriers contain valid span contexts).
159
+ */
160
+ export function linkCarriers(carriers) {
161
+ return Effect.gen(function* () {
162
+ const otelLinks = linksFromCarriers(normalizeCarriers(carriers));
163
+ if (otelLinks.length === 0)
164
+ return;
165
+ const current = yield* Effect.option(Effect.currentSpan);
166
+ if (Option.isSome(current)) {
167
+ current.value.addLinks(toEffectSpanLinks(otelLinks));
168
+ }
169
+ });
170
+ }
171
+ /**
172
+ * Runs an Effect inside a new root span linked to one or more detached `@libo11y/core` `Carrier`s,
173
+ * preserving caller ambient baggage while merging carrier baggage (carrier keys overwrite matching
174
+ * caller keys).
175
+ */
176
+ export const withLinkedContext = dual((args) => Effect.isEffect(args[0]), (effect, carrier, name, options) => Effect.suspend(() => {
177
+ const carriers = normalizeCarriers(carrier);
178
+ const carrierLinks = toEffectSpanLinks(linksFromCarriers(carriers));
179
+ const allLinks = [...carrierLinks, ...(options?.links ?? [])];
180
+ const mergedBaggage = mergeCarrierBaggage(carriers);
181
+ const traced = Effect.withSpan(effect, name, {
182
+ ...options,
183
+ root: true,
184
+ ...(allLinks.length > 0 ? { links: allLinks } : {}),
185
+ });
186
+ if (mergedBaggage === undefined)
187
+ return traced;
188
+ return Effect.withFiber((fiber) => {
189
+ const baseTracer = fiber.getRef(Tracer.Tracer);
190
+ return Effect.provideService(traced, Tracer.Tracer, wrapTracerWithBaggage(baseTracer, mergedBaggage));
191
+ });
192
+ }));
193
+ /**
194
+ * Wraps each Effect/Stream-returning method of a Durable Object implementation in a semconv 1.41.0
195
+ * `SERVER` span named `${className}/${method}` with `rpc.system.name: "cloudflare_durable_object"`,
196
+ * `rpc.method: "${className}/${method}"`, and `o11y.durable_object.class: className`.
197
+ */
198
+ export function traceDurableObjectMethods(className, methods) {
199
+ return Object.fromEntries(Object.entries(methods).map(([name, member]) => {
200
+ if (typeof member !== "function")
201
+ return [name, member];
202
+ const spec = durableObjectSpanSpec(className, name, OtelSpanKind.SERVER);
203
+ const spanOptions = specToSpanOptions(spec);
204
+ return [
205
+ name,
206
+ function (...args) {
207
+ const result = Reflect.apply(member, this, args);
208
+ return applySpanToValue(result, spec.name, spanOptions);
209
+ },
210
+ ];
211
+ }));
212
+ }
213
+ /**
214
+ * Wraps a caller-side Durable Object RPC Effect in a semconv 1.41.0 `CLIENT` span named
215
+ * `${className}/${method}` with `rpc.system.name: "cloudflare_durable_object"`,
216
+ * `rpc.method: "${className}/${method}"`, and `o11y.durable_object.class: className`.
217
+ */
218
+ export const traceDurableObjectCall = dual((args) => Effect.isEffect(args[0]), (effect, className, method) => {
219
+ const spec = durableObjectSpanSpec(className, method, OtelSpanKind.CLIENT);
220
+ return Effect.withSpan(effect, spec.name, specToSpanOptions(spec));
221
+ });
222
+ /**
223
+ * Wraps a Durable Object stub (including proxy-based stubs whose methods return dual Effect/Stream
224
+ * values) so every Effect or Stream call runs inside a semconv 1.41.0 `CLIENT` span while
225
+ * preserving both `Effect` and `Stream` capabilities.
226
+ */
227
+ export function traceDurableObjectStub(className, stub) {
228
+ return new Proxy(stub, {
229
+ get(target, prop, receiver) {
230
+ if (typeof prop !== "string" || prop === "then") {
231
+ return Reflect.get(target, prop, receiver);
232
+ }
233
+ const member = Reflect.get(target, prop, receiver);
234
+ if (typeof member !== "function")
235
+ return member;
236
+ const spec = durableObjectSpanSpec(className, prop, OtelSpanKind.CLIENT);
237
+ const spanOptions = specToSpanOptions(spec);
238
+ return (...args) => {
239
+ const result = Reflect.apply(member, target, args);
240
+ return applySpanToValue(result, spec.name, spanOptions);
241
+ };
242
+ },
243
+ });
244
+ }
245
+ /**
246
+ * Enriches Effect RPC handler functions inside a Durable Object by annotating the active Effect
247
+ * RPC server span with `o11y.durable_object.class: className` without opening a duplicate span.
248
+ */
249
+ export function enrichDurableObjectRpc(className, handlers) {
250
+ const attrs = durableObjectEnrichAttributes(className);
251
+ return Object.fromEntries(Object.entries(handlers).map(([name, member]) => {
252
+ if (typeof member !== "function")
253
+ return [name, member];
254
+ return [
255
+ name,
256
+ function (...args) {
257
+ const result = Reflect.apply(member, this, args);
258
+ return annotateValue(result, attrs);
259
+ },
260
+ ];
261
+ }));
262
+ }
263
+ function isAlarmSpanOptions(value) {
264
+ if (value === null || value === undefined || typeof value !== "object")
265
+ return false;
266
+ if (Symbol.iterator in value)
267
+ return false;
268
+ if ("traceparent" in value)
269
+ return false;
270
+ return "links" in value || "attributes" in value;
271
+ }
272
+ /**
273
+ * Runs a Durable Object alarm callback in a root `SERVER` span (`${className} alarm ${callback}`)
274
+ * with `o11y.durable_object.class` and `faas.trigger: "timer"`, optionally linked to originating
275
+ * detached carriers.
276
+ */
277
+ export const withAlarmSpan = dual((args) => Effect.isEffect(args[0]), (effect, className, callback, linksOrOptions) => Effect.suspend(() => {
278
+ const spec = alarmSpanSpec(className, callback);
279
+ const opts = linksOrOptions !== undefined && isAlarmSpanOptions(linksOrOptions)
280
+ ? linksOrOptions
281
+ : { links: linksOrOptions };
282
+ const links = opts.links === undefined ? [] : toEffectSpanLinks(linksFromCarriers(normalizeCarriers(opts.links)));
283
+ return Effect.withSpan(effect, spec.name, specToSpanOptions(spec, {
284
+ root: true,
285
+ links,
286
+ ...(opts.attributes === undefined ? {} : { attributes: opts.attributes }),
287
+ }));
288
+ }));
289
+ /**
290
+ * Runs a Cloudflare Workers scheduled/cron job in a root `SERVER` span (`scheduled ${job ?? cron}`)
291
+ * with `faas.trigger: "timer"`, `faas.cron`, and optional ISO `faas.time`.
292
+ */
293
+ export const withCronSpan = dual((args) => Effect.isEffect(args[0]), (effect, cron, jobOrOptions) => {
294
+ const spec = scheduledSpanSpec(cron, typeof jobOrOptions === "string" ? { job: jobOrOptions } : jobOrOptions);
295
+ return Effect.withSpan(effect, spec.name, specToSpanOptions(spec, { root: true }));
296
+ });
297
+ function defaultExtractMessageCarrier(message, field) {
298
+ const direct = extractQueueCarrier(message, { field });
299
+ if (direct !== undefined)
300
+ return direct;
301
+ if (typeof message === "object" && message !== null && "body" in message) {
302
+ return extractQueueCarrier(message.body, { field });
303
+ }
304
+ return undefined;
305
+ }
306
+ /**
307
+ * Wraps a streaming Cloudflare Queues consumer `(messages: Stream<M>) => Effect<A, E, R>` in a
308
+ * root `CONSUMER` span (`process ${queue}`), extracting deduplicated `_o11y` detached carriers
309
+ * from each message as span links, recording `messaging.batch.message_count`, and invoking
310
+ * `options.onBatchCount` before the span ends.
311
+ */
312
+ export function withQueueBatchSpan(queue, options = {}) {
313
+ const field = options.carrierField ?? DEFAULT_CARRIER_FIELD;
314
+ const spec = queueBatchSpanSpec(queue);
315
+ const spanOptions = specToSpanOptions(spec, { root: true });
316
+ return (consume) => (messages) => Effect.suspend(() => {
317
+ let count = 0;
318
+ const seen = new Set();
319
+ return Effect.gen(function* () {
320
+ const currentSpan = yield* Effect.option(Effect.currentSpan);
321
+ const tapped = Stream.tap(messages, (message) => Effect.sync(() => {
322
+ count++;
323
+ const carrier = options.extractCarrier !== undefined
324
+ ? options.extractCarrier(message)
325
+ : defaultExtractMessageCarrier(message, field);
326
+ if (carrier === undefined || carrier === null)
327
+ return;
328
+ const links = linksFromCarriers([carrier]);
329
+ const fresh = [];
330
+ for (const link of links) {
331
+ const key = `${link.context.traceId}:${link.context.spanId}`;
332
+ if (seen.has(key))
333
+ continue;
334
+ seen.add(key);
335
+ fresh.push(link);
336
+ }
337
+ if (fresh.length > 0 && Option.isSome(currentSpan)) {
338
+ currentSpan.value.addLinks(toEffectSpanLinks(fresh));
339
+ }
340
+ }));
341
+ return yield* consume(tapped).pipe(Effect.ensuring(Effect.suspend(() => {
342
+ const annotate = Effect.annotateCurrentSpan("messaging.batch.message_count", count);
343
+ if (options.onBatchCount === undefined)
344
+ return annotate;
345
+ return annotate.pipe(Effect.andThen(Effect.suspend(() => {
346
+ const res = options.onBatchCount?.(count);
347
+ return Effect.isEffect(res) ? res : Effect.void;
348
+ })));
349
+ })));
350
+ }).pipe(Effect.withSpan(spec.name, spanOptions));
351
+ });
352
+ }
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.9.0",
4
+ "description": "The libo11y bridge for Effect 4: Tracer, Logger, and Metrics layers, late-bound client layers with gated single-carrier HTTP/WebSocket RPC propagation, and server/Workers combinators. Runtime-neutral over @libo11y/server, @libo11y/workers, @libo11y/web, @libo11y/rum, and @libo11y/react-native.",
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.9.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.9.0",
30
+ "@libo11y/test": "0.9.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
+ }