From cd531d2ec79a374c582faa44edefc451be8974db Mon Sep 17 00:00:00 2001 From: effect-bot <129879685+effect-bot@users.noreply.github.com> Date: Fri, 30 Oct 2026 09:52:44 +1300 Subject: [PATCH 01/15] Add Match.whenFilter for Filter-backed extracting cases (#10094) --- .changeset/match-when-filter.md | 5 ++ packages/effect/src/Match.ts | 62 ++++++++++++++++++++++++ packages/effect/src/internal/matcher.ts | 45 +++++++++++++++++ packages/effect/test/Match.test.ts | 64 ++++++++++++++++++++++++- packages/effect/typetest/Match.tst.ts | 64 ++++++++++++++++++++++++- 5 files changed, 237 insertions(+), 3 deletions(-) create mode 100644 .changeset/match-when-filter.md diff --git a/.changeset/match-when-filter.md b/.changeset/match-when-filter.md new file mode 100644 index 0000000000..bc1b2d6981 --- /dev/null +++ b/.changeset/match-when-filter.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +Add `Match.whenFilter`, a case that runs a `Filter` once and passes its extracted value to the handler, falling through with the original input when the filter fails. diff --git a/packages/effect/src/Match.ts b/packages/effect/src/Match.ts index 886b18e738..d44c8a821e 100644 --- a/packages/effect/src/Match.ts +++ b/packages/effect/src/Match.ts @@ -11,6 +11,7 @@ * @stability stable * @since 4.0.0 */ +import type * as Filter from "./Filter.ts" import * as internal from "./internal/matcher.ts" import type * as Option from "./Option.ts" import type { Pipeable } from "./Pipeable.ts" @@ -817,6 +818,67 @@ export const whenAnd: < Fn extends (_: Types.WhenMatch>, ...args: Args) => Ret >(...args: [...patterns: ExactPatterns, f: Fn]) => internal.whenAnd(...args) +/** + * Defines a case that extracts a value with a `Filter`. + * + * **When to use** + * + * Use when a case both decides whether the input matches and computes a value + * the handler needs, such as parsing or normalizing the input, so the work is + * not repeated inside the handler. + * + * **Details** + * + * The filter runs once when the case is reached, and never if an earlier case + * already matched. On success, the handler receives the filter's pass value. + * On failure, the failure value is discarded and matching continues with the + * original input. + * + * Because a filter can reject any input, this case does not remove anything + * from the remaining input, so it never makes {@link exhaustive} valid on its + * own. + * + * **Example** (Matching on a parsed value) + * + * ```ts import.meta.vitest + * import { Filter, Match, Option } from "effect" + * + * const domainLabel = Filter.fromPredicateOption((query: string) => { + * const label = query.trim().toLowerCase() + * return label.length > 0 ? Option.some(label) : Option.none() + * }) + * + * const describeQuery = Match.type().pipe( + * Match.when("", () => "empty"), + * Match.whenFilter(domainLabel, (label) => `search:${label}`), + * Match.orElse(() => "invalid") + * ) + * + * describeQuery(" ACME ") // => "search:acme" + * describeQuery("") // => "empty" + * describeQuery(" ") // => "invalid" + * ``` + * + * @see {@link when} for matching a pattern and receiving the original input + * + * @stability stable + * @category defining patterns + * @since 4.2.0 + */ +export const whenFilter: < + Input, + Pass, + Fail, + Ret, + Args extends Array, + Fn extends (_: Pass, ...args: Args) => Ret +>( + filter: Filter.Filter, + f: Fn +) => ( + self: Matcher +) => Matcher, Pr, Ret, Args> = internal.whenFilter + /** * Matches values based on a specified discriminant field. * diff --git a/packages/effect/src/internal/matcher.ts b/packages/effect/src/internal/matcher.ts index 063eb6fb51..1907b28763 100644 --- a/packages/effect/src/internal/matcher.ts +++ b/packages/effect/src/internal/matcher.ts @@ -1,3 +1,4 @@ +import type * as Filter from "../Filter.ts" import { dual, identity } from "../Function.ts" import type { Case, @@ -311,6 +312,50 @@ export const when = < Args > => (self as any).add(makeWhen(makePredicate(pattern), f as any)) +/** @internal */ +export const whenFilter = < + Input, + Pass, + Fail, + Ret, + Args extends Array, + Fn extends (_: Pass, ...args: Args) => Ret +>( + filter: Filter.Filter, + f: Fn +) => +( + self: Matcher +): Matcher, Pr, Ret, Args> => { + // Caches the result of a successful `guard` for the `evaluate` call that + // follows it, so the filter runs once per match. `evaluate` consumes the + // cache, and re-runs the filter when called without a matching `guard`. + let guarded: { readonly input: unknown; readonly pass: Pass } | undefined + return (self as any).add(makeWhen( + (input) => { + guarded = undefined + const result = filter(input as Input) + if (Result.isFailure(result)) { + return false + } + guarded = { input, pass: result.success } + return true + }, + (input, ...args) => { + const cached = guarded + guarded = undefined + if (cached !== undefined && Object.is(cached.input, input)) { + return f(cached.pass, ...args as Args) + } + const result = filter(input as Input) + if (Result.isFailure(result)) { + throw new Error("effect/Match/whenFilter: input did not match the filter") + } + return f(result.success, ...args as Args) + } + )) +} + /** @internal */ export const whenOr = < R, diff --git a/packages/effect/test/Match.test.ts b/packages/effect/test/Match.test.ts index 2758ec4999..69132e8117 100644 --- a/packages/effect/test/Match.test.ts +++ b/packages/effect/test/Match.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "@effect/vitest" -import { Match, pipe } from "effect" -import { strictEqual } from "./utils/assert.ts" +import { Filter, Match, Option, pipe } from "effect" +import { assertFalse, assertTrue, strictEqual, throws } from "./utils/assert.ts" describe("Match", () => { it("fn keeps the selector arguments", () => { @@ -105,4 +105,64 @@ describe("Match", () => { strictEqual(match([1, 2]), "hit") strictEqual(match([1, 2, 3]), "hit") }) + + it("whenFilter passes the extracted value and otherwise falls through with the original input", () => { + let calls = 0 + const queryToDomainLabel = Filter.fromPredicateOption((query: string) => { + calls++ + const label = query.trim().toLowerCase() + return label.length > 0 ? Option.some(label) : Option.none() + }) + const describeQuery = (query: string) => + Match.value(query).pipe( + Match.when("", () => "empty"), + Match.whenFilter(queryToDomainLabel, (label) => `search:${label}`), + Match.orElse((query) => `invalid:[${query}]`) + ) + + strictEqual(describeQuery(" ACME "), "search:acme") + strictEqual(calls, 1) + strictEqual(describeQuery(""), "empty") + strictEqual(calls, 1) + strictEqual(describeQuery(" "), "invalid:[ ]") + strictEqual(calls, 2) + + const describeType = Match.type().pipe( + Match.whenFilter(queryToDomainLabel, (label) => `search:${label}`), + Match.orElse((query) => `invalid:[${query}]`) + ) + + strictEqual(describeType(" ACME "), "search:acme") + strictEqual(describeType(" "), "invalid:[ ]") + strictEqual(calls, 4) + }) + + it("whenFilter cases keep the guard and evaluate contract of Case", () => { + let calls = 0 + let fail = false + const matcher = Match.type().pipe( + Match.whenFilter( + Filter.fromPredicateOption((s: string) => { + calls++ + if (fail) throw new Error("boom") + return s === "" ? Option.none() : Option.some(s.length) + }), + (n) => n * 10 + ) + ) + assertTrue(matcher._tag === "TypeMatcher") + const [_case] = matcher.cases + + assertTrue(_case.guard("abc")) + strictEqual(_case.evaluate("abc"), 30) + assertFalse(_case.guard("")) + + // a throwing guard must not leave an earlier extraction behind + assertTrue(_case.guard("abc")) + fail = true + throws(() => _case.guard("abc")) + fail = false + strictEqual(_case.evaluate("abc"), 30) + strictEqual(calls, 5) + }) }) diff --git a/packages/effect/typetest/Match.tst.ts b/packages/effect/typetest/Match.tst.ts index 3a9f69fc45..6cc831e687 100644 --- a/packages/effect/typetest/Match.tst.ts +++ b/packages/effect/typetest/Match.tst.ts @@ -1,4 +1,4 @@ -import { Effect, Match, Option, pipe, type Result, Schema } from "effect" +import { Effect, type Filter, Match, Option, pipe, type Result, Schema } from "effect" import { describe, expect, it } from "tstyche" type Closed = { readonly _tag: "Closed" } @@ -14,6 +14,9 @@ declare const taggedInput: declare const discriminatedInput: | { readonly kind: "A"; readonly a: string } | { readonly kind: "B"; readonly b: number } +declare const text: string +declare const parseNumber: Filter.Filter +declare const parseUnknown: Filter.Filter declare const status: "draft" | "review" | "published" declare const renamedTransfer: { readonly _tag: "Transfer"; readonly renamedValue: "foo" } | null @@ -550,4 +553,63 @@ describe("Match", () => { }) ) }) + + it("whenFilter passes the filter's Pass type and keeps the remaining input", () => { + expect( + Match.value(text).pipe( + Match.whenFilter(parseNumber, (n) => { + expect(n).type.toBe() + return n + }), + Match.orElse((input) => { + expect(input).type.toBe() + return input + }) + ) + ).type.toBe() + + expect( + Match.type().pipe( + Match.whenFilter(parseNumber, (n) => n), + Match.option + ) + ).type.toBe<(u: string) => Option.Option>() + + expect( + Match.fn((_prefix: boolean, value: string) => value).pipe( + Match.whenFilter(parseNumber, (_n, prefix) => prefix), + Match.orElse((_value, prefix) => !prefix) + ) + ).type.toBe<(prefix: boolean, value: string) => boolean>() + + Match.type().pipe( + Match.withReturnType(), + // @ts-expect-error is not assignable to + Match.whenFilter(parseNumber, (n) => n) + ) + + // a filter can reject any input, so it never proves exhaustiveness + const incomplete = Match.type().pipe(Match.whenFilter(parseNumber, (n) => n)) + // @ts-expect-error Argument of type + Match.exhaustive(incomplete) + }) + + it("whenFilter keeps the matcher's remaining input for broader filters", () => { + Match.type().pipe( + Match.whenFilter(parseUnknown, (n) => n), + Match.orElse((input) => { + expect(input).type.toBe() + return input + }) + ) + + Match.type().pipe( + Match.when(Match.string, (s) => s), + Match.whenFilter(parseUnknown, (n) => n), + Match.orElse((input) => { + expect(input).type.toBe() + return input + }) + ) + }) }) From 1ee550e63119d630bfc5895183cf51ca1b051756 Mon Sep 17 00:00:00 2001 From: Lucas Duailibe Date: Thu, 29 Oct 2026 19:28:02 -0300 Subject: [PATCH 02/15] Follow OTEL_TRACES_SAMPLER in the OTLP tracer (#10108) Co-authored-by: Effect Bot Co-authored-by: Tim --- .changeset/otlp-tracer-sampler.md | 5 + packages/effect/src/observability/Otlp.ts | 24 +++- .../effect/src/observability/OtlpTracer.ts | 88 ++++++++++++- .../test/observability/OtlpTracer.test.ts | 121 ++++++++++++++++-- 4 files changed, 222 insertions(+), 16 deletions(-) create mode 100644 .changeset/otlp-tracer-sampler.md diff --git a/.changeset/otlp-tracer-sampler.md b/.changeset/otlp-tracer-sampler.md new file mode 100644 index 0000000000..e39e7da434 --- /dev/null +++ b/.changeset/otlp-tracer-sampler.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +Add trace sampling to the OTLP tracer. diff --git a/packages/effect/src/observability/Otlp.ts b/packages/effect/src/observability/Otlp.ts index 773cc23ad3..83505a9b8e 100644 --- a/packages/effect/src/observability/Otlp.ts +++ b/packages/effect/src/observability/Otlp.ts @@ -60,6 +60,13 @@ export const layer = (options: { readonly metricsExportInterval?: Duration.Input | undefined readonly metricsTemporality?: AggregationTemporality | undefined readonly tracerExportInterval?: Duration.Input | undefined + /** + * Passed to `OtlpTracer.layer` as `sampler`. + */ + readonly tracerSampler?: { + readonly ratio: number + readonly parentBased?: boolean | undefined + } | undefined readonly shutdownTimeout?: Duration.Input | undefined }): Layer.Layer => { const base = HttpClientRequest.get(options.baseUrl) @@ -93,7 +100,8 @@ export const layer = (options: { exportInterval: options.tracerExportInterval, maxBatchSize: options.maxBatchSize, context: options.tracerContext, - shutdownTimeout: options.shutdownTimeout + shutdownTimeout: options.shutdownTimeout, + sampler: options.tracerSampler }) ) } @@ -170,6 +178,13 @@ export const layerJson: (options: { readonly metricsExportInterval?: Duration.Input | undefined readonly metricsTemporality?: AggregationTemporality | undefined readonly tracerExportInterval?: Duration.Input | undefined + /** + * Passed to `OtlpTracer.layer` as `sampler`. + */ + readonly tracerSampler?: { + readonly ratio: number + readonly parentBased?: boolean | undefined + } | undefined readonly shutdownTimeout?: Duration.Input | undefined }) => Layer.Layer = flow( layer, @@ -205,6 +220,13 @@ export const layerProtobuf: (options: { readonly metricsExportInterval?: Duration.Input | undefined readonly metricsTemporality?: AggregationTemporality | undefined readonly tracerExportInterval?: Duration.Input | undefined + /** + * Passed to `OtlpTracer.layer` as `sampler`. + */ + readonly tracerSampler?: { + readonly ratio: number + readonly parentBased?: boolean | undefined + } | undefined readonly shutdownTimeout?: Duration.Input | undefined }) => Layer.Layer = flow( layer, diff --git a/packages/effect/src/observability/OtlpTracer.ts b/packages/effect/src/observability/OtlpTracer.ts index 3b2d5abed3..4b3b32d9e5 100644 --- a/packages/effect/src/observability/OtlpTracer.ts +++ b/packages/effect/src/observability/OtlpTracer.ts @@ -23,6 +23,7 @@ import type * as Headers from "../http/Headers.ts" import type * as HttpClient from "../http/HttpClient.ts" import * as Layer from "../Layer.ts" import * as Option from "../Option.ts" +import * as Schema from "../Schema.ts" import type * as Scope from "../Scope.ts" import * as Tracer from "../Tracer.ts" import type { ExtractTag } from "../Types.ts" @@ -64,6 +65,20 @@ export const make: ( readonly maxBatchSize?: number | undefined readonly context?: ((primitive: Tracer.EffectPrimitive, span: Tracer.AnySpan) => X) | undefined readonly shutdownTimeout?: Duration.Input | undefined + /** + * Keeps the share of traces given by `ratio`, from 0 to 1, decided from the + * trace ID. With `parentBased`, the default, a span with a parent follows + * the parent's sampled flag, even when created with `sampled: true`, and + * only root spans use `ratio`. + * + * The sampler only drops spans. A span Effect leaves unsampled, such as one + * below `MinimumTraceLevel`, is never exported. Without a sampler, every + * span Effect marks as sampled is exported. + */ + readonly sampler?: { + readonly ratio: number + readonly parentBased?: boolean | undefined + } | undefined } ) => Effect.Effect< Tracer.Tracer, @@ -104,9 +119,25 @@ export const make: ( exporter.push(makeOtlpSpan(span)) } + const sampler = options.sampler + const parentBased = sampler?.parentBased ?? true + const isSampled = sampler === undefined ? undefined : (span: SpanImpl): boolean => { + if (parentBased && Option.isSome(span.parent)) { + return span.parent.value.sampled + } + if (sampler.ratio >= 1) return true + if (sampler.ratio <= 0) return false + // Like the OpenTelemetry probability sampler, a trace is kept when the last + // 56 bits of its ID reach `(1 - ratio) * 2^56`, so every span of a trace + // gets the same decision. Only the top 52 of those bits are compared, which + // a double holds exactly. A trace ID without hex digits there is kept. + const randomness = Number(`0x${span.traceId.slice(-14, -1)}`) + return Number.isNaN(randomness) || randomness >= (1 - sampler.ratio) * 2 ** 52 + } + return Tracer.make({ span(options) { - return new SpanImpl(options, exportFn) + return new SpanImpl(options, exportFn, isSampled) }, context: options.context ? function(primitive, fiber) { @@ -143,6 +174,20 @@ export const layer: (options: { readonly maxBatchSize?: number | undefined readonly context?: ((primitive: Tracer.EffectPrimitive, span: Tracer.AnySpan) => X) | undefined readonly shutdownTimeout?: Duration.Input | undefined + /** + * Keeps the share of traces given by `ratio`, from 0 to 1, decided from the + * trace ID. With `parentBased`, the default, a span with a parent follows + * the parent's sampled flag, even when created with `sampled: true`, and + * only root spans use `ratio`. + * + * The sampler only drops spans. A span Effect leaves unsampled, such as one + * below `MinimumTraceLevel`, is never exported. Without a sampler, every + * span Effect marks as sampled is exported. + */ + readonly sampler?: { + readonly ratio: number + readonly parentBased?: boolean | undefined + } | undefined }) => Layer.Layer = flow( make, Layer.effect(Tracer.Tracer), @@ -159,6 +204,14 @@ export const layer: (options: { * `OTEL_EXPORTER_OTLP_COMPRESSION`, defaulting to "none". Gzip uses * HttpClientRequest's default minimum body size of 1KB. * + * `OTEL_TRACES_SAMPLER` accepts "always_on", "always_off", "traceidratio", + * "parentbased_always_on", "parentbased_always_off" and + * "parentbased_traceidratio", and sets the `sampler` option of `make`. The + * `traceidratio` samplers keep the share of traces set by + * `OTEL_TRACES_SAMPLER_ARG`, from 0 to 1, defaulting to 1. Other values, such + * as "jaeger_remote", fail the layer. When `OTEL_TRACES_SAMPLER` is unset, no + * sampler is used. + * * @stability unstable * @category layers * @since 4.0.0 @@ -190,7 +243,8 @@ export const layerFromConfig = (options?: { tracesTimeout, exportTimeout, scheduleDelay, - maxBatchSize + maxBatchSize, + samplerName } = yield* Config.all({ baseCompression: Config.option(Config.Literals(["gzip", "none"], "OTEL_EXPORTER_OTLP_COMPRESSION")), compression: Config.option(Config.Literals(["gzip", "none"], "OTEL_EXPORTER_OTLP_TRACES_COMPRESSION")), @@ -202,9 +256,29 @@ export const layerFromConfig = (options?: { Config.map(Duration.millis) ) ), - maxBatchSize: Config.option(Config.Int("OTEL_BSP_MAX_EXPORT_BATCH_SIZE")) + maxBatchSize: Config.option(Config.Int("OTEL_BSP_MAX_EXPORT_BATCH_SIZE")), + samplerName: Config.option(Config.Literals([ + "always_on", + "always_off", + "traceidratio", + "parentbased_always_on", + "parentbased_always_off", + "parentbased_traceidratio" + ], "OTEL_TRACES_SAMPLER")) }) + const sampler = Option.isNone(samplerName) ? undefined : { + ratio: samplerName.value.endsWith("traceidratio") + ? yield* Config.schema( + Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 })), + "OTEL_TRACES_SAMPLER_ARG" + ).pipe(Config.withDefault(1)) + : samplerName.value.endsWith("always_on") + ? 1 + : 0, + parentBased: samplerName.value.startsWith("parentbased_") + } + const shutdownTimeout = Option.firstSomeOf([tracesTimeout, baseTimeout, exportTimeout]).pipe( Option.map((_) => Duration.millis(_)) ) @@ -217,7 +291,8 @@ export const layerFromConfig = (options?: { exportInterval: Option.getOrUndefined(scheduleDelay), maxBatchSize: Option.getOrUndefined(maxBatchSize), context: options?.context, - shutdownTimeout: Option.getOrUndefined(shutdownTimeout) + shutdownTimeout: Option.getOrUndefined(shutdownTimeout), + sampler }) }).pipe(Effect.orDie, Layer.unwrap) @@ -249,15 +324,16 @@ class SpanImpl implements Tracer.Span { readonly kind: Tracer.SpanKind readonly sampled: boolean }, - exportFn: (span: SpanImpl) => void + exportFn: (span: SpanImpl) => void, + isSampled?: (span: SpanImpl) => boolean ) { this.name = options.name this.parent = options.parent this.annotations = options.annotations this.links = options.links this.kind = options.kind - this.sampled = options.sampled this.export = exportFn + this.sampled = options.sampled && (isSampled === undefined || isSampled(this)) this.status = { _tag: "Started", startTime: options.startTime diff --git a/packages/effect/test/observability/OtlpTracer.test.ts b/packages/effect/test/observability/OtlpTracer.test.ts index 0aaf10cf0a..cb0505bb7e 100644 --- a/packages/effect/test/observability/OtlpTracer.test.ts +++ b/packages/effect/test/observability/OtlpTracer.test.ts @@ -1,14 +1,24 @@ import { assert, describe, it } from "@effect/vitest" -import { Effect, Layer, Tracer } from "effect" +import { Cause, ConfigProvider, Effect, Exit, Layer, Tracer } from "effect" import { HttpClient, HttpClientResponse } from "effect/http" import type { HttpClientError } from "effect/http" import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/observability" import * as Version from "effect/Version" -const capture = () => { +const url = "http://localhost:4318/v1/traces" + +const tracerLayer = (sampler?: Parameters[0]["sampler"]) => + OtlpTracer.layer({ + url, + resource: { serviceName: "test", serviceVersion: "service-version" }, + exportInterval: "1 hour", + sampler + }) + +const capture = (tracer = tracerLayer()) => { const exports: Array<{ scope: { name: string; version: string } - spans: Array<{ traceId: string; links: Array<{ traceId: string }> }> + spans: Array<{ name: string; traceId: string; links: Array<{ traceId: string }> }> }> = [] const httpClient = HttpClient.makeWith( Effect.fnUntraced(function*(requestEffect) { @@ -20,17 +30,38 @@ const capture = () => { }), Effect.succeed as HttpClient.HttpClient.Preprocess ) - const layer = OtlpTracer.layer({ - url: "http://localhost:4318/v1/traces", - resource: { serviceName: "test", serviceVersion: "service-version" }, - exportInterval: "1 hour" - }).pipe( + const layer = tracer.pipe( Layer.provide(OtlpSerialization.layerJson), Layer.provide(Layer.succeed(HttpClient.HttpClient, httpClient)) ) - return { exports, layer } + const exportedNames = (): ReadonlyArray => exports.flatMap((_) => _.spans.map((span) => span.name)) + return { exports, exportedNames, layer } } +const layerFromEnv = (env: Record) => + OtlpTracer.layerFromConfig().pipe( + Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ + env: { + OTEL_SERVICE_NAME: "test", + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: url, + OTEL_TRACES_EXPORTER: "otlp", + OTEL_BSP_SCHEDULE_DELAY: "3600000", + ...env + } + }))) + ) + +// Ends a root span with a local child, a span continued from a sampled remote +// parent, and a span forced to be sampled under an unsampled remote parent. +const emitSpans = Effect.gen(function*() { + const parent = Tracer.externalSpan({ traceId: "0af7651916cd43dd8448eb211c80319c", spanId: "b7ad6b7169203331" }) + const unsampled = Tracer.externalSpan({ ...parent, sampled: false }) + yield* Effect.void.pipe(Effect.withSpan("local"), Effect.withSpan("root")) + yield* Effect.void.pipe(Effect.withSpan("remote", { parent })) + yield* Effect.void.pipe(Effect.withSpan("forced", { parent: unsampled, sampled: true })) + yield* (yield* OtlpExporter.Flusher).flush +}) + describe("OtlpTracer", () => { it.effect("uses effect as the instrumentation scope, not the service name", () => { const { exports, layer } = capture() @@ -51,4 +82,76 @@ describe("OtlpTracer", () => { assert.strictEqual(exports[0].spans[0].links[0].traceId, "0000000000000000463ac35c9f6413ad") }).pipe(Effect.provide(layer)) }) + + describe("sampler", () => { + it.effect("samples by the last 56 bits of the trace ID", () => { + const { exportedNames, layer } = capture(tracerLayer({ ratio: 0.5, parentBased: false })) + return Effect.gen(function*() { + for ( + const [name, traceId] of [ + ["below", "ffffffffffffffffff7fffffffffffff"], + ["at", "00000000000000000080000000000000"] + ] + ) { + const parent = Tracer.externalSpan({ traceId, spanId: "0000000000000001" }) + yield* Effect.void.pipe(Effect.withSpan(name, { parent })) + } + yield* (yield* OtlpExporter.Flusher).flush + assert.deepStrictEqual(exportedNames(), ["at"]) + }).pipe(Effect.provide(layer)) + }) + + it.effect("keeps trace IDs that are not hex unless the ratio is 0", () => + Effect.gen(function*() { + const parent = Tracer.externalSpan({ traceId: "trace-456", spanId: "0000000000000001" }) + for (const [ratio, expected] of [[0.5, ["span"]], [0, []]] as const) { + const { exportedNames, layer } = capture(tracerLayer({ ratio, parentBased: false })) + yield* Effect.gen(function*() { + yield* Effect.void.pipe(Effect.withSpan("span", { parent })) + yield* (yield* OtlpExporter.Flusher).flush + }).pipe(Effect.provide(layer)) + assert.deepStrictEqual(exportedNames(), expected, `ratio ${ratio}`) + } + })) + + it.effect("keeps the parent's decision by default", () => { + const { exportedNames, layer } = capture(tracerLayer({ ratio: 0 })) + return Effect.gen(function*() { + yield* emitSpans + assert.deepStrictEqual(exportedNames(), ["remote"]) + }).pipe(Effect.provide(layer)) + }) + + it.effect("follows OTEL_TRACES_SAMPLER and OTEL_TRACES_SAMPLER_ARG", () => + Effect.gen(function*() { + for ( + const [env, expected] of [ + [{}, ["local", "root", "remote", "forced"]], + [{ OTEL_TRACES_SAMPLER: "parentbased_always_on" }, ["local", "root", "remote"]], + [{ OTEL_TRACES_SAMPLER: "always_off" }, []], + [{ OTEL_TRACES_SAMPLER: "traceidratio", OTEL_TRACES_SAMPLER_ARG: "0" }, []], + [{ OTEL_TRACES_SAMPLER: "parentbased_always_off" }, ["remote"]], + [{ OTEL_TRACES_SAMPLER: "parentbased_traceidratio", OTEL_TRACES_SAMPLER_ARG: "0" }, ["remote"]] + ] as const + ) { + const { exportedNames, layer } = capture(layerFromEnv(env)) + yield* Effect.provide(emitSpans, layer) + assert.deepStrictEqual(exportedNames(), expected, JSON.stringify(env)) + } + })) + + it.effect("fails on an unsupported OTEL_TRACES_SAMPLER or OTEL_TRACES_SAMPLER_ARG", () => + Effect.gen(function*() { + for ( + const [variable, env] of [ + ["OTEL_TRACES_SAMPLER", { OTEL_TRACES_SAMPLER: "jaeger_remote" }], + ["OTEL_TRACES_SAMPLER_ARG", { OTEL_TRACES_SAMPLER: "traceidratio", OTEL_TRACES_SAMPLER_ARG: "1.5" }] + ] as const + ) { + const exit = yield* Effect.exit(Layer.build(capture(layerFromEnv(env)).layer)) + assert(Exit.isFailure(exit)) + assert.include(Cause.pretty(exit.cause), `at ["${variable}"]`) + } + })) + }) }) From 6d1dd5c61b540ca8d3e878b05e19f0077f0f11ef Mon Sep 17 00:00:00 2001 From: Gourav Kumar Dhiman Date: Fri, 30 Oct 2026 04:11:39 +0530 Subject: [PATCH 03/15] fix(ai-anthropic): read message batch results instead of failing on 200 (#10130) Co-authored-by: Claude Opus 5.5 Co-authored-by: Effect Bot Co-authored-by: Tim --- .changeset/anthropic-batch-results-jsonl.md | 5 + packages/ai/anthropic/codegen.yml | 4 + packages/ai/anthropic/src/Generated.ts | 116 +++++++++++++++++++- 3 files changed, 121 insertions(+), 4 deletions(-) create mode 100644 .changeset/anthropic-batch-results-jsonl.md diff --git a/.changeset/anthropic-batch-results-jsonl.md b/.changeset/anthropic-batch-results-jsonl.md new file mode 100644 index 0000000000..28653a9dc1 --- /dev/null +++ b/.changeset/anthropic-batch-results-jsonl.md @@ -0,0 +1,5 @@ +--- +"@effect/ai-anthropic": minor +--- + +Fix `messageBatchesResults` and `betaMessageBatchesResults` failing on successful JSON Lines responses. They now return the raw bytes, new `*Stream` variants stream them, and each line decodes with `MessageBatchIndividualResponse` or `BetaMessageBatchIndividualResponse`. diff --git a/packages/ai/anthropic/codegen.yml b/packages/ai/anthropic/codegen.yml index b17859ff5c..5aaa4861a4 100644 --- a/packages/ai/anthropic/codegen.yml +++ b/packages/ai/anthropic/codegen.yml @@ -34,6 +34,8 @@ patches: - '[{"op":"replace","path":"/components/schemas/ResponseTextBlock/required","value":["text","type"]},{"op":"replace","path":"/components/schemas/BetaResponseTextBlock/required","value":["text","type"]},{"op":"replace","path":"/components/schemas/ResponseDocumentBlock/required","value":["source","title","type"]},{"op":"replace","path":"/components/schemas/BetaResponseDocumentBlock/required","value":["source","title","type"]}]' # Make model optional in BetaMessageIterationUsage (gateways and older responses may omit it) - '[{"op":"replace","path":"/components/schemas/BetaMessageIterationUsage/required","value":["cache_creation","cache_creation_input_tokens","cache_read_input_tokens","input_tokens","output_tokens","type"]}]' + # Read JSON Lines batch results as bytes; the generator cannot decode application/x-jsonl (#10107) + - '[{"op":"replace","path":"/paths/~1v1~1messages~1batches~1{message_batch_id}~1results/get/responses/200/content/application~1x-jsonl/schema","value":{"type":"string","format":"binary"}},{"op":"replace","path":"/paths/~1v1~1messages~1batches~1{message_batch_id}~1results?beta=true/get/responses/200/content/application~1x-jsonl/schema","value":{"type":"string","format":"binary"}}]' # Decode every error envelope and let the status code decide the error, as released. collapseErrorResponses: true # Released schemas that no operation references: stream events, batch results, memory tool @@ -65,6 +67,8 @@ includeSchemas: - ErroredResult - ExpiredResult - SucceededResult + - BetaMessageBatchIndividualResponse + - MessageBatchIndividualResponse - BetaMemoryTool_20250818_CreateCommand - BetaMemoryTool_20250818_DeleteCommand - BetaMemoryTool_20250818_InsertCommand diff --git a/packages/ai/anthropic/src/Generated.ts b/packages/ai/anthropic/src/Generated.ts index a1ee54a89f..5e71fd2d3e 100644 --- a/packages/ai/anthropic/src/Generated.ts +++ b/packages/ai/anthropic/src/Generated.ts @@ -15651,6 +15651,26 @@ export const SucceededResult = Schema.Struct({ "message": Message, "type": Schema.Literal("succeeded").annotate({ "title": "Type", "default": "succeeded" }) }).annotate({ "title": "SucceededResult", "identifier": "SucceededResult" }) +export type MessageBatchIndividualResponse = { + readonly "custom_id": string + readonly "result": SucceededResult | ErroredResult | CanceledResult | ExpiredResult +} +export const MessageBatchIndividualResponse = Schema.Struct({ + "custom_id": Schema.String.annotate({ + "title": "Custom Id", + "description": + "Developer-provided ID created for each request in a Message Batch. Useful for matching results to requests, as results may be given out of request order.\n\nMust be unique for each request within the Message Batch." + }), + "result": Schema.Union([SucceededResult, ErroredResult, CanceledResult, ExpiredResult], { mode: "oneOf" }).annotate({ + "title": "Result", + "description": + "Processing result for this request.\n\nContains a Message output if processing was successful, an error response if processing failed, or the reason why processing was not attempted, such as cancellation or expiration." + }) +}).annotate({ + "title": "MessageBatchIndividualResponse", + "description": "This is a single line in the response `.jsonl` file and does not represent the response as a whole.", + "identifier": "MessageBatchIndividualResponse" +}) export type BetaRequestToolAdditionBlock = { readonly "cache_control"?: BetaCacheControlEphemeral | null readonly "tool": @@ -16728,6 +16748,31 @@ export const BetaSucceededResult = Schema.Struct({ "message": BetaMessage, "type": Schema.Literal("succeeded").annotate({ "title": "Type", "default": "succeeded" }) }).annotate({ "title": "SucceededResult", "identifier": "BetaSucceededResult" }) +export type BetaMessageBatchIndividualResponse = { + readonly "custom_id": string + readonly "result": BetaSucceededResult | BetaErroredResult | BetaCanceledResult | BetaExpiredResult +} +export const BetaMessageBatchIndividualResponse = Schema.Struct({ + "custom_id": Schema.String.annotate({ + "title": "Custom Id", + "description": + "Developer-provided ID created for each request in a Message Batch. Useful for matching results to requests, as results may be given out of request order.\n\nMust be unique for each request within the Message Batch." + }), + "result": Schema.Union([ + BetaSucceededResult, + BetaErroredResult, + BetaCanceledResult, + BetaExpiredResult + ], { mode: "oneOf" }).annotate({ + "title": "Result", + "description": + "Processing result for this request.\n\nContains a Message output if processing was successful, an error response if processing failed, or the reason why processing was not attempted, such as cancellation or expiration." + }) +}).annotate({ + "title": "MessageBatchIndividualResponse", + "description": "This is a single line in the response `.jsonl` file and does not represent the response as a whole.", + "identifier": "BetaMessageBatchIndividualResponse" +}) export type BetaMessageBatchIndividualRequestParams = { readonly "custom_id": string readonly "params": BetaCreateMessageParams @@ -18666,12 +18711,32 @@ export const make = ( "anthropic-workspace-id": options?.params?.["anthropic-workspace-id"] ?? undefined }), withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeBinary, "4xx": decodeError("MessageBatchesResults4XX", MessageBatchesResults4XX), orElse: unexpectedStatus })) ) ) ), + "messageBatchesResultsStream": (messageBatchId, options) => + Stream.unwrap( + __makePathRequest( + HttpClientRequest.get, + [messageBatchId], + () => "/v1/messages/batches/" + __encodePathParam(messageBatchId) + "/results" + ).pipe( + Effect.map((request) => + request.pipe( + HttpClientRequest.setHeaders({ + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined, + "anthropic-workspace-id": options?.params?.["anthropic-workspace-id"] ?? undefined + }), + binaryRequest + ) + ) + ) + ), "messagesCountTokensPost": (options: Parameters[0]) => HttpClientRequest.post("/v1/messages/count_tokens").pipe( HttpClientRequest.setHeaders({ @@ -19154,12 +19219,33 @@ export const make = ( "anthropic-workspace-id": options?.params?.["anthropic-workspace-id"] ?? undefined }), withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeBinary, "4xx": decodeError("BetaMessageBatchesResults4XX", BetaMessageBatchesResults4XX), orElse: unexpectedStatus })) ) ) ), + "betaMessageBatchesResultsStream": (messageBatchId, options) => + Stream.unwrap( + __makePathRequest( + HttpClientRequest.get, + [messageBatchId], + () => "/v1/messages/batches/" + __encodePathParam(messageBatchId) + "/results?beta=true" + ).pipe( + Effect.map((request) => + request.pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined, + "anthropic-workspace-id": options?.params?.["anthropic-workspace-id"] ?? undefined + }), + binaryRequest + ) + ) + ) + ), "betaMessagesCountTokensPost": (options: Parameters[0]) => HttpClientRequest.post("/v1/messages/count_tokens?beta=true").pipe( HttpClientRequest.setHeaders({ @@ -19821,7 +19907,7 @@ export interface AnthropicClient { messageBatchId: string, options: { readonly params?: typeof MessageBatchesResultsParams.Encoded | undefined; readonly config: Config } ): Effect.Effect< - WithOptionalResponse, + WithOptionalResponse, | HttpClientError.HttpClientError | SchemaError | AnthropicClientError<"MessageBatchesResults4XX", MessageBatchesResults4XX> @@ -19833,12 +19919,23 @@ export interface AnthropicClient { readonly config?: Config | undefined } | undefined ): Effect.Effect< - WithOptionalResponse, + WithOptionalResponse, | HttpClientError.HttpClientError | SchemaError | AnthropicClientError<"MessageBatchesResults4XX", MessageBatchesResults4XX> > } + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request in the Message Batch. Results are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + */ + readonly "messageBatchesResultsStream": ( + messageBatchId: string, + options: { readonly params?: typeof MessageBatchesResultsParams.Encoded | undefined } | undefined + ) => Stream.Stream /** * Count the number of tokens in a Message. * @@ -20513,7 +20610,7 @@ export interface AnthropicClient { messageBatchId: string, options: { readonly params?: typeof BetaMessageBatchesResultsParams.Encoded | undefined; readonly config: Config } ): Effect.Effect< - WithOptionalResponse, + WithOptionalResponse, | HttpClientError.HttpClientError | SchemaError | AnthropicClientError<"BetaMessageBatchesResults4XX", BetaMessageBatchesResults4XX> @@ -20525,12 +20622,23 @@ export interface AnthropicClient { readonly config?: Config | undefined } | undefined ): Effect.Effect< - WithOptionalResponse, + WithOptionalResponse, | HttpClientError.HttpClientError | SchemaError | AnthropicClientError<"BetaMessageBatchesResults4XX", BetaMessageBatchesResults4XX> > } + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request in the Message Batch. Results are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + */ + readonly "betaMessageBatchesResultsStream": ( + messageBatchId: string, + options: { readonly params?: typeof BetaMessageBatchesResultsParams.Encoded | undefined } | undefined + ) => Stream.Stream /** * Count the number of tokens in a Message. * From 83e1e609ccbb7e5ec9c0ed30a8f1a30646010fc3 Mon Sep 17 00:00:00 2001 From: digicoder Date: Thu, 29 Oct 2026 19:00:29 -0400 Subject: [PATCH 04/15] Map declared toolkit failures to MCP input_required results (#10090) Co-authored-by: creatifcoding Co-authored-by: Effect Bot --- .changeset/mcp-toolkit-input-required.md | 5 + packages/effect/MCP.md | 79 ++++++++++++++ packages/effect/src/ai/McpServer.ts | 38 +++++-- .../ai/McpServer/ProtocolAdapters.test.ts | 100 +++++++++++++++++- packages/effect/typetest/ai/McpServer.tst.ts | 11 ++ 5 files changed, 220 insertions(+), 13 deletions(-) create mode 100644 .changeset/mcp-toolkit-input-required.md diff --git a/.changeset/mcp-toolkit-input-required.md b/.changeset/mcp-toolkit-input-required.md new file mode 100644 index 0000000000..22b710c314 --- /dev/null +++ b/.changeset/mcp-toolkit-input-required.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +`McpServer.toolkit` and `McpServer.registerToolkit` return a declared `McpSchema.InputRequired` failure as an `input_required` result, so toolkit tools can request client input. diff --git a/packages/effect/MCP.md b/packages/effect/MCP.md index ccfc75e618..f863ade80c 100644 --- a/packages/effect/MCP.md +++ b/packages/effect/MCP.md @@ -463,6 +463,85 @@ against the defined schema, ensuring that only `"yes"` or `"no"` responses are a declines to answer or the elicitation fails, a fallback value is provided—here, the default answer is `"no"`. +## Multi round-trip tool results + +Under `v2026_07_28` the server has no session for sending requests back to the client, so +`McpServer.elicit` is not available. Instead, a tool returns an `input_required` result that lists +the input it needs and an opaque `requestState`. The client collects the input and retries the +same call with `inputResponses` and the unchanged `requestState`. + +A handler registered with `McpServer.addTool` returns `McpSchema.InputRequired` directly. A toolkit +tool declares `McpSchema.InputRequired` as a failure and fails with it: + +```typescript +import { Effect, Layer, Schema } from "effect" +import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai" + +const ArchiveNote = Tool.make("ArchiveNote", { + parameters: Schema.Struct({ noteId: Schema.String }), + success: Schema.Struct({ archived: Schema.String }), + failure: Schema.instanceOf(McpSchema.InputRequired), + dependencies: [McpSchema.McpRequestContext] +}) + +const NotesToolkit = Toolkit.make(ArchiveNote) + +// For example an HMAC from `effect/crypto/Mac`, with a key shared by every server instance. +declare const signState: (noteId: string) => Effect.Effect +declare const verifyState: (state: string, noteId: string) => Effect.Effect +declare const archiveNote: (noteId: string) => Effect.Effect + +const isAccepted = Schema.is(McpSchema.ElicitAcceptResult) + +const NotesLayer = McpServer.toolkit(NotesToolkit).pipe( + Layer.provide(NotesToolkit.toLayer({ + ArchiveNote: Effect.fnUntraced(function*({ noteId }) { + const request = yield* McpSchema.McpRequestContext + const verified = request.requestState !== undefined && + (yield* verifyState(request.requestState, noteId)) + const answer = request.inputResponses?.confirm + const confirmed = isAccepted(answer) && answer.content?.confirmed === true + if (!verified || !confirmed) { + return yield* Effect.fail( + new McpSchema.InputRequired({ + inputRequests: { + confirm: { + method: "elicitation/create", + params: { + message: `Archive note ${noteId}?`, + requestedSchema: { + type: "object", + properties: { confirmed: { type: "boolean" } }, + required: ["confirmed"] + } + } + } + }, + requestState: yield* signState(noteId) + }) + ) + } + yield* archiveNote(noteId) + return { archived: noteId } + }) + })) +) +``` + +The first call fails with `InputRequired`, which the client receives as an `input_required` +result. On the retry, the handler reads the answer and the state from `McpRequestContext`. + +- `InputRequired` is not an error class, so fail with `Effect.fail(new McpSchema.InputRequired(...))`. + It can also be one member of a union failure schema. For a tool you do not own, widen its failure + with `tool.setFailure(Schema.Union([...]))` before building the toolkit. +- Protocols before `v2026_07_28` reject the result with an `InvalidParams` error ("Client input is + not supported by this MCP protocol"), as they do for `addTool`. +- The client must declare the capability each input request needs, such as `elicitation`. + Otherwise the call fails with error `-32021` and HTTP status 400. +- `requestState` passes through the client and the retry may reach another instance, so sign it with + a shared key, bind it to the call's arguments and verify it before acting. A client can repeat a + retry, so make the side effect idempotent. + ## Complete Working Example Here's a complete, copy/pastable MCP server example that combines all the concepts: diff --git a/packages/effect/src/ai/McpServer.ts b/packages/effect/src/ai/McpServer.ts index 26805d0d58..430c9ddf66 100644 --- a/packages/effect/src/ai/McpServer.ts +++ b/packages/effect/src/ai/McpServer.ts @@ -3226,6 +3226,10 @@ type RegistrationRequirements = * The MCP middleware in the current context, provided with * `Effect.provide(middleware.layer)`, runs around every call to the toolkit. * + * A handler that fails with a declared `McpSchema.InputRequired` asks the + * client for input with an `input_required` result. Protocols without client + * input reject it, as they do for `addTool`. + * * @see {@link ToolkitRequirements} for which services are request-level * * @stability unstable @@ -3309,7 +3313,13 @@ export const registerToolkit: >( structuredContent, content: toolResultContent(structuredContent) }) - const handleCause = (cause: Cause.Cause) => { + const handleCause = ( + cause: Cause.Cause + ): Effect.Effect< + CallToolResult | McpSchema.InputRequired, + InvalidParams, + Tool.HandlerServices + > => { const failure = Cause.findFail(cause) if (Result.isSuccess(failure)) { const error = failure.success.error @@ -3318,7 +3328,9 @@ export const registerToolkit: >( return Effect.fail(new InvalidParams({ message: error.reason.message })) } if (origin === "handler" && isDeclaredFailure(error)) { - return Effect.catchCause(declaredFailureResult(error), internalToolError) + return isInputRequired(error) + ? Effect.succeed(error) + : Effect.catchCause(declaredFailureResult(error), internalToolError) } } return internalToolError(cause) @@ -3365,7 +3377,7 @@ export const registerToolkit: >( Stream.runLast, Effect.flatMap(Effect.fromOption), Effect.flatMap((result): Effect.Effect< - CallToolResult, + CallToolResult | McpSchema.InputRequired, unknown, Tool.HandlerServices > => { @@ -3378,16 +3390,20 @@ export const registerToolkit: >( : successResult(result.encodedResult) ) } - // Declared failures return their encoded payload; anything else is classified by origin. - return result.failureOrigin === "handler" - ? Effect.succeed(failureResult(result.encodedResult)) - : Effect.failCause(Cause.annotate( + // Declared failures return their encoded payload, or request client input; + // anything else is classified by origin. + if (result.failureOrigin !== "handler") { + return Effect.failCause(Cause.annotate( Cause.fail(result.result), Context.make(Toolkit.FailureOrigin, result.failureOrigin ?? "result") )) + } + return isDeclaredFailure(result.result) && isInputRequired(result.result) + ? Effect.succeed(result.result) + : Effect.succeed(failureResult(result.encodedResult)) }), Effect.catchCause(handleCause) - ) as Effect.Effect + ) as Effect.Effect }, services }) @@ -3402,6 +3418,8 @@ const isParameterValidationError = ( ): error is AiError.AiError & { readonly reason: AiError.ToolParameterValidationError } => AiError.isAiError(error) && error.reason._tag === "ToolParameterValidationError" +const isInputRequired = (u: unknown): u is McpSchema.InputRequired => Predicate.isTagged(u, "InputRequired") + // MCP requires an object root. A non-recursive root is compiled inline rather // than as a definition; a recursive root keeps its definition and the top-level // `$ref` is inlined. @@ -3426,6 +3444,10 @@ const toolJsonSchema = (schema: Schema.Constraint, strict: boolean): JsonSchema. * The layer requires `McpServer`. Pass it to a transport through the * `registrations` option, or provide the transport layer to it. * + * A handler that fails with a declared `McpSchema.InputRequired` asks the + * client for input with an `input_required` result. Protocols without client + * input reject it, as they do for `addTool`. + * * @see {@link ToolkitRequirements} for which services are request-level * * @stability unstable diff --git a/packages/effect/test/ai/McpServer/ProtocolAdapters.test.ts b/packages/effect/test/ai/McpServer/ProtocolAdapters.test.ts index 609c1295b6..f8265f135b 100644 --- a/packages/effect/test/ai/McpServer/ProtocolAdapters.test.ts +++ b/packages/effect/test/ai/McpServer/ProtocolAdapters.test.ts @@ -94,6 +94,29 @@ const CapabilityGatedTool = Tool.make("capability-gated", { client.capabilities.roots !== undefined ) +class RootsUnavailable extends Schema.TaggedError()("RootsUnavailable", {}) {} + +const InputRequiredTool = Tool.make("input-required", { + parameters: Tool.EmptyParams, + success: Schema.String, + failure: Schema.instanceOf(McpSchema.InputRequired), + dependencies: [McpSchema.McpRequestContext] +}) + +const InputRequiredReturnTool = Tool.make("input-required-return", { + parameters: Tool.EmptyParams, + success: Schema.String, + failure: Schema.Union([Schema.instanceOf(McpSchema.InputRequired), RootsUnavailable]), + failureMode: "return", + dependencies: [McpSchema.McpRequestContext] +}) + +// Declares no failures, so a value shaped like InputRequired only encodes through the built-in ExecutionFailure. +const UndeclaredInputRequiredTool = Tool.make("undeclared-input-required", { + parameters: Tool.EmptyParams, + failureMode: "return" +}) + const TestToolkit = Toolkit.make( SharedTool, JsonArrayTool, @@ -104,7 +127,10 @@ const TestToolkit = Toolkit.make( CapabilityTool, InitializeMetadataTool, LogLevelTool, - CapabilityGatedTool + CapabilityGatedTool, + InputRequiredTool, + InputRequiredReturnTool, + UndeclaredInputRequiredTool ) const FamilyResource = McpServer.resource({ @@ -173,6 +199,14 @@ const MrtrTool = new McpSchema.Tool({ inputSchema: { type: "object" } }) +// Requests the client's roots on the first call and completes once the retry carries them. +const requestRoots = () => + McpSchema.McpRequestContext.use((request) => + request.inputResponses?.roots === undefined + ? Effect.fail(new McpSchema.InputRequired({ inputRequests: { roots: { method: "roots/list" } } })) + : Effect.succeed("resumed") + ) + interface TestState { sharedInvocations: number structuredInvocations: number @@ -213,7 +247,17 @@ const makeFixture = Effect.fnUntraced(function*( "initialize-metadata": () => McpSchema.McpRequestContext.useSync((context) => JSON.stringify(context.requestMetadata)), "log-level": () => CurrentLogLevel, - "capability-gated": () => Effect.succeed("visible") + "capability-gated": () => Effect.succeed("visible"), + "input-required": requestRoots, + "input-required-return": requestRoots, + // Untyped handlers can still fail with a value the tool does not declare. + "undeclared-input-required": () => + Effect.fail({ + _tag: "InputRequired", + type: "execution-denied", + reason: "denied", + requestState: "state" + }) as Effect.Effect }))) ) const mrtrToolLayer = Layer.effectDiscard( @@ -1152,9 +1196,55 @@ describe("McpServer protocol adapters", () => { Effect.gen(function*() { const fixture = yield* makeFixture() const legacy = yield* initialize(fixture.post, "2025-11-25") - const legacyError = errorOf(yield* legacy.request("tools/call", { name: MrtrTool.name, arguments: {} })) - assert.strictEqual(legacyError.code, McpSchema.INVALID_PARAMS_ERROR_CODE) - assert.match(legacyError.message, /Client input is not supported/) + for (const name of [MrtrTool.name, "input-required", "input-required-return"]) { + const legacyError = errorOf(yield* legacy.request("tools/call", { name, arguments: {} })) + assert.strictEqual(legacyError.code, McpSchema.INVALID_PARAMS_ERROR_CODE, name) + assert.match(legacyError.message, /Client input is not supported/, name) + } + })) + + it.effect("should request input and resume when a toolkit handler fails with InputRequired", () => + Effect.gen(function*() { + const fixture = yield* makeFixture() + const call = (name: string, params: Record = {}) => + fixture.post( + modernRequest(50, "tools/call", { name, arguments: {}, ...params }, modernMetadata({ roots: {} })), + { ...modernHeaders("tools/call"), "Mcp-Name": name } + ).pipe(Effect.flatMap(readJsonRpcResponse), Effect.map(resultOf)) + for (const name of ["input-required", "input-required-return"]) { + const pending = yield* call(name) + assert.strictEqual(pending.resultType, "input_required", name) + assert.deepStrictEqual(pending.inputRequests, { roots: { method: "roots/list" } }, name) + + const resumed = yield* call(name, { inputResponses: { roots: { roots: [] } } }) + assert.strictEqual(resumed.resultType, "complete", name) + assert.strictEqual(resumed.structuredContent, "resumed", name) + } + })) + + it.effect("should reject a toolkit input request when the client omits its capability", () => + Effect.gen(function*() { + const fixture = yield* makeFixture() + const response = yield* fixture.post( + modernRequest(51, "tools/call", { name: "input-required", arguments: {} }), + { ...modernHeaders("tools/call"), "Mcp-Name": "input-required" } + ) + + assert.strictEqual(response.status, 400) + assert.strictEqual(errorOf(yield* readJsonRpcResponse(response)).code, -32021) + })) + + it.effect("should keep an undeclared InputRequired-tagged failure as an error result", () => + Effect.gen(function*() { + const fixture = yield* makeFixture() + const response = yield* fixture.post( + modernRequest(52, "tools/call", { name: "undeclared-input-required", arguments: {} }), + { ...modernHeaders("tools/call"), "Mcp-Name": "undeclared-input-required" } + ) + const result = resultOf(yield* readJsonRpcResponse(response)) + + assert.strictEqual(result.resultType, "complete") + assert.strictEqual(result.isError, true) })) it.effect("should reject prompt content when the negotiated schema cannot represent it", () => diff --git a/packages/effect/typetest/ai/McpServer.tst.ts b/packages/effect/typetest/ai/McpServer.tst.ts index 24e9d9e855..6379f97fbb 100644 --- a/packages/effect/typetest/ai/McpServer.tst.ts +++ b/packages/effect/typetest/ai/McpServer.tst.ts @@ -209,6 +209,17 @@ describe("McpServer", () => { >() }) + it("should accept InputRequired as a declared toolkit failure", () => { + const toolkit = Toolkit.make(Tool.make("Confirm", { failure: Schema.instanceOf(McpSchema.InputRequired) })) + const layer = McpServer.toolkit(toolkit).pipe( + Layer.provide(toolkit.toLayer({ + Confirm: () => Effect.fail(new McpSchema.InputRequired({ requestState: "state" })) + })) + ) + + expect>().type.toBe() + }) + describe("resource templates", () => { class Lookup extends Context.Service }>()("Lookup") {} class IdCodec extends Context.Service()("IdCodec") {} From 8f830d0392efbadf078723719b134a44eb2b4174 Mon Sep 17 00:00:00 2001 From: effect-bot <129879685+effect-bot@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:41:11 +1300 Subject: [PATCH 05/15] Support TOML 1.1 syntax in Toml.parse (#10184) --- .changeset/toml-1-1-syntax.md | 5 ++ packages/effect/src/encoding/Toml.ts | 65 ++++++++++------------ packages/effect/test/encoding/Toml.test.ts | 34 +++++++++++ 3 files changed, 67 insertions(+), 37 deletions(-) create mode 100644 .changeset/toml-1-1-syntax.md diff --git a/.changeset/toml-1-1-syntax.md b/.changeset/toml-1-1-syntax.md new file mode 100644 index 0000000000..cc7b51278f --- /dev/null +++ b/.changeset/toml-1-1-syntax.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +Support TOML 1.1 syntax in `Toml.parse`: multiline inline tables with comments and trailing commas, the `\e` and `\xHH` escapes, and times without seconds. Times without seconds are normalized to `:00`, so `13:37` parses as `"13:37:00"`. diff --git a/packages/effect/src/encoding/Toml.ts b/packages/effect/src/encoding/Toml.ts index 7b4b39c058..311df08520 100644 --- a/packages/effect/src/encoding/Toml.ts +++ b/packages/effect/src/encoding/Toml.ts @@ -1,15 +1,15 @@ /** * Parses TOML configuration files. * - * The implementation covers the TOML values and table forms used by Effect's - * configuration-file CLI primitive while avoiding a generated parser runtime. + * The implementation follows the TOML 1.1 specification, which is a superset + * of TOML 1.0, while avoiding a generated parser runtime. * * @stability unstable * @since 4.0.0 */ /* - * The behavior is based on `toml` 4.1.2. + * The behavior is based on `toml` 4.1.2, extended to TOML 1.1. * * Copyright (c) 2012 Michelle Tilley * @@ -42,9 +42,9 @@ const makeTable = (): Table => Object.create(null) const isTable = (value: unknown): value is Table => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date) const localDatePattern = /^(\d{4})-(\d{2})-(\d{2})$/ -const localTimePattern = /^(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?$/ +const localTimePattern = /^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?$/ const numericOffsetPattern = /^[+-](\d{2}):(\d{2})$/ -const dateTimePattern = /^(\d{4}-\d{2}-\d{2})[Tt](\d{2}:\d{2}:\d{2}(?:\.\d+)?)([Zz]|[+-]\d{2}:\d{2})?$/ +const dateTimePattern = /^(\d{4}-\d{2}-\d{2})[Tt](\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)([Zz]|[+-]\d{2}:\d{2})?$/ const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] const isValidDate = (date: string): boolean => { const [, year, month, day] = localDatePattern.exec(date)!.map(Number) @@ -52,6 +52,8 @@ const isValidDate = (date: string): boolean => { const days = month === 2 && leap ? 29 : daysInMonth[month - 1] return month >= 1 && month <= 12 && day >= 1 && day <= days } +// TOML 1.1 allows omitting seconds; `:00` is assumed +const withSeconds = (time: string): string => time.length === 5 ? `${time}:00` : time const isValidTime = (time: string): boolean => { const [, hour, minute, second] = localTimePattern.exec(time)!.map(Number) return hour <= 23 && minute <= 59 && second <= 60 @@ -80,7 +82,7 @@ class TomlParser { parse(): Table { while (true) { - this.skipDocumentWhitespace() + this.skipWhitespace() if (this.done) { return this.root } @@ -235,7 +237,7 @@ class TomlParser { return table } - const spaceSeparatedDateTime = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})?)/ + const spaceSeparatedDateTime = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:[Zz]|[+-]\d{2}:\d{2})?)/ .exec(this.input.slice(this.index)) if (spaceSeparatedDateTime !== null) { this.advance(spaceSeparatedDateTime[0].length) @@ -266,7 +268,8 @@ class TomlParser { private parseDate(token: string): Date | string | undefined { const dateTime = dateTimePattern.exec(token) if (dateTime !== null) { - const [, date, time, offset] = dateTime + const [, date, rawTime, offset] = dateTime + const time = withSeconds(rawTime) // `Date` cannot represent a leap second, so offset date-times reject `:60` const offsetValid = offset === undefined || (isValidOffset(offset) && time.slice(6, 8) !== "60") if (!isValidDate(date) || !isValidTime(time) || !offsetValid) { @@ -278,7 +281,8 @@ class TomlParser { return isValidDate(token) ? token : this.fail(`Invalid date-time '${token}'`) } if (localTimePattern.test(token)) { - return isValidTime(token) ? token : this.fail(`Invalid date-time '${token}'`) + const time = withSeconds(token) + return isValidTime(time) ? time : this.fail(`Invalid date-time '${token}'`) } return undefined } @@ -356,13 +360,14 @@ class TomlParser { n: "\n", f: "\f", r: "\r", + e: "\u001B", "\"": "\"", "\\": "\\" } if (hasOwn.call(escapes, escape)) { output += escapes[escape] - } else if (escape === "u" || escape === "U") { - const length = escape === "u" ? 4 : 8 + } else if (escape === "x" || escape === "u" || escape === "U") { + const length = escape === "x" ? 2 : escape === "u" ? 4 : 8 const hex = this.input.slice(this.index, this.index + length) const codePoint = Number.parseInt(hex, 16) if ( @@ -421,13 +426,13 @@ class TomlParser { this.expect("[") const output: Array = [] while (true) { - this.skipArrayWhitespace() + this.skipWhitespace() if (this.peek() === "]") { this.advance() return output } output.push(this.parseValue()) - this.skipArrayWhitespace() + this.skipWhitespace() if (this.peek() === "]") { this.advance() return output @@ -439,39 +444,23 @@ class TomlParser { private parseInlineTable(): Table { this.expect("{") const output = makeTable() - this.skipInlineWhitespace() - if (this.peek() === "}") { - this.advance() - return output - } while (true) { + this.skipWhitespace() + if (this.peek() === "}") { + this.advance() + return output + } const keys = this.parseKeyPath("=") this.skipInlineWhitespace() this.expect("=") this.skipInlineWhitespace() this.assign(output, keys, this.parseValue()) - this.skipInlineWhitespace() + this.skipWhitespace() if (this.peek() === "}") { this.advance() return output } this.expect(",") - this.skipInlineWhitespace() - if (this.peek() === "}") { - this.fail("Inline tables cannot end with a trailing comma") - } - } - } - - private skipDocumentWhitespace(): void { - while (!this.done) { - if (/[ \t\r\n]/.test(this.peek())) { - this.advance() - } else if (this.peek() === "#") { - this.skipComment() - } else { - return - } } } @@ -481,7 +470,8 @@ class TomlParser { } } - private skipArrayWhitespace(): void { + // Skips whitespace, newlines, and comments + private skipWhitespace(): void { while (!this.done) { if (/[ \t\r\n]/.test(this.peek())) { this.advance() @@ -558,7 +548,8 @@ class TomlParser { * Returns `Result.succeed` with the parsed record, or `Result.fail` with an * `EncodingError` when the input is not valid TOML. Offset date-times are * represented by `Date`, matching the package this parser replaces. Local - * dates and times remain strings. + * dates and times remain strings. Times written without seconds, which TOML + * 1.1 allows, are normalized to `:00`, so `13:37` parses as `"13:37:00"`. * * **Example** (Parsing a TOML document) * diff --git a/packages/effect/test/encoding/Toml.test.ts b/packages/effect/test/encoding/Toml.test.ts index 9f2fa32df6..33787f7dc2 100644 --- a/packages/effect/test/encoding/Toml.test.ts +++ b/packages/effect/test/encoding/Toml.test.ts @@ -162,6 +162,40 @@ nul = "\u0000" assert.deepStrictEqual(Result.getOrThrow(Toml.parse("key = '''\t\r\n'''\r\n# \t\r\n")), { key: "\t\r\n" }) }) + it("parses TOML 1.1 inline tables, escapes, and times without seconds", () => { + assert.deepStrictEqual( + Result.getOrThrow(Toml.parse(String.raw` +point = { + x = 1, # inline tables may span lines, with comments and a trailing comma + y = 2, + nested = { + z = 3, # comment + }, +} +escape = "\e[0m \x41 \xE9" +multiline = """\x41""" +literal = '\x41' +time = 13:37 +local = 1979-05-27T07:32 +space = 1979-05-27 07:32 +offset = 1979-05-27T07:32Z +`)), + { + point: { x: 1, y: 2, nested: { z: 3 } }, + escape: "\u001B[0m A é", + multiline: "A", + literal: "\\x41", + time: "13:37:00", + local: "1979-05-27T07:32:00", + space: "1979-05-27T07:32:00", + offset: new Date("1979-05-27T07:32:00Z") + } + ) + for (const input of [String.raw`a = "\xZ1"`, String.raw`a = "\x4"`, "a = { , }", "a = { a = 1,, }", "a = 24:00"]) { + assert.isTrue(Result.isFailure(Toml.parse(input)), input) + } + }) + it.each([ String.raw`value = "\uD800"`, String.raw`value = "\uDFFF"`, From 9dc85023f5792b8228c6344ed79fe0b74a608f83 Mon Sep 17 00:00:00 2001 From: effect-bot <129879685+effect-bot@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:45:32 +1300 Subject: [PATCH 06/15] Add SqlClient.batch and send PostgreSQL batches in one Sync (#10147) --- .changeset/sql-batch.md | 7 + packages/effect/src/sql/SqlClient.ts | 46 +++ packages/effect/src/sql/SqlConnection.ts | 13 + packages/effect/src/sql/Statement.ts | 117 ++++++-- packages/effect/test/sql/SqlClient.test.ts | 72 +++++ packages/effect/typetest/sql/SqlClient.tst.ts | 15 +- packages/sql/libsql/src/LibsqlClient.ts | 20 +- .../libsql/test/Client.integration.test.ts | 35 +++ packages/sql/pg/src/PgClient.ts | 6 + packages/sql/pg/src/PgConnection.ts | 269 +++++++++++++----- .../sql/pg/test/Client.integration.test.ts | 78 ++++- .../pg/test/PgConnection.in-process.test.ts | 119 ++++++++ .../pg/test/PgConnection.integration.test.ts | 73 +++++ 13 files changed, 770 insertions(+), 100 deletions(-) create mode 100644 .changeset/sql-batch.md diff --git a/.changeset/sql-batch.md b/.changeset/sql-batch.md new file mode 100644 index 0000000000..c11e67403a --- /dev/null +++ b/.changeset/sql-batch.md @@ -0,0 +1,7 @@ +--- +"effect": minor +"@effect/sql-pg": minor +"@effect/sql-libsql": minor +--- + +Add `SqlClient.batch`, which returns each statement's rows as a typed tuple and runs as one atomic round trip on PostgreSQL (also via the new `PgConnection.batch`) and libSQL, or one statement at a time on drivers without the new optional `Connection.executeBatch` hook. diff --git a/packages/effect/src/sql/SqlClient.ts b/packages/effect/src/sql/SqlClient.ts index 960b1d87ec..0f24b9d878 100644 --- a/packages/effect/src/sql/SqlClient.ts +++ b/packages/effect/src/sql/SqlClient.ts @@ -178,6 +178,50 @@ export interface Base extends Constructor { */ readonly afterCommit: (effect: Effect.Effect) => Effect.Effect + /** + * Runs the statements in order on one connection and returns each + * statement's rows. + * + * **When to use** + * + * Use to run dependent statements together, such as setting + * transaction-local context with `set_config(..., true)` before a query. + * + * **Details** + * + * Each statement is compiled and transformed by the client that built it, + * and `Statement.CurrentTransformer` applies to each. The batch runs under + * one span, on the current transaction's connection if there is one. An + * empty batch returns `[]` without acquiring a connection. + * + * PostgreSQL and libSQL send the batch in one round trip and run it as one + * transaction outside `withTransaction`, so a failing statement keeps + * nothing. Other drivers run the statements one at a time; wrap the batch in + * `withTransaction` when it must be atomic. + * + * **Example** (Setting row-level security context for one query) + * + * ```ts + * import { Effect } from "effect" + * import { SqlClient } from "effect/sql" + * + * const items = (org: string) => + * Effect.gen(function*() { + * const sql = yield* SqlClient.SqlClient + * const [, rows] = yield* sql.batch([ + * sql`SELECT set_config('app.organization_id', ${org}, true)`, + * sql`SELECT * FROM item` + * ]) + * return rows + * }) + * ``` + * + * @since 4.2.0 + */ + readonly batch: >>( + statements: S + ) => Effect.Effect<{ readonly [K in keyof S]: Effect.Success }, SqlError> + /** * Use the Reactivity service to create a reactive query. */ @@ -383,6 +427,8 @@ export const make = Effect.fnUntraced(function*(options: SqlClient.MakeOptions) withTransaction, transactionService, afterCommit, + batch: (statements: ReadonlyArray>) => + Statement.executeBatch(statements, getConnection, borrower, options.spanAttributes), reserve: transactionAcquirer, driver: options.driver, withoutTransforms(): any { diff --git a/packages/effect/src/sql/SqlConnection.ts b/packages/effect/src/sql/SqlConnection.ts index 3a2ab1ec12..ef15849bbc 100644 --- a/packages/effect/src/sql/SqlConnection.ts +++ b/packages/effect/src/sql/SqlConnection.ts @@ -62,6 +62,19 @@ export interface Connection { params: ReadonlyArray, transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined ) => Effect, SqlError> + + /** + * Runs compiled statements in order, ideally in one round trip, and returns + * each statement's untransformed rows. + * + * **Details** + * + * Optional. Without it, `SqlClient.batch` runs the statements one at a time + * with `execute` on the same connection. + */ + readonly executeBatch?: ( + statements: ReadonlyArray]> + ) => Effect>, SqlError> } /** diff --git a/packages/effect/src/sql/Statement.ts b/packages/effect/src/sql/Statement.ts index 5dd85a51d4..7808a0c49e 100644 --- a/packages/effect/src/sql/Statement.ts +++ b/packages/effect/src/sql/Statement.ts @@ -1393,6 +1393,8 @@ export const spanName = (spanAttributes: ReadonlyArray, key: string): unknown => { @@ -1499,21 +1501,7 @@ const StatementProto: Omit< } span.attribute(ATTR_SQL_METHOD, operation) span.attribute(ATTR_DB_QUERY_TEXT, sql) - const propagate = fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled) - // Measured from the span's start, so the wait also covers compiling the - // statement and any `CurrentTransformer` run first. - const clock = propagate ? waitClock(fiber) : undefined - const run = clock === undefined - ? (connection: Connection) => f(connection, sql, params) - : (connection: Connection) => - Effect.suspend(() => { - recordConnectionWait(span, clock) - return f(connection, sql, params) - }) - const execute = this.borrower === undefined - ? Effect.scoped(Effect.flatMap(this.acquirer, run)) - : this.borrower(run) - return propagate ? Effect.provideService(execute, Tracer.ParentSpan, span) : execute + return runOnConnection(fiber, span, this.acquirer, this.borrower, (connection) => f(connection, sql, params)) }) }, @@ -1618,6 +1606,44 @@ const StatementProto: Omit< } } +/** + * Runs `f` on a connection from the borrower, or one acquired for the call. + * With span propagation on, the connection wait is recorded on `span` and + * driver spans are parented under it. + */ +const runOnConnection = ( + fiber: Fiber.Fiber, + span: Tracer.Span, + acquirer: Acquirer, + borrower: Borrower | undefined, + f: (connection: Connection) => Effect.Effect +): Effect.Effect => { + const propagate = fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled) + // Measured from the span's start, so the wait also covers compiling the + // statement and any `CurrentTransformer` run first. + const clock = propagate ? waitClock(fiber) : undefined + const run = clock === undefined ? f : (connection: Connection) => + Effect.suspend(() => { + recordConnectionWait(span, clock) + return f(connection) + }) + const execute = borrower === undefined ? Effect.scoped(Effect.flatMap(acquirer, run)) : borrower(run) + return propagate ? Effect.provideService(execute, Tracer.ParentSpan, span) : execute +} + +const applyTransformer = ( + self: StatementImpl, + transform: Transformer, + fiber: Fiber.Fiber, + span: Tracer.Span +): Effect.Effect> => + transform( + self, + make(self.acquirer, self.compiler, self.spanAttributes, self.transformRows, self.borrower), + fiber, + span + ) as Effect.Effect> + const withStatement = ( self: StatementImpl, span: Tracer.Span, @@ -1628,17 +1654,60 @@ const withStatement = ( if (transform === undefined) { return f(self, fiber) } - return Effect.flatMap( - transform( - self, - make(self.acquirer, self.compiler, self.spanAttributes, self.transformRows, self.borrower), - fiber, - span - ) as Effect.Effect>, - (statement) => f(statement, fiber) - ) + return Effect.flatMap(applyTransformer(self, transform, fiber, span), (statement) => f(statement, fiber)) }) +/** + * Backs `SqlClient.batch`: runs the statements on one connection under one + * span, with each statement's compiler and row transform and the current + * transformer. + * + * @internal + */ +export const executeBatch = ( + statements: ReadonlyArray>, + acquirer: Acquirer, + borrower: Borrower | undefined, + spanAttributes: ReadonlyArray +): Effect.Effect => { + if (statements.length === 0) return Effect.succeed([]) + // OpenTelemetry names multi-statement batches `BATCH `. + const isBatch = statements.length > 1 + const target = spanTarget(spanAttributes) + const name = !isBatch ? spanName(spanAttributes) : target === undefined ? "BATCH" : `BATCH ${target}` + return Effect.useSpan(name, { kind: "client" }, (span) => + Effect.withFiber((fiber) => { + const transform = fiber.getRef(CurrentTransformer) + const impls = statements as ReadonlyArray> + const resolved = transform === undefined + ? Effect.succeed(impls) + : Effect.forEach(impls, (statement) => applyTransformer(statement, transform, fiber, span)) + return Effect.flatMap(resolved, (statements) => { + const compiled = statements.map((statement) => statement.compile()) + for (const [key, value] of spanAttributes) { + span.attribute(key, value) + } + span.attribute(ATTR_SQL_METHOD, "executeBatch") + if (isBatch) { + span.attribute(ATTR_DB_OPERATION_NAME, "BATCH") + span.attribute(ATTR_DB_OPERATION_BATCH_SIZE, statements.length) + } + span.attribute(ATTR_DB_QUERY_TEXT, compiled.map(([sql]) => sql).join("; ")) + return runOnConnection(fiber, span, acquirer, borrower, (connection) => + connection.executeBatch === undefined + ? Effect.forEach( + compiled, + ([sql, params], index) => connection.execute(sql, params, statements[index].transformRows) + ) + : Effect.map(connection.executeBatch(compiled), (results) => + results.map((rows, index) => { + const transformRows = statements[index].transformRows + return transformRows === undefined ? rows : transformRows(rows) + }))) + }) + })) +} + const isSegment = (u: unknown): u is Segment => hasProperty(u, SegmentTypeId) function convertLiteralOrFragment(clause: string | Fragment): Array { diff --git a/packages/effect/test/sql/SqlClient.test.ts b/packages/effect/test/sql/SqlClient.test.ts index fae0fa7c66..8ea7926a8e 100644 --- a/packages/effect/test/sql/SqlClient.test.ts +++ b/packages/effect/test/sql/SqlClient.test.ts @@ -12,6 +12,7 @@ import { type Scope, Semaphore, Stream, + String, Tracer } from "effect" import { Reactivity } from "effect/reactivity" @@ -867,4 +868,75 @@ describe("SqlClient", () => { assert.isFalse(calls.includes("invalidate(dropped)")) })) }) + + describe("batch", () => { + /** + * A client whose connection answers each statement with `[{ user_id }]`, + * taken from the statement's first parameter, and records what it ran. + */ + const makeBatchClient = (withExecuteBatch: boolean) => { + const calls: Array = [] + let acquired = 0 + const rowsFor = (params: ReadonlyArray) => [{ user_id: params[0] }] + const unused = () => Effect.die("unused") + const connection: SqlConnection.Connection = { + execute: (sql, params, transformRows) => + Effect.sync(() => { + calls.push(["execute", sql, params]) + return transformRows === undefined ? rowsFor(params) : transformRows(rowsFor(params)) + }), + executeRaw: unused, + executeValues: unused, + executeUnprepared: unused, + executeValuesUnprepared: unused, + executeStream: () => Stream.die("unused"), + ...(withExecuteBatch + ? { + executeBatch: (statements: ReadonlyArray]>) => + Effect.sync(() => { + calls.push(["executeBatch", statements]) + return statements.map(([, params]) => rowsFor(params)) + }) + } + : {}) + } + return SqlClient.make({ + driver: "test", + acquirer: Effect.sync(() => { + acquired++ + return connection + }), + compiler: Statement.makeCompilerSqlite(String.camelToSnake), + spanAttributes: [], + transformRows: Statement.defaultTransforms(String.snakeToCamel).array + }).pipe( + Effect.map((sql) => ({ sql, calls, acquired: () => acquired })), + Effect.provide(Reactivity.layer) + ) + } + + it.effect("runs each statement in order on one connection without executeBatch", () => + Effect.gen(function*() { + const { acquired, calls, sql } = yield* makeBatchClient(false) + const raw = sql.withoutTransforms() + + const results = yield* sql.batch([sql`SELECT ${1}`, raw`SELECT ${2}`]) + + assert.deepStrictEqual(results, [[{ userId: 1 }], [{ user_id: 2 }]]) + assert.deepStrictEqual(calls, [["execute", "SELECT ?", [1]], ["execute", "SELECT ?", [2]]]) + assert.strictEqual(acquired(), 1) + })) + + it.effect("prefers executeBatch and transforms each statement's rows", () => + Effect.gen(function*() { + const { calls, sql } = yield* makeBatchClient(true) + const raw = sql.withoutTransforms() + + const results = yield* sql.batch([sql`SELECT ${1}`, raw`SELECT ${2}`]) + assert.deepStrictEqual(yield* sql.batch([]), []) + + assert.deepStrictEqual(results, [[{ userId: 1 }], [{ user_id: 2 }]]) + assert.deepStrictEqual(calls, [["executeBatch", [["SELECT ?", [1]], ["SELECT ?", [2]]]]]) + })) + }) }) diff --git a/packages/effect/typetest/sql/SqlClient.tst.ts b/packages/effect/typetest/sql/SqlClient.tst.ts index 87d8bf8733..cb968a4341 100644 --- a/packages/effect/typetest/sql/SqlClient.tst.ts +++ b/packages/effect/typetest/sql/SqlClient.tst.ts @@ -1,5 +1,5 @@ import { Effect, hole } from "effect" -import type { SqlClient } from "effect/sql" +import type { SqlClient, SqlError, Statement } from "effect/sql" import { describe, expect, it } from "tstyche" describe("SqlClient", () => { @@ -11,4 +11,17 @@ describe("SqlClient", () => { expect(sql.reactive).type.toBeCallableWith(keys, effect) expect(sql.reactiveMailbox).type.toBeCallableWith({ anything: [1, { id: 1 }] }, effect) }) + + it("batch types each result from its statement", () => { + const sql = hole() + const a = hole>() + const b = hole>() + + expect(sql.batch([a, b])).type.toBe< + Effect.Effect< + readonly [ReadonlyArray<{ readonly a: number }>, ReadonlyArray<{ readonly b: string }>], + SqlError.SqlError + > + >() + }) }) diff --git a/packages/sql/libsql/src/LibsqlClient.ts b/packages/sql/libsql/src/LibsqlClient.ts index d5a8ad265b..6fb50b6058 100644 --- a/packages/sql/libsql/src/LibsqlClient.ts +++ b/packages/sql/libsql/src/LibsqlClient.ts @@ -4,8 +4,9 @@ * This module provides a {@link LibsqlClient} and the generic SQL client * service for `@libsql/client`. It uses Effect SQL's SQLite compiler, supports * managed SDK clients or caller-owned live clients, classifies libSQL and - * SQLite failures as `SqlError`s, and provides transaction support with - * savepoints. Streaming queries are not implemented by this driver. + * SQLite failures as `SqlError`s, provides transaction support with + * savepoints, and sends `SqlClient.batch` as one libSQL batch. Streaming + * queries are not implemented by this driver. * * @stability unstable * @since 4.0.0 @@ -262,6 +263,21 @@ export const make = ( ) { return this.execute(sql, params, transformRows) } + executeBatch(statements: ReadonlyArray]>) { + return Effect.map( + Effect.tryPromise({ + // Take the write lock up front, as `beginTransaction` does. A + // `Transaction` ignores the mode. + try: () => + (this.sdk as Libsql.Client).batch( + statements.map(([sql, params]) => ({ sql, args: params as Array })), + "write" + ), + catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute batch", "execute") }) + }), + (results) => results.map((result) => result.rows) + ) + } executeStream() { return Stream.die("executeStream not implemented") } diff --git a/packages/sql/libsql/test/Client.integration.test.ts b/packages/sql/libsql/test/Client.integration.test.ts index 071b78ab8c..9c915833fc 100644 --- a/packages/sql/libsql/test/Client.integration.test.ts +++ b/packages/sql/libsql/test/Client.integration.test.ts @@ -1,5 +1,6 @@ import { LibsqlClient } from "@effect/sql-libsql" import { assert, describe, it, layer } from "@effect/vitest" +import * as Libsql from "@libsql/client" import { Cause, Deferred, Effect, Exit, Fiber, Layer, Option } from "effect" import * as Reactivity from "effect/reactivity/Reactivity" import { SqlError } from "effect/sql/SqlError" @@ -228,6 +229,40 @@ describe("Client", () => { assert.deepStrictEqual(yield* Fiber.join(read), [{ value: 1 }]) }).pipe(Effect.provide(Reactivity.layer))) + describe("batch", () => { + it.effect("sends the statements in one libsql batch", () => + Effect.gen(function*() { + const sdk = Libsql.createClient({ url: ":memory:" }) + yield* Effect.addFinalizer(() => Effect.sync(() => sdk.close())) + let batches = 0 + const batch = sdk.batch.bind(sdk) + sdk.batch = (statements, mode) => { + batches++ + return batch(statements, mode) + } + const sql = yield* LibsqlClient.make({ liveClient: sdk }) + + const results = yield* sql.batch([sql`SELECT ${1} AS a`, sql`SELECT ${"x"} AS b`]) + + assert.deepStrictEqual(results, [[{ a: 1 }], [{ b: "x" }]]) + assert.strictEqual(batches, 1) + }).pipe(Effect.provide(Reactivity.layer))) + + it.effect("keeps nothing from a batch when a later statement fails", () => + Effect.gen(function*() { + const sql = yield* LibsqlClient.make({ url: ":memory:" }) + yield* sql`CREATE TABLE batch_rollback (id INTEGER PRIMARY KEY)` + + const error = yield* sql.batch([ + sql`INSERT INTO batch_rollback VALUES (1)`, + sql`INSERT INTO batch_rollback VALUES (1)` + ]).pipe(Effect.flip) + + assert.instanceOf(error, SqlError) + assert.deepStrictEqual(yield* sql`SELECT id FROM batch_rollback`, []) + }).pipe(Effect.provide(Reactivity.layer))) + }) + // Each test recreates the same tables. layer(LibsqlContainer.layerClient, { timeout: "30 seconds", concurrent: false })("shared tables", (it) => { it.effect("should work", () => diff --git a/packages/sql/pg/src/PgClient.ts b/packages/sql/pg/src/PgClient.ts index c83471f74b..c34842c129 100644 --- a/packages/sql/pg/src/PgClient.ts +++ b/packages/sql/pg/src/PgClient.ts @@ -401,6 +401,12 @@ class ConnectionImpl implements Connection { ? Effect.map(operation, transformRows) : operation } + executeBatch(statements: ReadonlyArray]>) { + return Effect.map( + this.connection.batch(statements.map(([sql, params]) => ({ sql, params }))), + (results) => results.map((result) => result.rows) + ) + } executeStream( sql: string, params: ReadonlyArray, diff --git a/packages/sql/pg/src/PgConnection.ts b/packages/sql/pg/src/PgConnection.ts index a5d92ffb4b..ae966a61b2 100644 --- a/packages/sql/pg/src/PgConnection.ts +++ b/packages/sql/pg/src/PgConnection.ts @@ -203,6 +203,18 @@ export interface Notification { readonly payload: string } +/** + * One statement of a `batch`. + * + * @stability unstable + * @category models + * @since 4.2.0 + */ +export interface BatchStatement { + readonly sql: string + readonly params?: ReadonlyArray | undefined +} + /** * A connected and authenticated PostgreSQL session. * @@ -254,6 +266,22 @@ export interface PgConnection { params?: ReadonlyArray, prepare?: boolean ) => Effect.Effect>, SqlError> + /** + * Sends the statements in one write closed by a single `Sync` and returns + * each statement's result. Interruption behaves as for `query`. + * + * **Details** + * + * Outside an explicit transaction the batch is one implicit transaction: + * transaction-local settings such as `set_config(..., true)` last until it + * ends, and a failing statement fails the batch and keeps nothing. Inside + * an explicit transaction a failing statement aborts it. + * + * Statements are unnamed, so a batch skips the prepared statement cache and + * is never retried. An empty batch returns `[]` without touching the + * session. A multiplexed connection pipelines the batch without pinning. + */ + readonly batch: (statements: ReadonlyArray) => Effect.Effect, SqlError> /** * Streams rows without collecting the full result. The session is pinned for * the lifetime of the stream. An early abort behaves like an interrupted @@ -549,6 +577,12 @@ class PgConnectionImpl implements PgConnection { cache: PreparedCache | undefined ): Plan => encodeQuery(sql, params, this.registry, this.bindEncoder, cache) + readonly queryCycle = (sql: string, params: ReadonlyArray): EncodeCycle => (cache) => + this.encodeQuery(sql, params, cache) + + readonly batchCycle = (statements: ReadonlyArray): EncodeCycle => () => + encodeBatch(statements, this.registry, this.bindEncoder) + /** * Routes backend messages to the oldest statement still on the wire. * @@ -677,8 +711,7 @@ class PgConnectionImpl implements PgConnection { * serializing them. */ private readonly pipelineCycle = ( - sql: string, - params: ReadonlyArray, + encode: EncodeCycle, wantRows: boolean, cache: PreparedCache | undefined ): Effect.Effect => @@ -687,7 +720,7 @@ class PgConnectionImpl implements PgConnection { if (this.deadWith !== undefined) return Effect.fail(this.deadWith) let plan: Plan try { - plan = this.encodeQuery(sql, params, cache) + plan = encode(cache) } catch (cause) { return Effect.fail(queryError(cause, "PgConnection: Failed to encode query")) } @@ -709,7 +742,7 @@ class PgConnectionImpl implements PgConnection { ) ) if (cache === undefined || entry.plan.parses) return awaited - return retryStale(entry.plan, cache, awaited, () => this.pipelineCycle(sql, params, wantRows, undefined)) + return retryStale(entry.plan, cache, awaited, () => this.pipelineCycle(encode, wantRows, undefined)) } ) @@ -718,11 +751,10 @@ class PgConnectionImpl implements PgConnection { * because competing pinned work and streams must acquire `owner` first. */ readonly cycleOwned = ( - sql: string, - params: ReadonlyArray, + encode: EncodeCycle, wantRows: boolean, cache: PreparedCache | undefined - ): Effect.Effect => Effect.suspend(() => this.attempt(sql, params, wantRows, cache)) + ): Effect.Effect => Effect.suspend(() => this.attempt(encode, wantRows, cache)) /** * Runs one cycle. A reused statement the backend has since dropped, or whose @@ -730,21 +762,20 @@ class PgConnectionImpl implements PgConnection { * that attempt skips the cache, so it cannot loop. */ private readonly attempt = ( - sql: string, - params: ReadonlyArray, + encode: EncodeCycle, wantRows: boolean, cache: PreparedCache | undefined ): Effect.Effect => { if (this.deadWith !== undefined) return Effect.fail(this.deadWith) let plan: Plan try { - plan = this.encodeQuery(sql, params, cache) + plan = encode(cache) } catch (cause) { return Effect.fail(queryError(cause, "PgConnection: Failed to encode query")) } const run = runQuery(this, plan, wantRows) if (cache === undefined || plan.parses) return run - return retryStale(plan, cache, run, () => this.attempt(sql, params, wantRows, undefined)) + return retryStale(plan, cache, run, () => this.attempt(encode, wantRows, undefined)) } /** Sends a `CancelRequest` for this session on a side connection. */ @@ -806,26 +837,34 @@ class PgConnectionImpl implements PgConnection { ) private readonly run = ( - sql: string, - params: ReadonlyArray, + encode: EncodeCycle, wantRows: boolean, - prepare: boolean - ): Effect.Effect => { - const cache = prepare ? this.prepared : undefined - return this.multiplex - ? this.pipelineCycle(sql, params, wantRows, cache) - : this.owner.withPermit(this.cycleOwned(sql, params, wantRows, cache)) - } + cache: PreparedCache | undefined + ): Effect.Effect => + this.multiplex + ? this.pipelineCycle(encode, wantRows, cache) + : this.owner.withPermit(this.cycleOwned(encode, wantRows, cache)) readonly query = (sql: string, params?: ReadonlyArray, prepare = true): Effect.Effect => - Effect.map(this.run(sql, params ?? emptyParams, true, prepare), takeResult) + Effect.map( + this.run(this.queryCycle(sql, params ?? emptyParams), true, prepare ? this.prepared : undefined), + takeResult + ) readonly queryValues = ( sql: string, params?: ReadonlyArray, prepare = true ): Effect.Effect>, SqlError> => - Effect.map(this.run(sql, params ?? emptyParams, false, prepare), takeValues) + Effect.map( + this.run(this.queryCycle(sql, params ?? emptyParams), false, prepare ? this.prepared : undefined), + takeValues + ) + + readonly batch = (statements: ReadonlyArray): Effect.Effect, SqlError> => + statements.length === 0 + ? Effect.succeed([]) + : Effect.map(this.run(this.batchCycle(statements), true, undefined), takeResults) readonly stream = (sql: string, params?: ReadonlyArray): Stream.Stream => streamRows(this, this.pin, sql, params ?? emptyParams) @@ -865,15 +904,14 @@ class PinnedPgConnection implements PgConnection { // Check the lease under the wire permit so queued work cannot run after release. private cycle( - sql: string, - params: ReadonlyArray, + encode: EncodeCycle, wantRows: boolean, - prepare: boolean + cache: PreparedCache | undefined ): Effect.Effect { return this.base.wire.withPermit(Effect.suspend(() => this.released ? Effect.fail(pinReleasedError()) - : this.base.cycleOwned(sql, params, wantRows, prepare ? this.base.prepared : undefined) + : this.base.cycleOwned(encode, wantRows, cache) )) } @@ -888,14 +926,25 @@ class PinnedPgConnection implements PgConnection { } readonly query = (sql: string, params?: ReadonlyArray, prepare = true): Effect.Effect => - Effect.map(this.cycle(sql, params ?? emptyParams, true, prepare), takeResult) + Effect.map( + this.cycle(this.base.queryCycle(sql, params ?? emptyParams), true, prepare ? this.base.prepared : undefined), + takeResult + ) readonly queryValues = ( sql: string, params?: ReadonlyArray, prepare = true ): Effect.Effect>, SqlError> => - Effect.map(this.cycle(sql, params ?? emptyParams, false, prepare), takeValues) + Effect.map( + this.cycle(this.base.queryCycle(sql, params ?? emptyParams), false, prepare ? this.base.prepared : undefined), + takeValues + ) + + readonly batch = (statements: ReadonlyArray): Effect.Effect, SqlError> => + statements.length === 0 + ? Effect.succeed([]) + : Effect.map(this.cycle(this.base.batchCycle(statements), true, undefined), takeResults) readonly stream = (sql: string, params?: ReadonlyArray): Stream.Stream => streamRows(this.base, this.pin, sql, params ?? emptyParams) @@ -907,7 +956,8 @@ class PinnedPgConnection implements PgConnection { } interface QueryOutput { - readonly result: Result + /** One result per statement, in order. */ + readonly results: ReadonlyArray readonly values: ReadonlyArray> } @@ -1017,7 +1067,8 @@ const concat = (chunks: ReadonlyArray): Uint8Array => { const emptyParams: ReadonlyArray = [] -const takeResult = (output: QueryOutput): Result => output.result +const takeResult = (output: QueryOutput): Result => output.results[0] +const takeResults = (output: QueryOutput): ReadonlyArray => output.results const takeValues = (output: QueryOutput): ReadonlyArray> => output.values /** @@ -1025,17 +1076,14 @@ const takeValues = (output: QueryOutput): ReadonlyArray> * `Execute` runs it without a row limit, and `Sync` closes the cycle; none of * the three carries per-query state, so the bytes are encoded once. */ -const describeExecuteSync: Uint8Array = concat([ - PgProtocol.encodeDescribe({ target: "portal", name: "" }), - PgProtocol.encodeExecute({ portal: "", maxRows: 0 }), - PgProtocol.encodeSync() -]) +const sync: Uint8Array = PgProtocol.encodeSync() +const execute: Uint8Array = PgProtocol.encodeExecute({ portal: "", maxRows: 0 }) +/** `Describe` / `Execute` for one batch statement; the batch ends with one `Sync`. */ +const describeExecute: Uint8Array = concat([PgProtocol.encodeDescribe({ target: "portal", name: "" }), execute]) +const describeExecuteSync: Uint8Array = concat([describeExecute, sync]) /** The same tail for a statement whose columns are already known. */ -const executeSync: Uint8Array = concat([ - PgProtocol.encodeExecute({ portal: "", maxRows: 0 }), - PgProtocol.encodeSync() -]) +const executeSync: Uint8Array = concat([execute, sync]) /** The default number of statements a connection keeps prepared. */ const defaultPreparedStatements = 100 @@ -1072,6 +1120,24 @@ interface Plan { readonly description: Description | undefined /** Set by the cycle when the backend rejected the name or the cached plan. */ stale: boolean + /** Number of statements in the cycle. */ + readonly statements: number +} + +/** Plans one attempt. The cache is `undefined` on a retry and ignored by batches. */ +type EncodeCycle = (cache: PreparedCache | undefined) => Plan + +const encodeUnnamedParseBind = ( + sql: string, + parameters: ReadonlyArray, + parameterTypes: ReadonlyArray, + encodeBind: BindEncoder +): readonly [parse: Uint8Array, bind: Uint8Array] => { + const parse = PgProtocol.encodeParse({ name: "", query: sql, parameterTypes }) + if (EffectResult.isFailure(parse)) throw parse.failure + const bind = encodeBind({ portal: "", statement: "", parameters }) + if (EffectResult.isFailure(bind)) throw bind.failure + return [parse.success, bind.success] } /** The unnamed path: `Parse` / `Bind` / `Describe` / `Execute` / `Sync`. */ @@ -1081,18 +1147,60 @@ const encodeUnnamed = ( parameterTypes: ReadonlyArray, encodeBind: BindEncoder ): Plan => { - const parse = PgProtocol.encodeParse({ name: "", query: sql, parameterTypes }) - if (EffectResult.isFailure(parse)) throw parse.failure - const bind = encodeBind({ portal: "", statement: "", parameters }) - if (EffectResult.isFailure(bind)) throw bind.failure + const [parse, bind] = encodeUnnamedParseBind(sql, parameters, parameterTypes, encodeBind) return { - frame: concat([parse.success, bind.success, describeExecuteSync]), + frame: concat([parse, bind, describeExecuteSync]), closes: 0, parses: true, describes: true, prepared: undefined, description: undefined, - stale: false + stale: false, + statements: 1 + } +} + +const inferParameters = ( + params: ReadonlyArray, + registry: PgTypes.Registry | undefined +): { readonly parameters: Array; readonly parameterTypes: Array } => { + const count = params.length + const parameters: Array = new Array(count) + const parameterTypes: Array = new Array(count) + for (let index = 0; index < count; index++) { + const parameter = inferParameter(params[index], registry) + parameters[index] = parameter + parameterTypes[index] = parameter.oid + } + return { parameters, parameterTypes } +} + +/** + * Unnamed `Parse` / `Bind` / `Describe` / `Execute` per statement, then one + * `Sync`. Nothing is named, so a batch bypasses the prepared statement cache + * and is never retried. + */ +const encodeBatch = ( + statements: ReadonlyArray, + registry: PgTypes.Registry | undefined, + encodeBind: BindEncoder +): Plan => { + const chunks: Array = [] + for (const statement of statements) { + const { parameterTypes, parameters } = inferParameters(statement.params ?? emptyParams, registry) + const [parse, bind] = encodeUnnamedParseBind(statement.sql, parameters, parameterTypes, encodeBind) + chunks.push(parse, bind, describeExecute) + } + chunks.push(sync) + return { + frame: concat(chunks), + closes: 0, + parses: true, + describes: true, + prepared: undefined, + description: undefined, + stale: false, + statements: statements.length } } @@ -1113,14 +1221,7 @@ const encodeQuery = ( encodeBind: BindEncoder, cache: PreparedCache | undefined ): Plan => { - const count = params.length - const parameters: Array = new Array(count) - const parameterTypes: Array = new Array(count) - for (let index = 0; index < count; index++) { - const parameter = inferParameter(params[index], registry) - parameters[index] = parameter - parameterTypes[index] = parameter.oid - } + const { parameterTypes, parameters } = inferParameters(params, registry) if (cache === undefined) { return encodeUnnamed(sql, parameters, parameterTypes, encodeBind) @@ -1149,7 +1250,8 @@ const encodeQuery = ( describes: false, prepared, description: prepared.description, - stale: false + stale: false, + statements: 1 } } @@ -1163,7 +1265,8 @@ const encodeQuery = ( describes: true, prepared, description: undefined, - stale: false + stale: false, + statements: 1 } } @@ -1366,9 +1469,13 @@ class QueryMachine implements Consumer { private readonly finish: (effect: Effect.Effect) => void /** Installed on the parser while this machine is at the head of the queue. */ readonly readField: PgProtocol.FieldReader | undefined + private readonly wantRows: boolean /** Object rows, or `undefined` when the caller asked for positional ones. */ - private readonly rows: Array | undefined - private readonly values: Array> | undefined + private rows: Array | undefined + private values: Array> | undefined + /** Statements left, including the current one. */ + private remaining: number + private readonly results: Array = [] private closes: number private phase: QueryPhase @@ -1392,8 +1499,10 @@ class QueryMachine implements Consumer { this.conn = conn this.plan = plan this.finish = finish + this.wantRows = wantRows this.rows = wantRows ? [] : undefined this.values = wantRows ? undefined : [] + this.remaining = plan.statements this.closes = plan.closes this.phase = plan.closes > 0 ? "close" : plan.parses ? "parse" : "bind" const description = plan.description @@ -1407,10 +1516,37 @@ class QueryMachine implements Consumer { return this.done } + /** Saves the statement's result, then waits for `ReadyForQuery` or the next `Parse`. */ + private endStatement(): void { + this.results.push({ + command: this.command, + rowCount: this.rowCount, + oid: this.oid, + rows: this.rows ?? emptyRows, + fields: this.resultFields + }) + if (--this.remaining === 0) { + this.phase = "complete" + return + } + this.rows = this.wantRows ? [] : undefined + this.values = this.wantRows ? undefined : [] + this.fieldCount = 0 + this.resultFields = emptyFields + this.rowBuilder = undefined + this.command = "" + this.rowCount = 0 + this.oid = null + this.phase = "parse" + } + abort(onDrained: () => void): void { if (this.done) return onDrained() this.aborted = true this.drainDone = onDrained + // Draining skips later `RowDescription`s, so don't decode their rows + // with this statement's reader. + this.conn.session.parser.readField = undefined } private complete(effect: Effect.Effect): void { @@ -1516,13 +1652,11 @@ class QueryMachine implements Consumer { this.command = parsed.command this.rowCount = parsed.rowCount this.oid = parsed.oid - this.phase = "complete" - return + return this.endStatement() } case "EmptyQueryResponse": if (this.phase !== "rows") return this.failDesync(`Unexpected EmptyQueryResponse during ${this.phase}`) - this.phase = "complete" - return + return this.endStatement() case "ErrorResponse": { if (isStalePreparedStatement(message.fields.code)) this.plan.stale = true // A cycle that carried this statement's `Parse` but failed before its @@ -1545,16 +1679,7 @@ class QueryMachine implements Consumer { } case "ReadyForQuery": if (this.phase !== "complete") return this.failDesync(`Unexpected ReadyForQuery during ${this.phase}`) - return this.complete(Effect.succeed({ - result: { - command: this.command, - rowCount: this.rowCount, - oid: this.oid, - rows: this.rows ?? emptyRows, - fields: this.resultFields - }, - values: this.values ?? emptyValues - })) + return this.complete(Effect.succeed({ results: this.results, values: this.values ?? emptyValues })) case "CopyInResponse": case "CopyOutResponse": case "CopyBothResponse": @@ -1976,7 +2101,7 @@ const unlisten = (conn: PgConnectionImpl, pinned: PinnedPgConnection, identifier unlistenTimeoutMillis ) return Effect.ensuring( - Effect.ignore(conn.cycleOwned(`UNLISTEN ${identifier}`, emptyParams, true, conn.prepared)), + Effect.ignore(conn.cycleOwned(conn.queryCycle(`UNLISTEN ${identifier}`, emptyParams), true, conn.prepared)), Effect.andThen(Effect.sync(() => clearTimeout(timeout)), releaseUnlisten(conn, pinned)) ) } diff --git a/packages/sql/pg/test/Client.integration.test.ts b/packages/sql/pg/test/Client.integration.test.ts index 6f282fca83..19e58b2105 100644 --- a/packages/sql/pg/test/Client.integration.test.ts +++ b/packages/sql/pg/test/Client.integration.test.ts @@ -14,7 +14,8 @@ import { Schedule, Schema, Stream, - String + String, + Tracer } from "effect" import * as Reactivity from "effect/reactivity/Reactivity" import { Model } from "effect/schema" @@ -426,6 +427,18 @@ it.layer(PgContainer.layerClient, { timeout: "30 seconds" })("PgClient", (it) => assert.deepStrictEqual(seen, [{ count: 1 }]) })) + + it.effect("batch applies the current statement transformer to each statement", () => + Effect.gen(function*() { + const sql = yield* PgClient.PgClient + const results = yield* sql.batch([sql`SELECT 1 AS value`, sql`SELECT 3 AS value`]).pipe( + Effect.provideService( + Statement.CurrentTransformer, + (statement, sql) => Effect.succeed(sql.unsafe(statement.compile()[0].replace(" AS", " + 1 AS"))) + ) + ) + assert.deepStrictEqual(results, [[{ value: 2 }], [{ value: 4 }]]) + })) }) it.layer(PgContainer.layerMakeClientUnprepared, { timeout: "30 seconds" })( @@ -670,6 +683,34 @@ it.layer(PgContainer.layerClientWithTransforms, { timeout: "30 seconds" })("PgCl expect(value).toEqual([[1]]) })) + it.effect("batch runs on the transaction connection and transforms rows", () => + Effect.gen(function*() { + const sql = yield* PgClient.PgClient + const setOrg = (org: string) => sql`SELECT set_config('app.org', ${org}, true)` + const query = sql<{ readonly orgName: string }>`SELECT current_setting('app.org', true) AS org_name` + + const [, rows] = yield* sql.batch([setOrg("acme"), query]) + assert.deepStrictEqual(rows, [{ orgName: "acme" }]) + const inTransaction = yield* sql.withTransaction(Effect.gen(function*() { + yield* sql.batch([setOrg("globex")]) + return yield* query + })) + assert.deepStrictEqual(inTransaction, [{ orgName: "globex" }]) + })) + + it.effect("batch compiles and transforms each statement with its own client", () => + Effect.gen(function*() { + const sql = yield* PgClient.PgClient + const raw = sql.withoutTransforms() + yield* raw`CREATE TABLE batch_untransformed (${raw("mixedCase")} int4)` + const results = yield* sql.batch([ + raw`INSERT INTO batch_untransformed (${raw("mixedCase")}) VALUES (1)`, + raw`SELECT ${raw("mixedCase")} AS org_name FROM batch_untransformed`, + sql`SELECT ${sql("mixedCase")} AS org_name FROM (SELECT 2 AS mixed_case) AS t` + ]) + assert.deepStrictEqual(results, [[], [{ org_name: 1 }], [{ orgName: 2 }]]) + })) + it.effect("retains the supplied config", () => Effect.gen(function*() { const sql = yield* PgClient.PgClient @@ -823,4 +864,39 @@ it.layer(PgContainer.layer, { timeout: "30 seconds" })("PgClient onAcquire", (it assert.strictEqual(finalized, 2) }).pipe(Effect.scoped, Effect.provide(Reactivity.layer))) + + it.effect("batch propagates its span like a statement", () => + Effect.gen(function*() { + const container = yield* PgContainer + const spans: Array = [] + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options) + spans.push(span) + return span + } + }) + const sql = yield* PgClient.make({ + url: Redacted.make(container.getConnectionUri()), + onAcquire: Effect.withSpan(Effect.void, "acquire hook") + }) + // The span the hook runs under, and whether it recorded the connection wait. + const hookParent = Effect.fnUntraced(function*(statement: Effect.Effect) { + spans.length = 0 + yield* statement.pipe(Effect.withSpan("caller")) + const hook = spans.find((span) => span.name === "acquire hook")! + const parent = spans.find((span) => span.spanId === Option.getOrThrow(hook.parent).spanId)! + return [parent.name === "caller", parent.attributes.has("db.client.connection.wait_time_ms")] + }) + + for (const propagate of [false, true]) { + const traced = (effect: Effect.Effect) => + effect.pipe(Effect.withTracer(tracer), Effect.provideService(Statement.SpanPropagationEnabled, propagate)) + assert.deepStrictEqual( + yield* traced(hookParent(sql.batch([sql`SELECT 1`]))), + yield* traced(hookParent(sql`SELECT 1`)), + `propagate: ${propagate}` + ) + } + }).pipe(Effect.scoped, Effect.provide(Reactivity.layer))) }) diff --git a/packages/sql/pg/test/PgConnection.in-process.test.ts b/packages/sql/pg/test/PgConnection.in-process.test.ts index 4120c2aa34..7095186968 100644 --- a/packages/sql/pg/test/PgConnection.in-process.test.ts +++ b/packages/sql/pg/test/PgConnection.in-process.test.ts @@ -434,6 +434,125 @@ describe("PgConnection in-process server", () => { assert.deepStrictEqual(frontendTags(writes[1]), ["P", "B", "D", "E", "S", "P", "B", "D", "E", "S"]) })) + describe("batch", () => { + const makeScripted = (reply: (write: Buffer) => Buffer) => { + const writes: Array = [] + const socket: Duplex = new Duplex({ + read() {}, + write(chunk: Buffer, _encoding, callback) { + const message = Buffer.from(chunk) + writes.push(message) + queueMicrotask(() => + socket.push( + writes.length === 1 ? Buffer.concat([authenticationOk, backendKeyData, readyForQuery]) : reply(message) + ) + ) + callback() + } + }) + return { socket, writes } + } + + const column = (name: string, oid: number) => + backendMessage( + "T", + Buffer.concat([ + int16(1), + Buffer.from(`${name}\0`), + int32(0), + int16(0), + int32(oid), + int16(-1), + int32(-1), + int16(1) + ]) + ) + const statementResult = (description: Buffer, value: Buffer) => + Buffer.concat([ + backendMessage("1", Buffer.alloc(0)), + backendMessage("2", Buffer.alloc(0)), + description, + backendMessage("D", Buffer.concat([int16(1), int32(value.length), value])), + backendMessage("C", Buffer.from("SELECT 1\0")) + ]) + + it.effect("sends every statement unnamed in one write closed by a single Sync", () => + Effect.gen(function*() { + const { socket, writes } = makeScripted(() => + Buffer.concat([ + statementResult(column("org", 25), Buffer.from("acme")), + statementResult(column("n", 23), int32(7)), + readyForQuery + ]) + ) + const connection = yield* PgConnection.make({ username: "test", stream: () => socket }) + + const results = yield* connection.batch([ + { sql: "SELECT set_config('app.org', $1, true) AS org", params: ["acme"] }, + { sql: "SELECT 7::int4 AS n" } + ]) + + assert.strictEqual(writes.length, 2) + assert.deepStrictEqual(frontendTags(writes[1]), ["P", "B", "D", "E", "P", "B", "D", "E", "S"]) + assert.deepStrictEqual(frontendPreparedNames(writes[1]), ["", ""]) + assert.deepStrictEqual(results.map((result) => result.rows), [[{ org: "acme" }], [{ n: 7 }]]) + })) + + it.effect("is never retried", () => + Effect.gen(function*() { + const { socket, writes } = makeScripted((write) => + frontendTags(write).length === 5 ? emptyQueryResult : Buffer.concat([ + backendMessage("1", Buffer.alloc(0)), + errorResponse([["S", "ERROR"], ["C", "0A000"], ["M", "not supported"]]), + readyForQuery + ]) + ) + const connection = yield* PgConnection.make({ username: "test", stream: () => socket }) + yield* connection.query("SELECT 1") + + const error = yield* Effect.flip(connection.batch([{ sql: "SELECT 1" }, { sql: "SELECT 1" }])) + + assert.propertyVal(error.reason.cause, "code", "0A000") + assert.strictEqual(writes.length, 3) + })) + + it.effect("returns no results without writing for an empty batch", () => + Effect.gen(function*() { + const { socket, writes } = makeScripted(() => emptyQueryResult) + const connection = yield* PgConnection.make({ username: "test", stream: () => socket }) + + assert.deepStrictEqual(yield* connection.batch([]), []) + assert.strictEqual(writes.length, 1) + })) + + it.live("drains an interrupted batch whose statements return different column types", () => + Effect.gen(function*() { + const { socket, writes } = makeScripted(() => + writes.length === 2 ? statementResult(column("n", 23), int32(7)) : emptyQueryResult + ) + // A cancel opens its own stream; give it one that goes nowhere. + let streams = 0 + const connection = yield* PgConnection.make({ + username: "test", + stream: () => + streams++ === 0 ? socket : new Duplex({ read() {}, write: (_chunk, _encoding, callback) => callback() }) + }) + + const batch = yield* Effect.forkChild( + connection.batch([{ sql: "SELECT 7::int4 AS n" }, { sql: "SELECT 'x'::text AS t" }]) + ) + // Let the first statement's int4 result arrive before interrupting. + yield* Effect.sleep("5 millis") + const interrupting = yield* Effect.forkChild(Fiber.interrupt(batch)) + yield* Effect.yieldNow + // The second statement's text result arrives while the batch drains. + socket.push(Buffer.concat([statementResult(column("t", 25), Buffer.from("x")), readyForQuery])) + yield* Fiber.join(interrupting) + + assert.deepStrictEqual((yield* connection.query("SELECT 1")).rows, []) + })) + }) + it.effect("uses distinct prepared statement names across connections", () => Effect.gen(function*() { const writes: Array> = [] diff --git a/packages/sql/pg/test/PgConnection.integration.test.ts b/packages/sql/pg/test/PgConnection.integration.test.ts index ef9b8304cd..a14b5027b7 100644 --- a/packages/sql/pg/test/PgConnection.integration.test.ts +++ b/packages/sql/pg/test/PgConnection.integration.test.ts @@ -617,6 +617,79 @@ it.layer(PgContainer.layer, { timeout: "30 seconds" })("PgConnection", (it) => { ) assert.deepStrictEqual(held.rows[0], { n: 1 }) })) + it.effect("returns each statement's result from one batch and ends the context at Sync", () => + Effect.gen(function*() { + const connection = yield* makeConnection() + const results = yield* connection.batch([ + { sql: "SELECT set_config('app.org', $1, true)", params: ["acme"] }, + { sql: "SELECT current_setting('app.org', true) AS org" } + ]) + assert.deepStrictEqual(results[1].rows, [{ org: "acme" }]) + const after = yield* connection.query("SELECT coalesce(current_setting('app.org', true), '') AS org") + assert.deepStrictEqual(after.rows, [{ org: "" }]) + })) + + it.effect("fails a batch with the failing statement's error, keeps nothing and stays usable", () => + Effect.gen(function*() { + const connection = yield* makeConnection() + yield* connection.query("CREATE TEMP TABLE batch_rolled_back (a int4)") + const error = yield* Effect.flip(connection.batch([ + { sql: "INSERT INTO batch_rolled_back VALUES (1)" }, + { sql: "SELECT 1/0" }, + { sql: "INSERT INTO batch_rolled_back VALUES (2)" } + ])) + assert.propertyVal(error.reason.cause, "code", "22012") + assert.deepStrictEqual((yield* connection.query("SELECT count(*)::int4 AS n FROM batch_rolled_back")).rows, [{ + n: 0 + }]) + })) + + it.effect("runs batch statements unnamed", () => + Effect.gen(function*() { + const connection = yield* makeConnection() + const batch = [{ sql: "SELECT $1::int4 AS n", params: [1] }] + yield* connection.batch(batch) + assert.deepStrictEqual((yield* connection.batch(batch))[0].rows, [{ n: 1 }]) + const held = yield* connection.query("SELECT count(*)::int4 AS n FROM pg_prepared_statements", [], false) + assert.deepStrictEqual(held.rows, [{ n: 0 }]) + })) + + it.effect("leaves a transaction aborted after a failing batch until ROLLBACK", () => + Effect.gen(function*() { + const connection = yield* makeConnection() + yield* connection.query("BEGIN") + const error = yield* Effect.flip(connection.batch([ + { sql: "SELECT set_config('app.org', $1, true)", params: ["acme"] }, + { sql: "SELECT 1/0" } + ])) + assert.propertyVal(error.reason.cause, "code", "22012") + const aborted = yield* Effect.flip(connection.query("SELECT 1")) + assert.propertyVal(aborted.reason.cause, "code", "25P02") + yield* connection.query("ROLLBACK") + assert.deepStrictEqual((yield* connection.query("SELECT 1::int4 AS n")).rows, [{ n: 1 }]) + })) + + it.effect("keeps batch context to its own pipelined cycle", () => + Effect.gen(function*() { + const connection = yield* makeConnection({ multiplex: true }) + const scoped = (org: string) => + Effect.map( + connection.batch([ + { sql: "SELECT set_config('app.org', $1, true)", params: [org] }, + { sql: "SELECT current_setting('app.org', true) AS org" } + ]), + (results) => results[1].rows[0].org + ) + const plain = Effect.map( + connection.query("SELECT coalesce(current_setting('app.org', true), '') AS org"), + (result) => result.rows[0].org + ) + const orgs = yield* Effect.all([scoped("a"), plain, scoped("b"), plain, scoped("c")], { + concurrency: "unbounded" + }) + assert.deepStrictEqual(orgs, ["a", "", "b", "", "c"]) + })) + it.effect("orders ordinary statements against a stream on the same session", () => Effect.gen(function*() { const connection = yield* makeConnection() From ae96f95142bd1c93717a2ae9a9457afd2315ae75 Mon Sep 17 00:00:00 2001 From: effect-bot <129879685+effect-bot@users.noreply.github.com> Date: Fri, 30 Oct 2026 22:37:53 +1300 Subject: [PATCH 07/15] Build HttpRouter.toHttpEffect apps with a fresh router (#10194) Co-authored-by: Tim --- ...http-router-to-http-effect-fresh-router.md | 9 ++ packages/effect/src/Layer.ts | 34 ++++++- packages/effect/src/http/HttpRouter.ts | 32 +++++-- packages/effect/test/Layer.test.ts | 22 +++++ packages/effect/test/http/HttpRouter.test.ts | 91 ++++++++++++++++++- 5 files changed, 173 insertions(+), 15 deletions(-) create mode 100644 .changeset/http-router-to-http-effect-fresh-router.md diff --git a/.changeset/http-router-to-http-effect-fresh-router.md b/.changeset/http-router-to-http-effect-fresh-router.md new file mode 100644 index 0000000000..79578c6f82 --- /dev/null +++ b/.changeset/http-router-to-http-effect-fresh-router.md @@ -0,0 +1,9 @@ +--- +"effect": minor +--- + +Build `HttpRouter.toHttpEffect` apps with their own router, so sub-app routes and middleware no longer register on the outer server's router when built inside `HttpRouter.serve` or `HttpRouter.toWebHandler`. The sub-app's router also stands in for `HttpRouter.layer` within the app, so apps that provide it themselves are isolated too. + +`HttpRouter.serve` likewise always builds its own router, instead of reusing an `HttpRouter.layer` already built outside it. Its `routerConfig` option now always applies. + +`Layer.forkMemoMap`, `Layer.forkMemoMapUnsafe` and `Layer.CurrentMemoMap.forkOrCreate` accept a `fresh` option listing layers that the child memo map builds again instead of reusing from its parent. diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index 2c7c6948fe..a4131916c3 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -421,9 +421,11 @@ class MemoMapImpl implements MemoMap { } readonly parent: MemoMap | undefined + readonly fresh: ReadonlySet> | undefined - constructor(parent?: MemoMap) { + constructor(parent?: MemoMap, fresh?: ReadonlySet>) { this.parent = parent + this.fresh = fresh } readonly map = new Map, MemoMapEntry>() @@ -437,6 +439,7 @@ class MemoMapImpl implements MemoMap { memoMapObserve(local, scope) return local.deferred.effect ?? Deferred.await(local.deferred) } + if (this.fresh?.has(layer)) return undefined return this.parent?.get(layer, scope) } @@ -514,6 +517,12 @@ export const makeMemoMapUnsafe = (): MemoMap => new MemoMapImpl() * builds should see parent memoized layers without writing newly built layers * back to the parent. * + * **Details** + * + * Layers listed in the `fresh` option (since 4.2.0) are never looked up in the + * parent. Each is built again the first time the child uses it, then memoized + * in the child. + * * @see {@link forkMemoMap} for allocating the child memo map inside `Effect` * @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent * @@ -521,7 +530,10 @@ export const makeMemoMapUnsafe = (): MemoMap => new MemoMapImpl() * @category constructors * @since 4.0.0 */ -export const forkMemoMapUnsafe = (parent: MemoMap): MemoMap => new MemoMapImpl(parent) +export const forkMemoMapUnsafe = ( + parent: MemoMap, + options?: { readonly fresh?: Iterable> | undefined } +): MemoMap => new MemoMapImpl(parent, options?.fresh ? new Set(options.fresh) : undefined) /** * Constructs a `MemoMap` effectfully so it can be used to build additional layers. @@ -568,6 +580,12 @@ export const makeMemoMap: Effect = internalEffect.sync(makeMemoMapUnsaf * Use when a layer build should inherit already memoized layers from an * existing `MemoMap` while keeping newly memoized layers out of the parent map. * + * **Details** + * + * Layers listed in the `fresh` option (since 4.2.0) are never looked up in the + * parent. Each is built again the first time the child uses it, then memoized + * in the child. + * * @see {@link makeMemoMap} for creating a root memo map in an `Effect` * @see {@link forkMemoMapUnsafe} for the synchronous constructor variant * @see {@link buildWithMemoMap} for building layers with an explicit memo map @@ -576,7 +594,10 @@ export const makeMemoMap: Effect = internalEffect.sync(makeMemoMapUnsaf * @category constructors * @since 4.0.0 */ -export const forkMemoMap = (parent: MemoMap): Effect => internalEffect.sync(() => forkMemoMapUnsafe(parent)) +export const forkMemoMap = ( + parent: MemoMap, + options?: { readonly fresh?: Iterable> | undefined } +): Effect => internalEffect.sync(() => forkMemoMapUnsafe(parent, options)) /** * Context service for the current `MemoMap` used in layer construction. @@ -598,9 +619,12 @@ export const forkMemoMap = (parent: MemoMap): Effect => internalEffect. * @since 3.13.0 */ export class CurrentMemoMap extends Context.Service()("effect/Layer/CurrentMemoMap") { - static forkOrCreate(self: Context.Context): MemoMap { + static forkOrCreate( + self: Context.Context, + options?: { readonly fresh?: Iterable> | undefined } + ): MemoMap { const current = Context.getOrUndefined(self, CurrentMemoMap) - return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe() + return current ? forkMemoMapUnsafe(current, options) : makeMemoMapUnsafe() } } diff --git a/packages/effect/src/http/HttpRouter.ts b/packages/effect/src/http/HttpRouter.ts index 625684cfd5..7135a5406c 100644 --- a/packages/effect/src/http/HttpRouter.ts +++ b/packages/effect/src/http/HttpRouter.ts @@ -653,11 +653,19 @@ export const layer: Layer.Layer = Layer.effect(HttpRouter)(make) * `Scope`; route request markers are converted into the ordinary requirements of * the returned handler. * + * The app is built with its own fresh `HttpRouter`, which also stands in for + * `HttpRouter.layer` if the app provides it. The routes and middleware it + * registers are only reachable through the returned handler, even when it is + * built inside another router app such as `serve` or `toWebHandler`. + * * **Gotchas** * * The layer is built with a forked `MemoMap`, so calling `toHttpEffect` twice * will build the same layer twice. * + * The fresh router reads `RouterConfig` from the context where `toHttpEffect` + * is run, not from the `routerConfig` option of the outer server. + * * @stability unstable * @category converting * @since 4.0.0 @@ -673,14 +681,16 @@ export const toHttpEffect = ( Request.Without, Exclude, HttpRouter> | Scope.Scope > => - Effect.contextWith((context) => { - const scope = Context.get(context, Scope.Scope) - const memoMap = Layer.CurrentMemoMap.forkOrCreate(context) - return Effect.map(Layer.buildWithMemoMap(Layer.provideMerge(appLayer, layer), memoMap, scope), (context) => { - const router = Context.get(context, HttpRouter) - return router.asHttpEffect() - }) - }) as any + Effect.contextWith((context) => + Effect.map( + Layer.buildWithMemoMap( + Layer.provideMerge(appLayer, layer), + Layer.CurrentMemoMap.forkOrCreate(context, { fresh: [layer] }), + Context.get(context, Scope.Scope) + ), + (context) => Context.get(context, HttpRouter).asHttpEffect() + ) + ) as any const RouteTypeId = "~effect/http/HttpRouter/Route" @@ -1332,6 +1342,10 @@ export const provideRequest = * Layers first built inside the app are private to this server. Provide * services that must be shared with sibling layers outside `serve`. * + * The server always builds its own `HttpRouter`, even if `HttpRouter.layer` was + * already built outside `serve`. Within the app, `HttpRouter.layer` resolves to + * the server's router. + * * **Gotchas** * * The layer is built with a forked `MemoMap`, so calling `serve` twice will @@ -1384,7 +1398,7 @@ export const serve = | Request.On : layer ) return Effect.contextWith((context) => { - const memoMap = Layer.CurrentMemoMap.forkOrCreate(context) + const memoMap = Layer.CurrentMemoMap.forkOrCreate(context, { fresh: [layer] }) return Layer.buildWithMemoMap(layerWithRouter, memoMap, Context.get(context, Scope.Scope)) }).pipe( Effect.map((context) => { diff --git a/packages/effect/test/Layer.test.ts b/packages/effect/test/Layer.test.ts index f0d871dbfd..bdbf95d130 100644 --- a/packages/effect/test/Layer.test.ts +++ b/packages/effect/test/Layer.test.ts @@ -733,6 +733,28 @@ describe("Layer", () => { assert.deepStrictEqual(arr, [acquire1, acquire2, acquire2, release2, release2, release1]) })) + + it.effect("forked memo maps build fresh layers again but reuse other parent layers", () => + Effect.gen(function*() { + const arr: Array = [] + const freshLayer = makeLayer1(arr) + const sharedLayer = makeLayer2(arr) + const parent = yield* Layer.makeMemoMap + const child = yield* Layer.forkMemoMap(parent, { fresh: [freshLayer] }) + + const scope1 = yield* Scope.make() + const scope2 = yield* Scope.make() + + yield* Layer.buildWithMemoMap(freshLayer, parent, scope1) + yield* Layer.buildWithMemoMap(sharedLayer, parent, scope1) + yield* Layer.buildWithMemoMap(freshLayer, child, scope2) + yield* Layer.buildWithMemoMap(sharedLayer, child, scope2) + + yield* Scope.close(scope2, Exit.void) + yield* Scope.close(scope1, Exit.void) + + assert.deepStrictEqual(arr, [acquire1, acquire2, acquire1, release1, release2, release1]) + })) }) describe("tracing", () => { diff --git a/packages/effect/test/http/HttpRouter.test.ts b/packages/effect/test/http/HttpRouter.test.ts index ac928ab2ab..24026d7939 100644 --- a/packages/effect/test/http/HttpRouter.test.ts +++ b/packages/effect/test/http/HttpRouter.test.ts @@ -1,6 +1,7 @@ import { assert, describe, it } from "@effect/vitest" import { Effect, Layer, Option } from "effect" -import { HttpRouter, HttpServerError, HttpServerRequest, HttpServerResponse } from "effect/http" +import { HttpRouter, HttpServer, HttpServerError, HttpServerRequest, HttpServerResponse } from "effect/http" +import * as NetAddress from "effect/net/NetAddress" const echoUrl = (request: HttpServerRequest.HttpServerRequest) => Effect.succeed(HttpServerResponse.text(request.url)) @@ -113,6 +114,94 @@ describe("HttpRouter", () => { assert.strictEqual(body, "/?tab=1") })) + describe("toHttpEffect sub-apps", () => { + const Admin = HttpRouter.add("GET", "/admin/stats", HttpServerResponse.text("admin stats")) + + const request = async (app: Layer.Layer, init?: RequestInit) => { + const { dispose, handler } = HttpRouter.toWebHandler(app, { disableLogger: true }) + try { + const response = await handler(new Request("http://localhost/admin/stats", init)) + return { status: response.status, body: await response.text() } + } finally { + await dispose() + } + } + + for ( + const { name, subApp } of [ + { name: "only serves sub-app routes through the mount", subApp: Admin }, + { + name: "only serves routes of a sub-app that provides HttpRouter.layer through the mount", + subApp: Admin.pipe(Layer.provide(HttpRouter.layer)) + } + ] + ) { + it(name, async () => { + const app = HttpRouter.use(Effect.fnUntraced(function*(router) { + const admin = yield* HttpRouter.toHttpEffect(subApp) + yield* router.add( + "*", + "/admin/*", + Effect.gen(function*() { + const request = yield* HttpServerRequest.HttpServerRequest + if (request.headers.authorization !== "Bearer admin") { + return HttpServerResponse.text("unauthorized", { status: 401 }) + } + return yield* Effect.orDie(admin) + }) + ) + })) + + assert.deepStrictEqual(await request(app), { status: 401, body: "unauthorized" }) + assert.deepStrictEqual(await request(app, { headers: { authorization: "Bearer admin" } }), { + status: 200, + body: "admin stats" + }) + }) + } + + it("mounts a sub-app at one of its own routes", async () => { + const app = HttpRouter.use(Effect.fnUntraced(function*(router) { + const admin = yield* HttpRouter.toHttpEffect(Admin) + yield* router.add("GET", "/admin/stats", Effect.orDie(admin)) + })) + + assert.deepStrictEqual(await request(app), { status: 200, body: "admin stats" }) + }) + }) + + it.effect("serve does not reuse an HttpRouter.layer memoized outside it", () => + Effect.gen(function*() { + let serverHandler: Effect.Effect | undefined + const server = HttpServer.make({ + address: NetAddress.inetAddressUnsafe(NetAddress.ipv4Loopback, 0), + serve: (handler) => Effect.sync(() => void (serverHandler = handler)) + }) + const outside = HttpRouter.add("GET", "/outside", HttpServerResponse.text("outside")).pipe( + Layer.provide(HttpRouter.layer) + ) + const app = HttpRouter.serve(HttpRouter.add("GET", "/inside", HttpServerResponse.text("inside")), { + disableLogger: true, + disableListenLog: true + }).pipe( + Layer.provideMerge(outside), + Layer.provide(Layer.succeed(HttpServer.HttpServer)(server)) + ) + yield* Layer.build(app) + const status = (path: string) => + serverHandler!.pipe( + Effect.catchCause((cause) => Effect.map(HttpServerError.causeResponse(cause), ([response]) => response)), + Effect.map((response) => response.status), + Effect.provideService( + HttpServerRequest.HttpServerRequest, + HttpServerRequest.fromWeb(new Request(`http://localhost${path}`)) + ) + ) + + assert.strictEqual(yield* status("/inside"), 200) + assert.strictEqual(yield* status("/outside"), 404) + })) + for (const ignoreDuplicateSlashes of [true, false]) { it.effect(`preserves the local URL with ignoreDuplicateSlashes=${ignoreDuplicateSlashes}`, () => Effect.gen(function*() { From 4e28ee40e7a817a0e8c5d4dee95193f461115d1d Mon Sep 17 00:00:00 2001 From: Tim Date: Sat, 31 Oct 2026 22:02:37 +1300 Subject: [PATCH 08/15] Return Result from Yaml.parse instead of throwing (#10224) --- .changeset/yaml-parse-result.md | 5 + packages/effect/src/ai/internal/mcpSkills.ts | 6 +- packages/effect/src/cli/Primitive.ts | 4 +- packages/effect/src/encoding/Yaml.ts | 70 ++++++++---- packages/effect/test/encoding/Yaml.test.ts | 103 ++++++++++-------- .../ai-codegen/test/OpenAiGeneration.test.ts | 5 +- .../test/OpenRouterTranscriptions.test.ts | 5 +- .../openapi-generator/src/OpenApiPatch.ts | 12 +- 8 files changed, 129 insertions(+), 81 deletions(-) create mode 100644 .changeset/yaml-parse-result.md diff --git a/.changeset/yaml-parse-result.md b/.changeset/yaml-parse-result.md new file mode 100644 index 0000000000..77395760ea --- /dev/null +++ b/.changeset/yaml-parse-result.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +`Yaml.parse` now returns a `Result` instead of throwing, failing with an `EncodingError` on invalid input. diff --git a/packages/effect/src/ai/internal/mcpSkills.ts b/packages/effect/src/ai/internal/mcpSkills.ts index 473c6a4f9f..8ecc93b9ab 100644 --- a/packages/effect/src/ai/internal/mcpSkills.ts +++ b/packages/effect/src/ai/internal/mcpSkills.ts @@ -9,6 +9,7 @@ import * as Yaml from "../../encoding/Yaml.ts" import * as Mime from "../../http/Mime.ts" import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" +import * as Result from "../../Result.ts" import * as Rpc from "../../rpc/Rpc.ts" import * as RpcGroup from "../../rpc/RpcGroup.ts" import * as Schema from "../../Schema.ts" @@ -244,11 +245,12 @@ const FRONTMATTER = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/ export const parseFrontmatter = (markdown: string): Record | undefined => { const block = FRONTMATTER.exec(markdown)?.[1] if (block === undefined) return undefined + const parsed = Yaml.parse(block) + if (Result.isFailure(parsed) || !Predicate.isObject(parsed.success)) return undefined try { - const parsed = Yaml.parse(block) // The frontmatter is listed as JSON, so keep only what JSON carries: // `.inf` and `.nan` become `null`. - return Predicate.isObject(parsed) ? JSON.parse(JSON.stringify(parsed)) : undefined + return JSON.parse(JSON.stringify(parsed.success)) } catch { return undefined } diff --git a/packages/effect/src/cli/Primitive.ts b/packages/effect/src/cli/Primitive.ts index e53f8f644d..221a5c8abd 100644 --- a/packages/effect/src/cli/Primitive.ts +++ b/packages/effect/src/cli/Primitive.ts @@ -698,8 +698,8 @@ const fileParsers: Record unknown> = { ini: (content: string) => Ini.parse(content), json: (content: string) => JSON.parse(content), toml: (content: string) => Result.getOrThrow(Toml.parse(content)), - yml: (content: string) => Yaml.parse(content), - yaml: (content: string) => Yaml.parse(content) + yml: (content: string) => Result.getOrThrow(Yaml.parse(content)), + yaml: (content: string) => Result.getOrThrow(Yaml.parse(content)) } /** diff --git a/packages/effect/src/encoding/Yaml.ts b/packages/effect/src/encoding/Yaml.ts index 04293d5219..e02d1e315f 100644 --- a/packages/effect/src/encoding/Yaml.ts +++ b/packages/effect/src/encoding/Yaml.ts @@ -35,6 +35,9 @@ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +import * as Result from "../Result.ts" +import { EncodingError } from "./EncodingError.ts" + type YamlRecord = Record type Line = { @@ -697,25 +700,7 @@ class YamlParser { } } -/** - * Parses one YAML document into JavaScript values. - * - * **Details** - * - * The core YAML 1.2 scalar schema is used, so booleans, nulls, and numbers are - * decoded while date-like values remain strings. - * - * YAML 1.1 merge keys are always enabled. An unquoted `<<` key merges a - * mapping, or a sequence of mappings, into the enclosing mapping. Explicit - * keys take precedence over merged keys, earlier merge sources over later - * ones, and a mapping may contain only one merge key. Quote the key (`"<<"`) - * to keep it as an ordinary key. - * - * @stability unstable - * @category decoding - * @since 4.0.0 - */ -export const parse = (input: string): unknown => { +const parseDocument = (input: string): unknown => { const source = input.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n") const lines = source.split("\n").map((raw, index): Line => { const indentation = /^( *)/.exec(raw)![1].length @@ -730,3 +715,50 @@ export const parse = (input: string): unknown => { }) return new YamlParser(lines).parse() } + +/** + * Parses one YAML document into JavaScript values. + * + * **Details** + * + * Returns `Result.succeed` with the parsed value, or `Result.fail` with an + * `EncodingError` when the input is not valid YAML or uses an unsupported + * feature. + * + * The core YAML 1.2 scalar schema is used, so booleans, nulls, and numbers are + * decoded while date-like values remain strings. + * + * YAML 1.1 merge keys are always enabled. An unquoted `<<` key merges a + * mapping, or a sequence of mappings, into the enclosing mapping. Explicit + * keys take precedence over merged keys, earlier merge sources over later + * ones, and a mapping may contain only one merge key. Quote the key (`"<<"`) + * to keep it as an ordinary key. + * + * **Example** (Parsing a YAML document) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * import { Yaml } from "effect/encoding" + * + * Yaml.parse("port: 8080") // => Result.succeed({ port: 8080 }) + * Result.isFailure(Yaml.parse("port: [8080")) // => true + * ``` + * + * @stability unstable + * @category decoding + * @since 4.0.0 + */ +export const parse = (input: string): Result.Result => { + try { + return Result.succeed(parseDocument(input)) + } catch (e) { + return Result.fail( + new EncodingError({ + module: "Yaml", + kind: "Decode", + input, + message: e instanceof Error ? e.message : "Invalid input" + }) + ) + } +} diff --git a/packages/effect/test/encoding/Yaml.test.ts b/packages/effect/test/encoding/Yaml.test.ts index e4afc89a83..e77e304212 100644 --- a/packages/effect/test/encoding/Yaml.test.ts +++ b/packages/effect/test/encoding/Yaml.test.ts @@ -1,10 +1,21 @@ import { assert, describe, it } from "@effect/vitest" +import { Result } from "effect" import * as Yaml from "effect/encoding/Yaml" +const parse = (input: string): unknown => Result.getOrThrow(Yaml.parse(input)) + +const failureMessage = (input: string): string => { + const error = Result.getOrThrow(Result.flip(Yaml.parse(input))) + assert.strictEqual(error.kind, "Decode") + assert.strictEqual(error.module, "Yaml") + assert.strictEqual(error.input, input) + return error.message +} + describe("Yaml", () => { it("parses nested block and flow collections", () => { assert.deepStrictEqual( - Yaml.parse(` + parse(` name: effect enabled: true ports: [3000, 3001] @@ -33,7 +44,7 @@ database: it("parses quoted and block scalars", () => { assert.deepStrictEqual( - Yaml.parse(` + parse(` quoted: "line\\nvalue" literal: | first @@ -52,7 +63,7 @@ folded: >- it("preserves paragraph and indentation breaks in folded block scalars", () => { assert.deepStrictEqual( - Yaml.parse(` + parse(` paragraph: >- first @@ -90,7 +101,7 @@ indented: >- ["whitespace-only content", "message: |\n a\n \n b\n", "a\n \nb\n"], ["explicit-indicator leading whitespace", "message: |1\n \n x\n", " \n x\n"] ])("preserves %s", (_, source, expected) => { - assert.deepStrictEqual(Yaml.parse(source), { message: expected }) + assert.deepStrictEqual(parse(source), { message: expected }) }) describe.each(["|", ">"])("block scalar chomping (%s)", (style) => { @@ -103,7 +114,7 @@ indented: >- ["empty keep", "+", "", ""], ["keep with only empty lines", "+", "\n\n", "\n\n"] ])("applies %s before a sibling key", (_, chomp, content, expected) => { - assert.deepStrictEqual(Yaml.parse(`message: ${style}${chomp}\n${content}next: 1\n`), { + assert.deepStrictEqual(parse(`message: ${style}${chomp}\n${content}next: 1\n`), { message: expected, next: 1 }) @@ -115,12 +126,12 @@ indented: >- ["keep without a final line break", "+", " text", "text"], ["keep with trailing empty lines", "+", " text\n\n\n", "text\n\n\n"] ])("applies %s at end-of-input", (_, chomp, content, expected) => { - assert.deepStrictEqual(Yaml.parse(`message: ${style}${chomp}\n${content}`), { message: expected }) + assert.deepStrictEqual(parse(`message: ${style}${chomp}\n${content}`), { message: expected }) }) }) it("parses YAML 1.2.2 example 8.6 (empty scalar chomping)", () => { - assert.deepStrictEqual(Yaml.parse("strip: >-\n\nclip: >\n\nkeep: |+\n\n"), { + assert.deepStrictEqual(parse("strip: >-\n\nclip: >\n\nkeep: |+\n\n"), { strip: "", clip: "", keep: "\n" @@ -128,7 +139,7 @@ indented: >- }) it("preserves kept trailing lines in block sequence entries", () => { - assert.deepStrictEqual(Yaml.parse("- |+\n first\n\n- second\n"), ["first\n\n", "second"]) + assert.deepStrictEqual(parse("- |+\n first\n\n- second\n"), ["first\n\n", "second"]) }) it.each([ @@ -136,19 +147,19 @@ indented: >- [">-", "\n first\n second\n\n", "\nfirst second"], ["|2+", " # text\n\n", " # text\n\n"] ])("ends %s scalars before less-indented comments", (indicator, content, expected) => { - assert.deepStrictEqual(Yaml.parse(`message: ${indicator}\n${content} # outside\nnext: 1\n`), { + assert.deepStrictEqual(parse(`message: ${indicator}\n${content} # outside\nnext: 1\n`), { message: expected, next: 1 }) }) it("rejects less-indented block scalar content", () => { - assert.throws(() => Yaml.parse("message: |\n first\n second\nnext: 1\n"), SyntaxError) + failureMessage("message: |\n first\n second\nnext: 1\n") }) it("resolves aliases", () => { assert.deepStrictEqual( - Yaml.parse(` + parse(` defaults: &defaults host: localhost port: 5432 @@ -163,11 +174,11 @@ development: }) it("rejects invalid indentation", () => { - assert.throws(() => Yaml.parse("root:\n child: true\n sibling: false\n")) + failureMessage("root:\n child: true\n sibling: false\n") }) it("allows tabs on comment and blank lines outside scalars", () => { - assert.deepStrictEqual(Yaml.parse("a: 1\n\t# comment\n\t\nb: 2\n"), { a: 1, b: 2 }) + assert.deepStrictEqual(parse("a: 1\n\t# comment\n\t\nb: 2\n"), { a: 1, b: 2 }) }) it.each([ @@ -177,11 +188,11 @@ development: ["single-quoted continuation", "text: 'a\n\tb'\n"], ["double-quoted continuation", "text: \"a\n\tb\"\n"] ])("rejects tabs in %s", (_, source) => { - assert.throws(() => Yaml.parse(source), /Tabs cannot be used for YAML indentation/) + assert.match(failureMessage(source), /Tabs cannot be used for YAML indentation/) }) it("rejects leading empty lines more indented than the first block content line", () => { - assert.throws(() => Yaml.parse("text: |\n \n \tx\n"), SyntaxError) + failureMessage("text: |\n \n \tx\n") }) // YAML 1.2.2 §8.2.1: a mapping value's block sequence may be indentless. @@ -228,7 +239,7 @@ development: } } ])("parses $name", ({ source, expected }) => { - assert.deepStrictEqual(Yaml.parse(source), expected) + assert.deepStrictEqual(parse(source), expected) }) }) @@ -247,18 +258,18 @@ development: expected: { items: [{ name: "a", age: 1 }, { name: "b", age: 2 }] } } ])("parses $name", ({ source, expected }) => { - assert.deepStrictEqual(Yaml.parse(source), expected) + assert.deepStrictEqual(parse(source), expected) }) it.each([ ["two spaces", "- name: a\n age: 1\n"], ["three spaces", "- name: a\n age: 1\n"] ])("rejects a later key indented by %s", (_, source) => { - assert.throws(() => Yaml.parse(source), SyntaxError) + failureMessage(source) }) it("rejects a tab before the first key", () => { - assert.throws(() => Yaml.parse("- \tname: a\n age: 1\n"), /Tabs cannot be used for YAML indentation/) + assert.match(failureMessage("- \tname: a\n age: 1\n"), /Tabs cannot be used for YAML indentation/) }) }) @@ -317,20 +328,20 @@ development: ["double quote starting a plain continuation", "description: Deploy\n \"it # end\n", "Deploy \"it"], ["bracket and quote inside plain text", "description: plain [ a 'quote # comment\n", "plain [ a 'quote"] ])("folds %s", (_, source, expected) => { - assert.deepStrictEqual(Yaml.parse(source), { description: expected }) + assert.deepStrictEqual(parse(source), { description: expected }) const nested = source.split(/\r?\n/).map((line) => ` ${line}`).join("\n") - assert.deepStrictEqual(Yaml.parse(`metadata:\n${nested}`), { metadata: { description: expected } }) + assert.deepStrictEqual(parse(`metadata:\n${nested}`), { metadata: { description: expected } }) }) it("ends plain scalars at sibling keys after terminating comments", () => { assert.deepStrictEqual( - Yaml.parse("description: Deploy\n and verify. # end\n# between keys\nenabled: true\n"), + parse("description: Deploy\n and verify. # end\n# between keys\nenabled: true\n"), { description: "Deploy and verify.", enabled: true } ) }) it("folds plain sequence items", () => { - assert.deepStrictEqual(Yaml.parse("- Deploy\n and verify.\n- Finish\n"), ["Deploy and verify.", "Finish"]) + assert.deepStrictEqual(parse("- Deploy\n and verify.\n- Finish\n"), ["Deploy and verify.", "Finish"]) }) }) @@ -352,7 +363,7 @@ development: ["multiline plain values", "a: [b\n c, d\n\n e]\n", { a: ["b c", "d\ne"] }] ] as const )("parses %s", (_, source, expected) => { - assert.deepStrictEqual(Yaml.parse(source), expected) + assert.deepStrictEqual(parse(source), expected) }) it.each([ @@ -360,7 +371,7 @@ development: ["unterminated collection before a sibling key", "a: [1,\n 2\nb: 3\n"], ["content after the closing bracket", "a: [1,\n 2] extra\n"] ])("rejects %s", (_, source) => { - assert.throws(() => Yaml.parse(source), SyntaxError) + failureMessage(source) }) }) @@ -382,12 +393,12 @@ development: ["tab-indented scalar", "description:\n\tDeploy\n"], ["duplicate key", "description: first\ndescription: second\n"] ])("rejects %s", (_, source) => { - assert.throws(() => Yaml.parse(source), SyntaxError) + failureMessage(source) }) it("preserves numeric decoding and quoted colon content", () => { assert.deepStrictEqual( - Yaml.parse("description: 123\nquoted: 'Use when: deploy'\ntrailing: \"Deploy:\"\n"), + parse("description: 123\nquoted: 'Use when: deploy'\ntrailing: \"Deploy:\"\n"), { description: 123, quoted: "Use when: deploy", trailing: "Deploy:" } ) }) @@ -408,10 +419,10 @@ development: ["invalid mapping indentation", "broken:\n child: true\n sibling: false\n"], ["duplicate keys", "broken: one\nbroken: two\n"] ])("rejects %s alone and before or after valid shapes", (_, malformed) => { - assert.throws(() => Yaml.parse(malformed), SyntaxError) - for (const [name, source] of shapes) { - assert.throws(() => Yaml.parse(malformed + source), SyntaxError, undefined, `before ${name}`) - assert.throws(() => Yaml.parse(source + malformed), SyntaxError, undefined, `after ${name}`) + failureMessage(malformed) + for (const [, source] of shapes) { + failureMessage(malformed + source) + failureMessage(source + malformed) } }) }) @@ -428,7 +439,7 @@ development: ["single-line nested sequence", "- - 1\n"], ["empty nested entry", "- -\n"] ])("rejects %s", (_, source) => { - assert.throws(() => Yaml.parse(source), SyntaxError) + failureMessage(source) }) it.each( @@ -437,7 +448,7 @@ development: ["sequence item", "- one\n - two\n", ["one - two"]] ] as const )("preserves a dash in a plain continuation of a %s", (_, source, expected) => { - assert.deepStrictEqual(Yaml.parse(source), expected) + assert.deepStrictEqual(parse(source), expected) }) }) @@ -449,8 +460,8 @@ development: ["...", ""], ["...", " # comment"] ])("preserves indented %s%s as a mapping value", (marker, suffix) => { - assert.deepStrictEqual(Yaml.parse(`a:\n ${marker}${suffix}\n`), { a: marker }) - assert.deepStrictEqual(Yaml.parse(`metadata:\n a:\n ${marker}${suffix}\n`), { metadata: { a: marker } }) + assert.deepStrictEqual(parse(`a:\n ${marker}${suffix}\n`), { a: marker }) + assert.deepStrictEqual(parse(`metadata:\n a:\n ${marker}${suffix}\n`), { metadata: { a: marker } }) }) it.each([ @@ -461,7 +472,7 @@ development: ["empty first document", "---\n---\nb: 2\n"], ["empty trailing document", "a: 1\n---\n"] ])("rejects a document stream containing %s", (_, source) => { - assert.throws(() => Yaml.parse(source), SyntaxError) + failureMessage(source) }) it.each( @@ -472,7 +483,7 @@ development: ["empty document", "---\n...\n", null] ] as const )("preserves single-document markers around a %s", (_, source, expected) => { - assert.deepStrictEqual(Yaml.parse(source), expected) + assert.deepStrictEqual(parse(source), expected) }) }) @@ -488,7 +499,7 @@ items: - <<: *base a: 5 ` - const result = Yaml.parse(source) + const result = parse(source) assert.deepStrictEqual(result, { base: { a: 1, b: 2 }, other: { b: 3, c: 4 }, @@ -500,13 +511,13 @@ items: }) it("treats quoted merge keys as ordinary keys", () => { - assert.deepStrictEqual(Yaml.parse("\"<<\": 1\nflow: {'<<': 2}\n"), { "<<": 1, flow: { "<<": 2 } }) + assert.deepStrictEqual(parse("\"<<\": 1\nflow: {'<<': 2}\n"), { "<<": 1, flow: { "<<": 2 } }) }) it.each(["<<: 1\n", "{<<: [{a: 1}, 2]}", "<<: {a: 1}\n<<: {b: 2}\n"])( "rejects invalid merge usage in %j", (source) => { - assert.throws(() => Yaml.parse(source), SyntaxError) + failureMessage(source) } ) }) @@ -525,34 +536,34 @@ items: "Deploy # first # second" ] ])("resolves anchored multiline %s scalars", (_, source, expected) => { - assert.deepStrictEqual(Yaml.parse(source), { description: expected, alias: expected }) + assert.deepStrictEqual(parse(source), { description: expected, alias: expected }) }) it("resolves anchored nested indentless sequences", () => { assert.deepStrictEqual( - Yaml.parse("metadata:\n tools: &tools\n - Read\n - Bash\n alias: *tools\n"), + parse("metadata:\n tools: &tools\n - Read\n - Bash\n alias: *tools\n"), { metadata: { tools: ["Read", "Bash"], alias: ["Read", "Bash"] } } ) }) it("resolves anchors defined inside flow collections", () => { assert.deepStrictEqual( - Yaml.parse("mapping: {a: &value 1, b: *value}\nsequence: [&item one, *item, &empty, *empty]\nalias: *value\n"), + parse("mapping: {a: &value 1, b: *value}\nsequence: [&item one, *item, &empty, *empty]\nalias: *value\n"), { mapping: { a: 1, b: 1 }, sequence: ["one", "one", null, null], alias: 1 } ) }) it.each(["{a: &}", "[&item[1]]", "[&first &second 1]"])("rejects invalid flow anchor %s", (source) => { - assert.throws(() => Yaml.parse(source), SyntaxError) + failureMessage(source) }) it("preserves hashes in JSON-style flow strings without colon spacing", () => { - assert.deepStrictEqual(Yaml.parse("{\"description\":\"Deploy # now\"} # end\n"), { description: "Deploy # now" }) + assert.deepStrictEqual(parse("{\"description\":\"Deploy # now\"} # end\n"), { description: "Deploy # now" }) }) it("preserves hashes in single- and double-quoted flow sequence items", () => { assert.deepStrictEqual( - Yaml.parse("descriptions: [\"Deploy # now\", 'Verify # later'] # end\n"), + parse("descriptions: [\"Deploy # now\", 'Verify # later'] # end\n"), { descriptions: ["Deploy # now", "Verify # later"] } ) }) diff --git a/packages/tools/ai-codegen/test/OpenAiGeneration.test.ts b/packages/tools/ai-codegen/test/OpenAiGeneration.test.ts index c416c014af..466ed29f3f 100644 --- a/packages/tools/ai-codegen/test/OpenAiGeneration.test.ts +++ b/packages/tools/ai-codegen/test/OpenAiGeneration.test.ts @@ -11,6 +11,7 @@ import * as HttpClient from "effect/http/HttpClient" import * as HttpClientResponse from "effect/http/HttpClientResponse" import * as Layer from "effect/Layer" import * as Path from "effect/Path" +import * as Result from "effect/Result" import * as Schema from "effect/Schema" import { gzipSync } from "node:zlib" @@ -277,9 +278,9 @@ const cases: ReadonlyArray = [ const openAiConfig = Effect.gen(function*() { const fs = yield* FileSystem.FileSystem - const config = Schema.decodeUnknownSync(Config.CodegenConfig)(Yaml.parse( + const config = Schema.decodeUnknownSync(Config.CodegenConfig)(Result.getOrThrow(Yaml.parse( yield* fs.readFileString(new URL("../../../ai/openai/codegen.yaml", import.meta.url).pathname) - )) + ))) // Patches addressing individual OpenAI components cannot apply to these fixtures, // but document-level patches (such as the OpenAPI version) still shape generation. const patches = config.patchList.filter((patch) => !patch.includes("\"/components/")) diff --git a/packages/tools/ai-codegen/test/OpenRouterTranscriptions.test.ts b/packages/tools/ai-codegen/test/OpenRouterTranscriptions.test.ts index bf91255d79..f6d734d1e0 100644 --- a/packages/tools/ai-codegen/test/OpenRouterTranscriptions.test.ts +++ b/packages/tools/ai-codegen/test/OpenRouterTranscriptions.test.ts @@ -6,6 +6,7 @@ import * as Effect from "effect/Effect" import * as Yaml from "effect/encoding/Yaml" import * as FileSystem from "effect/FileSystem" import * as Layer from "effect/Layer" +import * as Result from "effect/Result" import * as Schema from "effect/Schema" const operation = (operationId: string) => ({ @@ -29,9 +30,9 @@ describe("OpenRouter transcription spec patch", () => { Effect.gen(function*() { const fs = yield* FileSystem.FileSystem const generator = yield* Generator.CodeGenerator - const config = Schema.decodeUnknownSync(Config.CodegenConfig)(Yaml.parse( + const config = Schema.decodeUnknownSync(Config.CodegenConfig)(Result.getOrThrow(Yaml.parse( yield* fs.readFileString(new URL("../../../ai/openrouter/codegen.yml", import.meta.url).pathname) - )) + ))) const patches = config.patchList.filter((patch) => patch.includes("/paths/~1audio~1transcriptions/")) assert.strictEqual(patches.length, 1) const generate = (patches: ReadonlyArray) => diff --git a/packages/tools/openapi-generator/src/OpenApiPatch.ts b/packages/tools/openapi-generator/src/OpenApiPatch.ts index 312476687c..7f44612367 100644 --- a/packages/tools/openapi-generator/src/OpenApiPatch.ts +++ b/packages/tools/openapi-generator/src/OpenApiPatch.ts @@ -18,6 +18,7 @@ import * as JsonPatch from "effect/JsonPatch" import * as JsonPointer from "effect/JsonPointer" import * as Path from "effect/Path" import * as Predicate from "effect/Predicate" +import * as Result from "effect/Result" import * as Schema from "effect/Schema" // ============================================================================= @@ -410,14 +411,9 @@ const parseJsonContent = Effect.fnUntraced(function*(content: string, source: st * Parse content as YAML. */ const parseYamlContent = Effect.fnUntraced(function*(content: string, source: string) { - return yield* Effect.try({ - try: () => Yaml.parse(content) as unknown, - catch: (error) => - new JsonPatchParseError({ - source, - reason: error instanceof Error ? error.message : String(error) - }) - }) + return yield* Effect.fromResult( + Result.mapError(Yaml.parse(content), (error) => new JsonPatchParseError({ source, reason: error.message })) + ) }) /** From 9eb8d2ae5c86bceed850e26b65ceafb18f17ffd8 Mon Sep 17 00:00:00 2001 From: effect-bot <129879685+effect-bot@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:59:17 +0100 Subject: [PATCH 09/15] Document per-signal opt-in for OTLP layerFromConfig (#10269) --- packages/effect/src/observability/Otlp.ts | 12 +++++++++++ .../effect/src/observability/OtlpLogger.ts | 6 ++++++ .../effect/src/observability/OtlpMetrics.ts | 6 ++++++ .../effect/src/observability/OtlpTracer.ts | 6 ++++++ .../test/observability/OtlpConfig.test.ts | 20 +++++++++++++++++++ .../test/observability/OtlpExporter.test.ts | 1 + 6 files changed, 51 insertions(+) diff --git a/packages/effect/src/observability/Otlp.ts b/packages/effect/src/observability/Otlp.ts index 83505a9b8e..e37a983242 100644 --- a/packages/effect/src/observability/Otlp.ts +++ b/packages/effect/src/observability/Otlp.ts @@ -112,6 +112,18 @@ export const layer = (options: { * * **Details** * + * Each signal is exported only when an endpoint is set and its own exporter + * variable includes `otlp`. Unlike the OpenTelemetry SDK specification, the + * exporter variables have no default, so an endpoint alone exports nothing. + * To export all three signals: + * + * ```sh + * export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 + * export OTEL_TRACES_EXPORTER=otlp + * export OTEL_METRICS_EXPORTER=otlp + * export OTEL_LOGS_EXPORTER=otlp + * ``` + * * The layer provides the `OtlpExporter.Flusher` shared by all enabled signals. * It is provided even when configuration disables every signal, in which case * `flush` is a no-op. diff --git a/packages/effect/src/observability/OtlpLogger.ts b/packages/effect/src/observability/OtlpLogger.ts index 0eff0f64e4..d2796eb290 100644 --- a/packages/effect/src/observability/OtlpLogger.ts +++ b/packages/effect/src/observability/OtlpLogger.ts @@ -144,6 +144,12 @@ export const layer = (options: { * * **Details** * + * Logs are exported only when an endpoint is set, through + * `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT`, and + * `OTEL_LOGS_EXPORTER` includes `otlp`. Unlike the OpenTelemetry SDK + * specification, `OTEL_LOGS_EXPORTER` has no default, so leaving it unset + * disables logs. + * * Compression accepts "gzip" or "none". * `OTEL_EXPORTER_OTLP_LOGS_COMPRESSION` takes precedence over * `OTEL_EXPORTER_OTLP_COMPRESSION`, defaulting to "none". Gzip uses diff --git a/packages/effect/src/observability/OtlpMetrics.ts b/packages/effect/src/observability/OtlpMetrics.ts index b1dbaff5b6..892a89df50 100644 --- a/packages/effect/src/observability/OtlpMetrics.ts +++ b/packages/effect/src/observability/OtlpMetrics.ts @@ -434,6 +434,12 @@ export const layer = (options: { * * **Details** * + * Metrics are exported only when an endpoint is set, through + * `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT`, and + * `OTEL_METRICS_EXPORTER` includes `otlp`. Unlike the OpenTelemetry SDK + * specification, `OTEL_METRICS_EXPORTER` has no default, so leaving it unset + * disables metrics. + * * Compression accepts "gzip" or "none". * `OTEL_EXPORTER_OTLP_METRICS_COMPRESSION` takes precedence over * `OTEL_EXPORTER_OTLP_COMPRESSION`, defaulting to "none". Gzip uses diff --git a/packages/effect/src/observability/OtlpTracer.ts b/packages/effect/src/observability/OtlpTracer.ts index 4b3b32d9e5..18c6fad46d 100644 --- a/packages/effect/src/observability/OtlpTracer.ts +++ b/packages/effect/src/observability/OtlpTracer.ts @@ -199,6 +199,12 @@ export const layer: (options: { * * **Details** * + * Traces are exported only when an endpoint is set, through + * `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT`, and + * `OTEL_TRACES_EXPORTER` includes `otlp`. Unlike the OpenTelemetry SDK + * specification, `OTEL_TRACES_EXPORTER` has no default, so leaving it unset + * disables traces. + * * Compression accepts "gzip" or "none". * `OTEL_EXPORTER_OTLP_TRACES_COMPRESSION` takes precedence over * `OTEL_EXPORTER_OTLP_COMPRESSION`, defaulting to "none". Gzip uses diff --git a/packages/effect/test/observability/OtlpConfig.test.ts b/packages/effect/test/observability/OtlpConfig.test.ts index 1e84c8e77b..2bac10cbf7 100644 --- a/packages/effect/test/observability/OtlpConfig.test.ts +++ b/packages/effect/test/observability/OtlpConfig.test.ts @@ -72,6 +72,26 @@ describe("Otlp.layerFromConfig", () => { OTEL_METRIC_EXPORT_INTERVAL: "1000" })) )) + + it.effect("does not install exporters when only the endpoint is set", () => + Effect.gen(function*() { + yield* Effect.log("endpoint-only log") + yield* Metric.update(Metric.counter("otel_endpoint_only_counter"), 1) + yield* Effect.void.pipe(Effect.withSpan("endpoint-only-span")) + + yield* TestClock.adjust("1 second") + + const requests = yield* MockHttpClient.requests + assert.deepStrictEqual(requests, []) + }).pipe( + Effect.provide(testLayer({ + OTEL_SERVICE_NAME: "otel-config-test", + OTEL_EXPORTER_OTLP_ENDPOINT: "http://collector.example", + OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: "1", + OTEL_BSP_MAX_EXPORT_BATCH_SIZE: "1", + OTEL_METRIC_EXPORT_INTERVAL: "1000" + })) + )) }) interface CapturedRequest { diff --git a/packages/effect/test/observability/OtlpExporter.test.ts b/packages/effect/test/observability/OtlpExporter.test.ts index 05a8b4e0ac..db4b6c01de 100644 --- a/packages/effect/test/observability/OtlpExporter.test.ts +++ b/packages/effect/test/observability/OtlpExporter.test.ts @@ -630,6 +630,7 @@ describe("OtlpExporter", () => { yield* Effect.gen(function*() { yield* Effect.log("flush test") yield* Metric.update(Metric.counter("otlp_flush_test"), 1) + yield* Effect.void.pipe(Effect.withSpan("flush test")) yield* (yield* OtlpExporter.Flusher).flush assert.deepStrictEqual( From a5745e2ff060efad2a900b4d2548c6408b11c9da Mon Sep 17 00:00:00 2001 From: Harry Solovay <4893548+harrysolovay@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:12:23 -0500 Subject: [PATCH 10/15] Add String.hasNonWhitespace predicate (#10341) Co-authored-by: Effect Bot --- .changeset/string-has-non-whitespace.md | 5 +++++ packages/effect/src/String.ts | 25 +++++++++++++++++++++++++ packages/effect/test/String.test.ts | 11 +++++++++++ 3 files changed, 41 insertions(+) create mode 100644 .changeset/string-has-non-whitespace.md diff --git a/.changeset/string-has-non-whitespace.md b/.changeset/string-has-non-whitespace.md new file mode 100644 index 0000000000..c3f6785253 --- /dev/null +++ b/.changeset/string-has-non-whitespace.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +Add `String.hasNonWhitespace`, which checks whether a string contains at least one non-whitespace character. diff --git a/packages/effect/src/String.ts b/packages/effect/src/String.ts index 9895d0e813..c2b82ee65a 100644 --- a/packages/effect/src/String.ts +++ b/packages/effect/src/String.ts @@ -432,6 +432,31 @@ export const isEmpty = (self: string): self is "" => self.length === 0 */ export const isNonEmpty = (self: string): boolean => self.length > 0 +/** + * Checks whether a string contains at least one non-whitespace character. + * + * **Details** + * + * Uses JavaScript whitespace semantics, matching `trim`. Empty strings and + * whitespace-only strings return `false`; the input is not modified. + * + * **Example** (Checking for non-whitespace characters) + * + * ```ts import.meta.vitest + * import { String } from "effect" + * + * String.hasNonWhitespace("hello") // => true + * String.hasNonWhitespace(" hello ") // => true + * String.hasNonWhitespace("") // => false + * String.hasNonWhitespace(" \t\n") // => false + * ``` + * + * @stability stable + * @category predicates + * @since 4.2.0 + */ +export const hasNonWhitespace = (self: string): boolean => /\S/u.test(self) + /** * Returns the JavaScript string length, measured in UTF-16 code units. * diff --git a/packages/effect/test/String.test.ts b/packages/effect/test/String.test.ts index 9f644412b4..386b80604e 100644 --- a/packages/effect/test/String.test.ts +++ b/packages/effect/test/String.test.ts @@ -179,6 +179,17 @@ describe("String", () => { }) }) + describe("hasNonWhitespace", () => { + it("requires a character that trim does not remove", () => { + assertFalse(S.hasNonWhitespace("")) + assertFalse(S.hasNonWhitespace(" \t\n\r\v\f")) + assertFalse(S.hasNonWhitespace("\u00a0\u1680\u2000\u2028\u2029\u202f\u205f\u3000\ufeff")) + assertTrue(S.hasNonWhitespace(" a ")) + assertTrue(S.hasNonWhitespace("\u200b")) + assertTrue(S.hasNonWhitespace("\u0085")) + }) + }) + describe("isEmpty", () => { it("returns true for empty string", () => { assertTrue(S.isEmpty("")) From 9bb0d233e7127a2c72fea44477da39ea9213ce18 Mon Sep 17 00:00:00 2001 From: effect-bot <129879685+effect-bot@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:36:48 +0100 Subject: [PATCH 11/15] Add Yaml.parseAll and return Result from Yaml.parse (#10271) --- .changeset/yaml-document-streams.md | 7 + packages/effect/src/encoding/Yaml.ts | 289 +++++++++++++++------ packages/effect/test/encoding/Yaml.test.ts | 103 +++++++- 3 files changed, 313 insertions(+), 86 deletions(-) create mode 100644 .changeset/yaml-document-streams.md diff --git a/.changeset/yaml-document-streams.md b/.changeset/yaml-document-streams.md new file mode 100644 index 0000000000..7b90254679 --- /dev/null +++ b/.changeset/yaml-document-streams.md @@ -0,0 +1,7 @@ +--- +"effect": minor +--- + +Add `Yaml.parseAll` for YAML document streams, with anchors scoped to each document and support for the `%YAML 1.2` directive. + +`Yaml.parse` now fails on input it used to misread instead of skipping or dropping it: `%YAML` versions other than 1.2, `%TAG` and other directives, a directive without a following `---`, and plain scalars starting with `%`. Input with more than one document still fails, with a message pointing to `Yaml.parseAll`. diff --git a/packages/effect/src/encoding/Yaml.ts b/packages/effect/src/encoding/Yaml.ts index e02d1e315f..5e932a0f53 100644 --- a/packages/effect/src/encoding/Yaml.ts +++ b/packages/effect/src/encoding/Yaml.ts @@ -2,16 +2,17 @@ * Parses YAML configuration files. * * Supports YAML 1.2 block and flow collections, indentless sequence values, - * multiline plain and quoted scalars, block scalars, anchors, aliases, and - * YAML 1.1 merge keys (`<<`). + * multiline plain and quoted scalars, block scalars, anchors, aliases, YAML 1.1 + * merge keys (`<<`), document streams, and the `%YAML 1.2` directive. Parsing + * returns a `Result` that fails with an `EncodingError`. * * Unlike YAML 1.2, the closing bracket of a multiline flow collection may sit * at its parent's indentation. * * Unsupported: compact nested block sequences (`- - value` on one line), - * multiline quoted scalars in flow collections, explicit complex keys, - * tag/directive processing, recursive aliases, and document streams. Mapping - * keys are JavaScript strings. + * multiline quoted scalars in flow collections, explicit complex keys, tags, + * `%TAG` and other directives, YAML versions other than 1.2, and recursive + * aliases. Mapping keys are JavaScript strings. * * @stability unstable * @since 4.0.0 @@ -141,6 +142,14 @@ const mappingSeparator = (input: string): number => findIndicator(input, ":") const isSequenceEntry = (text: string): boolean => text === "-" || text.startsWith("- ") +// YAML 1.2.2 §9.1: document markers start at column zero and are followed by whitespace. +const isDocumentMarker = (line: Line): boolean => line.indent === 0 && /^(?:---|\.\.\.)(?:[ \t]|$)/.test(line.raw) + +const isDocumentStart = (line: Line): boolean => isDocumentMarker(line) && line.raw.startsWith("---") + +// YAML 1.2.2 §5.3: `%` is the directive indicator and cannot start a plain scalar. +const directiveIndicatorError = "Plain scalars cannot start with '%'" + const foldLineBreak = (blankLines: number): string => blankLines === 0 ? " " : "\n".repeat(blankLines) // Folds the line breaks of a multiline plain flow scalar. @@ -296,7 +305,9 @@ class FlowParser { this.anchors.set(name, value) return value } - return parseScalar(foldFlowLines(this.readUntil(/[,\]}]/)).trim()) + const text = foldFlowLines(this.readUntil(/[,\]}]/)).trim() + if (text.startsWith("%")) this.fail(directiveIndicatorError) + return parseScalar(text) } private parseSequence(): Array { @@ -360,7 +371,9 @@ class FlowParser { if (character === "\"" || character === "'") { return parseKey(this.readQuoted(character)) } - return foldFlowLines(this.readUntil(/:/)).trim() + const key = foldFlowLines(this.readUntil(/:/)).trim() + if (key.startsWith("%")) this.fail(directiveIndicatorError) + return key } private readQuoted(quote: string): string { @@ -400,31 +413,135 @@ class FlowParser { } } -class YamlParser { - private readonly lines: ReadonlyArray - private index = 0 - private documentStarted = false - private readonly anchors = new Map() +const makeLine = (raw: string, number: number): Line => { + const indentation = /^( *)/.exec(raw)![1].length + return { + raw, + text: stripComment(raw.slice(indentation)), + indent: indentation, + number, + // Rejected where the line is read as structure; block scalar content may hold tabs. + tabIndent: raw[indentation] === "\t" + } +} - constructor(lines: ReadonlyArray) { +// YAML separates tokens with spaces and tabs only, unlike `String.prototype.trimEnd`. +const trimSeparation = (text: string): string => text.replace(/[ \t]+$/, "") + +// Removes the comment from a marker or directive line, keeping characters before +// it that are not YAML separation so they can be rejected. +const boundaryContent = (raw: string): string => { + const index = findIndicator(raw, "#") + return trimSeparation(index === -1 ? raw : raw.slice(0, index)) +} + +class YamlParser { + private readonly lines: Array + private index = 0 + // Lines from this index on belong to the next document, so document content + // never reads past a document marker. + private documentEnd: number + // Anchors are scoped to one document. + private anchors = new Map() + + constructor(lines: Array) { this.lines = lines + this.documentEnd = lines.length } - parse(): unknown { - this.skipIgnored() - if (this.index >= this.lines.length) return null - this.documentStarted = true - const value = this.parseNode(this.lines[this.index].indent) - this.skipIgnored() - if (this.index < this.lines.length) { - this.fail(this.lines[this.index], "Unexpected content") + private lineAt(index: number): Line | undefined { + return index < this.documentEnd ? this.lines[index] : undefined + } + + // YAML 1.2.2 §9.2. `limit` stops with an error before a document past it starts. + parseStream(limit = Number.POSITIVE_INFINITY): Array { + const documents: Array = [] + // True at the start of the stream and after a document end marker, where directives and bare documents may start. + let prefix = true + while (true) { + this.skipIgnored() + const line = this.lines[this.index] + if (line === undefined) return documents + // YAML 1.2.2 §9.1.1: a byte order mark may start any document prefix. + if (prefix && line.raw.startsWith("\uFEFF")) { + this.lines[this.index] = makeLine(line.raw.slice(1), line.number) + continue + } + if (isDocumentMarker(line) && !isDocumentStart(line)) { + if (boundaryContent(line.raw) !== "...") this.fail(line, "Unexpected content after document end marker") + this.index++ + prefix = true + continue + } + if (!prefix && !isDocumentStart(line)) this.fail(line, "Unexpected content") + if (documents.length >= limit) { + this.fail(line, "Expected a single YAML document, use parseAll to parse a document stream") + } + if (prefix && line.indent === 0 && line.text.startsWith("%")) this.parseDirectives() + this.anchors = new Map() + documents.push(this.parseDocument()) + prefix = false } + } + + // YAML 1.2.2 §6.8: only `%YAML 1.2` is supported, and directives must be followed by `---`. + private parseDirectives(): void { + let version = false + while (true) { + this.skipIgnored() + const line = this.lines[this.index] + if (line === undefined || line.indent !== 0 || !line.text.startsWith("%")) break + const [name, ...parameters] = boundaryContent(line.raw.slice(1)).split(/[ \t]+/) + if (name === "YAML") { + if (version) this.fail(line, "Duplicate %YAML directive") + if (parameters.length !== 1 || parameters[0] !== "1.2") { + this.fail(line, `Unsupported YAML version '${parameters.join(" ")}', only 1.2 is supported`) + } + version = true + } else { + this.fail(line, `Unsupported YAML directive '%${name}'`) + } + this.index++ + } + const next = this.lines[this.index] + if (next === undefined || !isDocumentStart(next)) { + this.fail(next ?? this.lines[this.index - 1], "Expected '---' after YAML directives") + } + } + + private parseDocument(): unknown { + const start = this.lines[this.index] + if (isDocumentStart(start)) this.index++ + // Scanning forward from the current line keeps a stream of many documents linear. + let end = this.index + while (end < this.lines.length && !isDocumentMarker(this.lines[end])) end++ + this.documentEnd = end + const value = this.parseDocumentContent(start) + this.documentEnd = this.lines.length return value } + private parseDocumentContent(start: Line): unknown { + if (isDocumentStart(start)) { + // Strip the comment after the marker, so quotes and flow openers are read as token starts. + const content = stripComment(start.raw.slice(3).replace(/^[ \t]+/, "")) + if (content.length > 0) { + // Block collections start on the line after the marker. + if (isSequenceEntry(content) || mappingSeparator(content) !== -1) { + this.fail(start, "Block collections cannot start on the document start line") + } + return this.parseNodeValue(content, -1) + } + } + this.skipIgnored() + const line = this.lineAt(this.index) + if (line === undefined) return null + return this.parseNode(line.indent) + } + private parseNode(indent: number, parentIndent = indent - 1): unknown { this.skipIgnored() - const line = this.lines[this.index] + const line = this.lineAt(this.index) if (line === undefined) return null if (line.indent !== indent) this.fail(line, `Expected indentation of ${indent} spaces`) if (isSequenceEntry(line.text)) return this.parseSequence(indent) @@ -436,7 +553,7 @@ class YamlParser { private parseMapping(indent: number, mapping = new MappingBuilder()): YamlRecord { while (true) { this.skipIgnored() - const line = this.lines[this.index] + const line = this.lineAt(this.index) if (line === undefined || line.indent < indent) return mapping.output if (line.indent > indent) this.fail(line, `Unexpected indentation of ${line.indent} spaces`) const separator = mappingSeparator(line.text) @@ -454,6 +571,7 @@ class YamlParser { line: Line ): void { const rawKey = text.slice(0, separator).trim() + if (rawKey.startsWith("%")) this.fail(line, directiveIndicatorError) const rawValue = text.slice(separator + 1).trimStart() const value = this.parseNodeValue(rawValue, indent, true) const fail = (message: string) => this.fail(line, message) @@ -465,7 +583,7 @@ class YamlParser { const output: Array = [] while (true) { this.skipIgnored() - const line = this.lines[this.index] + const line = this.lineAt(this.index) if (line === undefined || line.indent < indent) return output if (line.indent > indent) this.fail(line, `Unexpected indentation of ${line.indent} spaces`) if (!isSequenceEntry(line.text)) return output @@ -499,7 +617,7 @@ class YamlParser { const text = value.trimEnd() if (text.length === 0) { this.skipIgnored() - const next = this.lines[this.index] + const next = this.lineAt(this.index) if (next === undefined) return null if (next.indent > parentIndent) return this.parseNode(next.indent, parentIndent) if (allowIndentless && next.indent === parentIndent && isSequenceEntry(next.text)) { @@ -521,8 +639,8 @@ class YamlParser { private parseFlowValue(text: string, parentIndent: number): unknown { return new FlowParser(text, this.anchors, (depth) => { - const next = this.lines[this.index] - if (next === undefined || (next.indent === 0 && /^(?:---|\.\.\.)(?:\s|$)/.test(next.text))) return undefined + const next = this.lineAt(this.index) + if (next === undefined) return undefined // Continuation lines are more indented than the parent; a closing bracket may sit at its indentation. const content = next.text.trim().length > 0 if (content && next.indent < parentIndent) return undefined @@ -536,18 +654,19 @@ class YamlParser { private parsePlainValue(value: string, parentIndent: number): unknown { const first = this.lines[this.index - 1] if (/:(?:\s|$)/.test(value)) this.fail(first, "Invalid colon in plain scalar") + if (value.startsWith("%")) this.fail(first, directiveIndicatorError) let output = value let terminated = findIndicator(first.raw, "#") !== -1 while (!terminated) { const blankLines = this.skipBlankLines() - const next = this.lines[this.index] + const next = this.lineAt(this.index) if (next === undefined || next.indent <= parentIndent) break this.rejectTabIndent(next) // Quotes in plain continuations are literal. const content = next.raw.slice(next.indent) const comment = content.search(/(?:^|[ \t])#/) const text = (comment === -1 ? content : content.slice(0, comment)).trimEnd() - if (text.length === 0 || (next.indent === 0 && /^(?:---|\.\.\.)(?:\s|$)/.test(text))) break + if (text.length === 0) break if (/:(?:\s|$)/.test(text)) this.fail(next, "Invalid colon in plain scalar") this.rejectTabIndentedBlankLines(blankLines, parentIndent) output += foldLineBreak(blankLines) + text @@ -577,7 +696,7 @@ class YamlParser { this.rejectTabIndentedBlankLines(blankLines, parentIndent) output += trimFoldedEnd(line, quote) + foldLineBreak(blankLines) } - const next = this.lines[this.index++] + const next = this.lineAt(this.index++) if (next === undefined) throw new SyntaxError("Unterminated quoted YAML scalar") this.rejectTabIndent(next) if (next.raw.trim().length > 0 && next.indent <= parentIndent) { @@ -596,7 +715,7 @@ class YamlParser { let contentIndent = Number.isNaN(explicitIndent) ? undefined : parentIndent + explicitIndent let hasContent = false - while (end < this.lines.length) { + while (end < this.documentEnd) { const line = this.lines[end] // Only spaces make a line empty; a tab after the indentation is content. if (/[^ ]/.test(line.raw)) { @@ -668,26 +787,15 @@ class YamlParser { private skipBlankLines(): number { const start = this.index - while (this.index < this.lines.length && this.lines[this.index].raw.trim().length === 0) this.index++ + while (this.lineAt(this.index)?.raw.trim().length === 0) this.index++ return this.index - start } private skipIgnored(): void { - while (this.index < this.lines.length) { + while (this.index < this.documentEnd) { const line = this.lines[this.index] - const text = line.text.trimEnd() - if (text.length === 0 || text.startsWith("%")) { + if (line.text.trimEnd().length === 0) { this.index++ - } else if (line.indent === 0 && text === "---") { - if (this.documentStarted) this.fail(line, "Multiple YAML documents are not supported") - this.documentStarted = true - this.index++ - } else if (line.indent === 0 && text === "...") { - this.index++ - while (this.index < this.lines.length && this.lines[this.index].text.trimEnd().length === 0) this.index++ - if (this.index < this.lines.length) { - this.fail(this.lines[this.index], "Multiple YAML documents are not supported") - } } else { this.rejectTabIndent(line) return @@ -700,33 +808,36 @@ class YamlParser { } } -const parseDocument = (input: string): unknown => { - const source = input.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n") - const lines = source.split("\n").map((raw, index): Line => { - const indentation = /^( *)/.exec(raw)![1].length - return { - raw, - text: stripComment(raw.slice(indentation)), - indent: indentation, - number: index + 1, - // Rejected where the line is read as structure; block scalar content may hold tabs. - tabIndent: raw[indentation] === "\t" - } - }) - return new YamlParser(lines).parse() +const decode = (input: string, f: (parser: YamlParser) => A): Result.Result => { + try { + const lines = input.replace(/\r\n?/g, "\n").split("\n").map((raw, index) => makeLine(raw, index + 1)) + return Result.succeed(f(new YamlParser(lines))) + } catch (e) { + return Result.fail( + new EncodingError({ + module: "Yaml", + kind: "Decode", + input, + message: e instanceof Error ? e.message : "Invalid input" + }) + ) + } } /** - * Parses one YAML document into JavaScript values. + * Parses a single YAML document into JavaScript values. * * **Details** * * Returns `Result.succeed` with the parsed value, or `Result.fail` with an * `EncodingError` when the input is not valid YAML or uses an unsupported - * feature. + * feature. Empty input, or input holding only comments, parses to `null`. + * Input holding more than one document fails; use {@link parseAll} for + * document streams. * * The core YAML 1.2 scalar schema is used, so booleans, nulls, and numbers are - * decoded while date-like values remain strings. + * decoded while date-like values remain strings. Numbers use JavaScript number + * semantics, so integers beyond `Number.MAX_SAFE_INTEGER` lose precision. * * YAML 1.1 merge keys are always enabled. An unquoted `<<` key merges a * mapping, or a sequence of mappings, into the enclosing mapping. Explicit @@ -742,23 +853,49 @@ const parseDocument = (input: string): unknown => { * * Yaml.parse("port: 8080") // => Result.succeed({ port: 8080 }) * Result.isFailure(Yaml.parse("port: [8080")) // => true + * Result.isFailure(Yaml.parse("a: 1\n---\nb: 2")) // => true + * ``` + * + * @see {@link parseAll} for parsing a stream of documents + * + * @stability unstable + * @category decoding + * @since 4.0.0 + */ +export const parse = (input: string): Result.Result => + decode(input, (parser) => parser.parseStream(1)[0] ?? null) + +/** + * Parses a YAML stream into one JavaScript value per document. + * + * **Details** + * + * Returns `Result.succeed` with the parsed documents, or `Result.fail` with an + * `EncodingError` when any document is invalid. Documents are separated by + * `---` and `...` markers at the start of a line. An empty document parses to + * `null`, and input holding no documents parses to an empty array. Anchors + * are scoped to the document that defines them. + * + * A document may be preceded by a `%YAML 1.2` directive, which must be + * followed by `---`. Other YAML versions and other directives, including + * `%TAG`, fail. + * + * Each document is parsed like {@link parse}. + * + * **Example** (Parsing a document stream) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * import { Yaml } from "effect/encoding" + * + * Yaml.parseAll("a: 1\n---\nb: 2\n") // => Result.succeed([{ a: 1 }, { b: 2 }]) + * Yaml.parseAll("") // => Result.succeed([]) + * Result.isFailure(Yaml.parseAll("%YAML 1.1\n---\na: yes\n")) // => true * ``` * * @stability unstable * @category decoding * @since 4.0.0 */ -export const parse = (input: string): Result.Result => { - try { - return Result.succeed(parseDocument(input)) - } catch (e) { - return Result.fail( - new EncodingError({ - module: "Yaml", - kind: "Decode", - input, - message: e instanceof Error ? e.message : "Invalid input" - }) - ) - } -} +export const parseAll = (input: string): Result.Result, EncodingError> => + decode(input, (parser) => parser.parseStream()) diff --git a/packages/effect/test/encoding/Yaml.test.ts b/packages/effect/test/encoding/Yaml.test.ts index e77e304212..da38cf8fd8 100644 --- a/packages/effect/test/encoding/Yaml.test.ts +++ b/packages/effect/test/encoding/Yaml.test.ts @@ -4,8 +4,10 @@ import * as Yaml from "effect/encoding/Yaml" const parse = (input: string): unknown => Result.getOrThrow(Yaml.parse(input)) -const failureMessage = (input: string): string => { - const error = Result.getOrThrow(Result.flip(Yaml.parse(input))) +const parseAll = (input: string): unknown => Result.getOrThrow(Yaml.parseAll(input)) + +const failureMessage = (input: string, decode: typeof Yaml.parse | typeof Yaml.parseAll = Yaml.parse): string => { + const error = Result.getOrThrow(Result.flip(decode(input))) assert.strictEqual(error.kind, "Decode") assert.strictEqual(error.module, "Yaml") assert.strictEqual(error.input, input) @@ -464,15 +466,94 @@ development: assert.deepStrictEqual(parse(`metadata:\n a:\n ${marker}${suffix}\n`), { metadata: { a: marker } }) }) + // YAML 1.2.2 §9.2: a stream holds any number of documents. Expected values were checked with yaml 2.9.1. + it.each( + [ + ["mappings", "a: 1\n---\nb: 2\n", [{ a: 1 }, { b: 2 }]], + ["sequences", "- one\n---\n- two\n", [["one"], ["two"]]], + ["plain scalars", "one\n---\ntwo\n", ["one", "two"]], + ["explicit initial marker", "---\na: 1\n--- # second document\nb: 2\n", [{ a: 1 }, { b: 2 }]], + ["empty first document", "---\n---\nb: 2\n", [null, { b: 2 }]], + ["empty trailing document", "a: 1\n---\n", [{ a: 1 }, null]], + ["end marker before a start marker", "a: 1\n...\n---\nb: 2\n", [{ a: 1 }, { b: 2 }]], + ["bare document after an end marker", "a: 1\n...\nb: 2\n", [{ a: 1 }, { b: 2 }]], + ["content on start marker lines", "--- a\n--- [1, 2]\n--- &x {b: 1}\n", ["a", [1, 2], { b: 1 }]], + ["start marker content after a mapping", "a: 1\n--- {b: 2}\n--- \"x: y\"\n", [{ a: 1 }, { b: 2 }, "x: y"]], + ["an anchored empty document", "--- &a\n--- b\n", [null, "b"]], + [ + "quoted hashes on start marker lines", + "--- \"a # b\"\n--- 'a # b'\n--- [\"a # b\"]\n", + ["a # b", "a # b", ["a # b"]] + ], + [ + "separation whitespace after markers and directives", + "a: 1\n... \t\n%YAML\t1.2 \n---\nb: 2\n", + [{ a: 1 }, { b: 2 }] + ], + ["byte order marks in document prefixes", "1\n...\n\uFEFF---\n2\n...\n\uFEFF%YAML 1.2\n---\n3\n", [1, 2, 3]] + ] as const + )("parses a stream of %s with parseAll and rejects it in parse", (_, source, expected) => { + assert.deepStrictEqual(parseAll(source), expected) + assert.match(failureMessage(source), /parseAll/) + }) + it.each([ - ["mappings", "a: 1\n---\nb: 2\n"], - ["sequences", "- one\n---\n- two\n"], - ["plain scalars", "one\n---\ntwo\n"], - ["explicit initial marker", "---\na: 1\n--- # second document\nb: 2\n"], - ["empty first document", "---\n---\nb: 2\n"], - ["empty trailing document", "a: 1\n---\n"] - ])("rejects a document stream containing %s", (_, source) => { + ["empty input", ""], + ["comment-only input", "# comment\n\n"] + ])("parses %s as an empty stream", (_, source) => { + assert.deepStrictEqual(parseAll(source), []) + }) + + // yaml 2.9.1 reports an extra empty document for example 9.3; the expected values follow the spec. + it.each( + [ + [ + "2.7", + "# Ranking of 1998 home runs\n---\n- Mark McGwire\n- Sammy Sosa\n- Ken Griffey\n\n# Team ranking\n---\n- Chicago Cubs\n- St Louis Cardinals\n", + [["Mark McGwire", "Sammy Sosa", "Ken Griffey"], ["Chicago Cubs", "St Louis Cardinals"]] + ], + [ + "2.8", + "---\ntime: 20:03:20\nplayer: Sammy Sosa\naction: strike (miss)\n...\n---\ntime: 20:03:47\nplayer: Sammy Sosa\naction: grand slam\n...\n", + [ + { time: "20:03:20", player: "Sammy Sosa", action: "strike (miss)" }, + { time: "20:03:47", player: "Sammy Sosa", action: "grand slam" } + ] + ], + ["9.2", "%YAML 1.2\n---\nDocument\n... # Suffix\n", ["Document"]], + [ + "9.3", + "Bare\ndocument\n...\n# No document\n...\n|\n%!PS-Adobe-2.0 # Not the first line\n", + ["Bare document", "%!PS-Adobe-2.0 # Not the first line\n"] + ], + ["9.4", "---\n{ matches\n% : 20 }\n...\n---\n# Empty\n...\n", [{ "matches %": 20 }, null]], + ["9.5", "%YAML 1.2\n--- |\n%!PS-Adobe-2.0\n...\n%YAML 1.2\n---\n# Empty\n...\n", ["%!PS-Adobe-2.0\n", null]], + ["9.6", "Document\n---\n# Empty\n...\n%YAML 1.2\n---\nmatches %: 20\n", ["Document", null, { "matches %": 20 }]] + ] as const + )("parses YAML 1.2.2 example %s with parseAll", (_, source, expected) => { + assert.deepStrictEqual(parseAll(source), expected) + }) + + it("scopes anchors to their document", () => { + assert.deepStrictEqual(parseAll("a: &x 1\nb: *x\n---\nc: &x 2\nd: *x\n"), [{ a: 1, b: 1 }, { c: 2, d: 2 }]) + assert.match(failureMessage("a: &x 1\n---\nb: *x\n", Yaml.parseAll), /alias/) + }) + + // YAML 1.2.2 §§6.8 and 9.2: only %YAML 1.2 is processed, and directives must precede a start marker. + it.each([ + ["a directive without a start marker", "%YAML 1.2\na: 1\n"], + ["a directive after a bare document", "a: 1\n%YAML 1.2\n---\nb: 2\n"], + ["an unsupported YAML version", "%YAML 1.1\n---\na: yes\n"], + ["a YAML directive with extra parameters", "%YAML 1.2 x\n---\na\n"], + ["a TAG directive", "%TAG !e! tag:example.com,2000:\n---\na: 1\n"], + ["an indented plain scalar starting with %", "a:\n %foo\nb: 1\n"], + ["content after an end marker following a mapping", "a: 1\n... trailing: 2\n"], + ["a non-separation character after an end marker", "a: 1\n... \u00A0\n"], + ["a non-separation character before an end marker comment", "a: 1\n... \u00A0 # tail\n"], + ["an unsupported YAML version after a byte order mark", "1\n...\n\uFEFF%YAML 1.1\n---\na: yes\n"] + ])("rejects %s", (_, source) => { failureMessage(source) + failureMessage(source, Yaml.parseAll) }) it.each( @@ -480,7 +561,9 @@ development: ["mapping", "# before\n--- # start\na: 1\n... # end\n# after\n", { a: 1 }], ["sequence", "---\n- one\n- two\n...\n", ["one", "two"]], ["plain scalar", "---\none\n...\n", "one"], - ["empty document", "---\n...\n", null] + ["empty document", "---\n...\n", null], + ["anchored empty document", "--- &a\n...\n", null], + ["%YAML 1.2 directive", "%YAML 1.2\n---\nDocument\n... # Suffix\n", "Document"] ] as const )("preserves single-document markers around a %s", (_, source, expected) => { assert.deepStrictEqual(parse(source), expected) From afdf3c4d406e2fd8ba539aedb3139c26ec690c2a Mon Sep 17 00:00:00 2001 From: effect-bot <129879685+effect-bot@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:48:00 +0100 Subject: [PATCH 12/15] Support OpenTelemetry SDK 3.x in @effect/opentelemetry (#10339) --- .changeset/opentelemetry-sdk-v3.md | 26 ++ packages/opentelemetry/package.json | 45 +-- packages/opentelemetry/src/NodeSdk.ts | 15 +- packages/opentelemetry/src/OtelLogger.ts | 4 +- packages/opentelemetry/src/WebSdk.ts | 15 +- .../opentelemetry/src/internal/metrics.ts | 39 +-- .../opentelemetry/test/OtelLogger.test.ts | 12 +- .../opentelemetry/test/OtelMetrics.test.ts | 10 - .../opentelemetry/test/OtelTracer.test.ts | 20 +- packages/opentelemetry/test/WebSdk.test.ts | 22 ++ pnpm-lock.yaml | 256 +++++++----------- 11 files changed, 199 insertions(+), 265 deletions(-) create mode 100644 .changeset/opentelemetry-sdk-v3.md create mode 100644 packages/opentelemetry/test/WebSdk.test.ts diff --git a/.changeset/opentelemetry-sdk-v3.md b/.changeset/opentelemetry-sdk-v3.md new file mode 100644 index 0000000000..26b8871e1a --- /dev/null +++ b/.changeset/opentelemetry-sdk-v3.md @@ -0,0 +1,26 @@ +--- +"@effect/opentelemetry": minor +--- + +Support OpenTelemetry JS SDK 3.x in `@effect/opentelemetry`. SDK 2.x is no longer supported; stay on `@effect/opentelemetry` 4.1.x if you need it. + +- Peer dependency changes: + - `@opentelemetry/api` now needs `>=1.10.0`. + - `@opentelemetry/resources`, `@opentelemetry/sdk-logs` and `@opentelemetry/sdk-metrics` now need `>=3.0.0 <4.0.0`. + - `@opentelemetry/sdk-trace` 3.x replaces `@opentelemetry/sdk-trace-base`, `@opentelemetry/sdk-trace-node` and `@opentelemetry/sdk-trace-web`. + - `@opentelemetry/api-logs` is no longer a peer. +- `NodeSdk` and `WebSdk` `tracerConfig` now takes `TracerProviderOptions` from `@opentelemetry/sdk-trace`. `loggerProviderConfig` and `OtelLogger.layerLoggerProvider` now take `LoggerProviderOptions` from `@opentelemetry/sdk-logs`. +- Import span processors, exporters and samplers from `@opentelemetry/sdk-trace`, and import `SeverityNumber` from `@opentelemetry/api`. Pass the exporter in an options object: `new BatchSpanProcessor({ exporter })`. `BatchSpanProcessor` no longer reads `OTEL_BSP_*`, so pass those settings as options. +- `NodeSdk` no longer reads `OTEL_TRACES_SAMPLER`, `OTEL_TRACES_SAMPLER_ARG` or the `OTEL_SPAN_*` / `OTEL_ATTRIBUTE_*` span limits, because SDK 3.x removed environment-based tracer configuration. Configure them in code instead: + + ```ts + NodeSdk.layer(() => ({ + spanProcessor: new BatchSpanProcessor({ exporter }), + tracerConfig: { + sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(0.1) }), + spanLimits: { attributeCountLimit: 64 } + } + })) + ``` + +- Metric descriptors from `OtelMetrics` no longer include the `type` and `advice` fields, because they were removed from the SDK 3.x descriptor. diff --git a/packages/opentelemetry/package.json b/packages/opentelemetry/package.json index 887552a69d..028dc42333 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -72,14 +72,11 @@ "check": "tsc -b tsconfig.json" }, "peerDependencies": { - "@opentelemetry/api": ">=1.9.0 <2.0.0", - "@opentelemetry/api-logs": ">=0.203.0 <0.300.0", - "@opentelemetry/resources": ">=2.0.0 <3.0.0", - "@opentelemetry/sdk-logs": ">=0.203.0 <0.300.0", - "@opentelemetry/sdk-metrics": ">=2.0.0 <3.0.0", - "@opentelemetry/sdk-trace-base": ">=2.0.0 <3.0.0", - "@opentelemetry/sdk-trace-node": ">=2.0.0 <3.0.0", - "@opentelemetry/sdk-trace-web": ">=2.0.0 <3.0.0", + "@opentelemetry/api": ">=1.10.0 <2.0.0", + "@opentelemetry/resources": ">=3.0.0 <4.0.0", + "@opentelemetry/sdk-logs": ">=3.0.0 <4.0.0", + "@opentelemetry/sdk-metrics": ">=3.0.0 <4.0.0", + "@opentelemetry/sdk-trace": ">=3.0.0 <4.0.0", "@opentelemetry/semantic-conventions": ">=1.33.0 <2.0.0", "effect": "workspace:^" }, @@ -93,36 +90,24 @@ "@opentelemetry/sdk-metrics": { "optional": true }, - "@opentelemetry/sdk-trace-base": { - "optional": true - }, - "@opentelemetry/sdk-trace-node": { - "optional": true - }, - "@opentelemetry/sdk-trace-web": { + "@opentelemetry/sdk-trace": { "optional": true }, "@opentelemetry/sdk-logs": { "optional": true - }, - "@opentelemetry/api-logs": { - "optional": true } }, "devDependencies": { "@opentelemetry/api": "^1.10.0", - "@opentelemetry/api-logs": "^0.223.0", - "@opentelemetry/context-async-hooks": "^2.12.0", - "@opentelemetry/exporter-metrics-otlp-http": "0.223.0", - "@opentelemetry/exporter-prometheus": "^0.223.0", - "@opentelemetry/exporter-trace-otlp-http": "^0.223.0", - "@opentelemetry/otlp-exporter-base": "^0.223.0", - "@opentelemetry/resources": "^2.12.0", - "@opentelemetry/sdk-logs": "^0.223.0", - "@opentelemetry/sdk-metrics": "^2.12.0", - "@opentelemetry/sdk-trace-base": "^2.12.0", - "@opentelemetry/sdk-trace-node": "^2.12.0", - "@opentelemetry/sdk-trace-web": "^2.12.0", + "@opentelemetry/context-async-hooks": "^3.0.0", + "@opentelemetry/exporter-metrics-otlp-http": "0.300.0", + "@opentelemetry/exporter-prometheus": "^0.300.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.300.0", + "@opentelemetry/otlp-exporter-base": "^0.300.0", + "@opentelemetry/resources": "^3.0.0", + "@opentelemetry/sdk-logs": "^3.0.0", + "@opentelemetry/sdk-metrics": "^3.0.0", + "@opentelemetry/sdk-trace": "^3.0.0", "@opentelemetry/semantic-conventions": "^1.44.0" } } diff --git a/packages/opentelemetry/src/NodeSdk.ts b/packages/opentelemetry/src/NodeSdk.ts index 7850e78820..69f6548869 100644 --- a/packages/opentelemetry/src/NodeSdk.ts +++ b/packages/opentelemetry/src/NodeSdk.ts @@ -5,17 +5,16 @@ * tracing, metrics, and logging in Node.js. The main `layer` builds the shared * OpenTelemetry resource from environment variables and optional service * metadata, then enables only the signal types that have processors or readers - * configured. `layerTracerProvider` creates a scoped Node tracer provider, and + * configured. `layerTracerProvider` creates a scoped tracer provider, and * `layerEmpty` provides an empty resource. * * @stability unstable * @since 4.0.0 */ import type * as Otel from "@opentelemetry/api" -import type { LoggerProviderConfig, LogRecordProcessor } from "@opentelemetry/sdk-logs" +import type { LoggerProviderOptions, LogRecordProcessor } from "@opentelemetry/sdk-logs" import type { MetricReader } from "@opentelemetry/sdk-metrics" -import type { SpanProcessor, TracerConfig } from "@opentelemetry/sdk-trace-base" -import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node" +import { type SpanProcessor, TracerProvider, type TracerProviderOptions } from "@opentelemetry/sdk-trace" import type { NonEmptyReadonlyArray } from "effect/Array" import type * as Duration from "effect/Duration" import * as Effect from "effect/Effect" @@ -36,11 +35,11 @@ import * as Resource from "./Resource.ts" */ export interface Configuration { readonly spanProcessor?: SpanProcessor | ReadonlyArray | undefined - readonly tracerConfig?: Omit | undefined + readonly tracerConfig?: Omit | undefined readonly metricReader?: MetricReader | ReadonlyArray | undefined readonly metricTemporality?: Metrics.TemporalityPreference | undefined readonly logRecordProcessor?: LogRecordProcessor | ReadonlyArray | undefined - readonly loggerProviderConfig?: Omit | undefined + readonly loggerProviderConfig?: Omit | undefined readonly loggerMergeWithExisting?: boolean | undefined readonly resource?: { readonly serviceName: string @@ -59,7 +58,7 @@ export interface Configuration { */ export const layerTracerProvider = ( processor: SpanProcessor | NonEmptyReadonlyArray, - config?: Omit & { + config?: Omit & { readonly shutdownTimeout?: Duration.Input | undefined } ): Layer.Layer => @@ -69,7 +68,7 @@ export const layerTracerProvider = ( const resource = yield* Resource.Resource return yield* Effect.acquireRelease( Effect.sync(() => { - const provider = new NodeTracerProvider({ + const provider = new TracerProvider({ ...(config ?? undefined), resource, spanProcessors: Array.isArray(processor) ? (processor as any) : [processor] diff --git a/packages/opentelemetry/src/OtelLogger.ts b/packages/opentelemetry/src/OtelLogger.ts index 5cda33ed5b..24d68225ce 100644 --- a/packages/opentelemetry/src/OtelLogger.ts +++ b/packages/opentelemetry/src/OtelLogger.ts @@ -11,7 +11,7 @@ * @since 4.0.0 */ import * as OtelApi from "@opentelemetry/api" -import { SeverityNumber } from "@opentelemetry/api-logs" +import { SeverityNumber } from "@opentelemetry/api" import * as Otel from "@opentelemetry/sdk-logs" import type { NonEmptyReadonlyArray } from "effect/Array" import * as Arr from "effect/Array" @@ -190,7 +190,7 @@ export const layer = (options: { */ export const layerLoggerProvider = ( processor: Otel.LogRecordProcessor | NonEmptyReadonlyArray, - config?: Omit & { + config?: Omit & { readonly shutdownTimeout?: Duration.Input | undefined } ): Layer.Layer => diff --git a/packages/opentelemetry/src/WebSdk.ts b/packages/opentelemetry/src/WebSdk.ts index d4fc8e8383..89cf558936 100644 --- a/packages/opentelemetry/src/WebSdk.ts +++ b/packages/opentelemetry/src/WebSdk.ts @@ -5,16 +5,15 @@ * tracing, metrics, and logging in browser runtimes. The main `layer` builds * the shared OpenTelemetry resource from explicit service metadata, then * enables only the signal types that have processors or readers configured. - * `layerTracerProvider` creates a scoped `WebTracerProvider`. + * `layerTracerProvider` creates a scoped `TracerProvider`. * * @stability unstable * @since 4.0.0 */ import type * as Otel from "@opentelemetry/api" -import type { LoggerProviderConfig, LogRecordProcessor } from "@opentelemetry/sdk-logs" +import type { LoggerProviderOptions, LogRecordProcessor } from "@opentelemetry/sdk-logs" import type { MetricReader } from "@opentelemetry/sdk-metrics" -import type { SpanProcessor, TracerConfig } from "@opentelemetry/sdk-trace-base" -import { WebTracerProvider } from "@opentelemetry/sdk-trace-web" +import { type SpanProcessor, TracerProvider, type TracerProviderOptions } from "@opentelemetry/sdk-trace" import type { NonEmptyReadonlyArray } from "effect/Array" import * as Effect from "effect/Effect" import { constant, type LazyArg } from "effect/Function" @@ -34,11 +33,11 @@ import * as Resource from "./Resource.ts" */ export interface Configuration { readonly spanProcessor?: SpanProcessor | ReadonlyArray | undefined - readonly tracerConfig?: Omit + readonly tracerConfig?: Omit readonly metricReader?: MetricReader | ReadonlyArray | undefined readonly metricTemporality?: Metrics.TemporalityPreference | undefined readonly logRecordProcessor?: LogRecordProcessor | ReadonlyArray | undefined - readonly loggerProviderConfig?: Omit | undefined + readonly loggerProviderConfig?: Omit | undefined readonly loggerMergeWithExisting?: boolean | undefined readonly resource: { readonly serviceName: string @@ -56,7 +55,7 @@ export interface Configuration { */ export const layerTracerProvider = ( processor: SpanProcessor | NonEmptyReadonlyArray, - config?: Omit + config?: Omit ): Layer.Layer => Layer.effect( Tracer.OtelTracerProvider, @@ -64,7 +63,7 @@ export const layerTracerProvider = ( const resource = yield* Resource.Resource return yield* Effect.acquireRelease( Effect.sync(() => { - const provider = new WebTracerProvider({ + const provider = new TracerProvider({ ...(config ?? undefined), resource, spanProcessors: Array.isArray(processor) ? (processor as any) : [processor] diff --git a/packages/opentelemetry/src/internal/metrics.ts b/packages/opentelemetry/src/internal/metrics.ts index 9ded807180..5ea1940e2f 100644 --- a/packages/opentelemetry/src/internal/metrics.ts +++ b/packages/opentelemetry/src/internal/metrics.ts @@ -6,10 +6,10 @@ import type { Histogram, MetricCollectOptions, MetricData, + MetricDescriptor, MetricProducer } from "@opentelemetry/sdk-metrics" -import { AggregationTemporality, DataPointType, InstrumentType } from "@opentelemetry/sdk-metrics" -import type { InstrumentDescriptor } from "@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js" +import { AggregationTemporality, DataPointType } from "@opentelemetry/sdk-metrics" import * as Arr from "effect/Array" import type * as Context from "effect/Context" import * as Metric from "effect/Metric" @@ -18,10 +18,6 @@ import type * as Metrics from "../OtelMetrics.ts" const sdkName = "@effect/opentelemetry/Metrics" -type MetricDataWithInstrumentDescriptor = MetricData & { - readonly descriptor: InstrumentDescriptor -} - interface PreviousHistogramState { readonly count: number readonly sum: number @@ -90,7 +86,7 @@ export class MetricProducerImpl implements MetricProducer { this.previousSummaryState = new Map() const metricData: Array = [] const metricDataByName = new Map() - const addMetricData = (data: MetricDataWithInstrumentDescriptor) => { + const addMetricData = (data: MetricData) => { metricData.push(data) metricDataByName.set(data.descriptor.name, data) } @@ -373,9 +369,7 @@ export class MetricProducerImpl implements MetricProducer { name: `${state.id}_count`, description: state.description ?? "", unit: "1", - type: InstrumentType.COUNTER, - valueType: ValueType.INT, - advice: {} + valueType: ValueType.INT }, aggregationTemporality, isMonotonic: true, @@ -387,9 +381,7 @@ export class MetricProducerImpl implements MetricProducer { name: `${state.id}_sum`, description: state.description ?? "", unit: "1", - type: InstrumentType.COUNTER, - valueType: ValueType.DOUBLE, - advice: {} + valueType: ValueType.DOUBLE }, aggregationTemporality, isMonotonic: true, @@ -436,30 +428,13 @@ const currentHrTime = (): HrTime => { const descriptorFromState = ( state: Metric.Metric.Snapshot, attributes: Record -): InstrumentDescriptor => { +): MetricDescriptor => { const unit = attributes.unit ?? attributes.time_unit ?? "1" return { name: state.id, description: state.description ?? "", unit, - type: instrumentTypeFromSnapshot(state), - valueType: determineValueType(state), - advice: {} - } -} - -const instrumentTypeFromSnapshot = (state: Metric.Metric.Snapshot): InstrumentType => { - switch (state.type) { - case "Histogram": - return InstrumentType.HISTOGRAM - case "Gauge": - return InstrumentType.OBSERVABLE_GAUGE - case "Frequency": - return InstrumentType.COUNTER - case "Counter": - return state.state.incremental ? InstrumentType.COUNTER : InstrumentType.UP_DOWN_COUNTER - case "Summary": - return InstrumentType.COUNTER + valueType: determineValueType(state) } } diff --git a/packages/opentelemetry/test/OtelLogger.test.ts b/packages/opentelemetry/test/OtelLogger.test.ts index fa5bf6b2d2..20ce7826dc 100644 --- a/packages/opentelemetry/test/OtelLogger.test.ts +++ b/packages/opentelemetry/test/OtelLogger.test.ts @@ -4,10 +4,10 @@ import * as OtelTracer from "@effect/opentelemetry/OtelTracer" import * as Resource from "@effect/opentelemetry/Resource" import { assert, describe, it } from "@effect/vitest" import * as OtelApi from "@opentelemetry/api" -import { SeverityNumber } from "@opentelemetry/api-logs" -import { AsyncHooksContextManager } from "@opentelemetry/context-async-hooks" +import { SeverityNumber } from "@opentelemetry/api" +import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks" import { InMemoryLogRecordExporter, type LogRecordProcessor, SimpleLogRecordProcessor } from "@opentelemetry/sdk-logs" -import { InMemorySpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base" +import { InMemorySpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace" import * as Cause from "effect/Cause" import * as Clock from "effect/Clock" import * as ConfigProvider from "effect/ConfigProvider" @@ -169,7 +169,7 @@ describe("Logger", () => { resource: { serviceName: "test" }, - spanProcessor: [new SimpleSpanProcessor(spanExporter)], + spanProcessor: [new SimpleSpanProcessor({ exporter: spanExporter })], logRecordProcessor: [new SimpleLogRecordProcessor({ exporter: logExporter })] }))) @@ -201,7 +201,7 @@ describe("Logger", () => { const spanExporter = new InMemorySpanExporter() const TracingLayer = NodeSdk.layer(Effect.sync(() => ({ resource: { serviceName: "test" }, - spanProcessor: [new SimpleSpanProcessor(spanExporter)], + spanProcessor: [new SimpleSpanProcessor({ exporter: spanExporter })], logRecordProcessor: [new SimpleLogRecordProcessor({ exporter: logExporter })] }))) @@ -245,7 +245,7 @@ describe("Logger", () => { }) it("uses ambient context only when there is no Effect parent span", async () => { - const contextManager = new AsyncHooksContextManager() + const contextManager = new AsyncLocalStorageContextManager() OtelApi.context.setGlobalContextManager(contextManager.enable()) try { const logExporter = new InMemoryLogRecordExporter() diff --git a/packages/opentelemetry/test/OtelMetrics.test.ts b/packages/opentelemetry/test/OtelMetrics.test.ts index 73d5d39d38..799df94dfc 100644 --- a/packages/opentelemetry/test/OtelMetrics.test.ts +++ b/packages/opentelemetry/test/OtelMetrics.test.ts @@ -86,11 +86,9 @@ describe("Metrics", () => { assert.deepStrictEqual(metric, { "dataPointType": 2, "descriptor": { - "advice": {}, "name": "rps", "description": "", "unit": "requests", - "type": "OBSERVABLE_GAUGE", "valueType": ValueType.DOUBLE }, "aggregationTemporality": 1, @@ -150,11 +148,9 @@ describe("Metrics", () => { assert.deepEqual(metric, { "dataPointType": 2, "descriptor": { - "advice": {}, "name": "rps-bigint", "description": "", "unit": "requests", - "type": "OBSERVABLE_GAUGE", "valueType": ValueType.INT }, "aggregationTemporality": 1, @@ -214,11 +210,9 @@ describe("Metrics", () => { assert.deepEqual(metric, { "dataPointType": 3, "descriptor": { - "advice": {}, "name": "counter", "description": "Example", "unit": "requests", - "type": "UP_DOWN_COUNTER", "valueType": ValueType.DOUBLE }, "isMonotonic": false, @@ -282,11 +276,9 @@ describe("Metrics", () => { assert.deepEqual(metric, { "dataPointType": 3, "descriptor": { - "advice": {}, "name": "counter-inc", "description": "Example", "unit": "requests", - "type": "COUNTER", "valueType": ValueType.DOUBLE }, "isMonotonic": true, @@ -351,11 +343,9 @@ describe("Metrics", () => { assert.deepEqual(metric, { "dataPointType": 3, "descriptor": { - "advice": {}, "name": "counter-bigint", "description": "Example", "unit": "requests", - "type": "COUNTER", "valueType": ValueType.INT }, "isMonotonic": true, diff --git a/packages/opentelemetry/test/OtelTracer.test.ts b/packages/opentelemetry/test/OtelTracer.test.ts index 93d80a14a5..5996b18f07 100644 --- a/packages/opentelemetry/test/OtelTracer.test.ts +++ b/packages/opentelemetry/test/OtelTracer.test.ts @@ -3,8 +3,8 @@ import * as OtelTracer from "@effect/opentelemetry/OtelTracer" import * as Resource from "@effect/opentelemetry/Resource" import { assert, describe, it } from "@effect/vitest" import * as OtelApi from "@opentelemetry/api" -import { AsyncHooksContextManager } from "@opentelemetry/context-async-hooks" -import { InMemorySpanExporter, SimpleSpanProcessor, type SpanExporter } from "@opentelemetry/sdk-trace-base" +import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks" +import { InMemorySpanExporter, SimpleSpanProcessor, type SpanExporter } from "@opentelemetry/sdk-trace" import * as Cause from "effect/Cause" import * as EffectContext from "effect/Context" import * as Effect from "effect/Effect" @@ -17,12 +17,12 @@ import * as EffectTracer from "effect/Tracer" import * as Version from "effect/Version" const TracingLayer = OtelTracer.layer.pipe( - Layer.provide(NodeSdk.layerTracerProvider([new SimpleSpanProcessor(new InMemorySpanExporter())])), + Layer.provide(NodeSdk.layerTracerProvider([new SimpleSpanProcessor({ exporter: new InMemorySpanExporter() })])), Layer.provide(Resource.layerEmpty) ) // needed to test context propagation -const contextManager = new AsyncHooksContextManager() +const contextManager = new AsyncLocalStorageContextManager() OtelApi.context.setGlobalContextManager(contextManager.enable()) describe("Tracer", () => { @@ -30,7 +30,7 @@ describe("Tracer", () => { const exporter = new InMemorySpanExporter() const layer = NodeSdk.layer(Effect.sync(() => ({ resource: { serviceName: "test", serviceVersion: "service-version" }, - spanProcessor: [new SimpleSpanProcessor(exporter)] + spanProcessor: [new SimpleSpanProcessor({ exporter })] }))) return Effect.gen(function*() { yield* Effect.void.pipe(Effect.withSpan("test")) @@ -53,7 +53,7 @@ describe("Tracer", () => { HttpRouter.add("GET", "/", Effect.succeed(HttpServerResponse.text("ok"))).pipe( Layer.provideMerge(NodeSdk.layer(() => ({ resource: { serviceName: "test" }, - spanProcessor: new SimpleSpanProcessor(exporter) + spanProcessor: new SimpleSpanProcessor({ exporter }) }))) ), { disableLogger: true } @@ -307,7 +307,7 @@ describe("Tracer", () => { it.effect("records every pretty error", () => Effect.gen(function*() { const exporter = new InMemorySpanExporter() - const spanProcessor = new SimpleSpanProcessor(exporter) + const spanProcessor = new SimpleSpanProcessor({ exporter }) const firstFailure = Cause.fail(new Error("first")) const secondFailure = Cause.fail(new Error("second")) const cause = Cause.combine(firstFailure, secondFailure) @@ -336,7 +336,7 @@ describe("Tracer", () => { it.effect("renders nested error causes in the stacktrace", () => Effect.gen(function*() { const exporter = new InMemorySpanExporter() - const spanProcessor = new SimpleSpanProcessor(exporter) + const spanProcessor = new SimpleSpanProcessor({ exporter }) const error = new Error("outer failure", { cause: new Error("inner cause") }) yield* Effect.die(error).pipe( @@ -374,13 +374,13 @@ describe("Tracer", () => { assert.deepStrictEqual(spans[0].attributes, { "effect.fiber.interrupted": true }) }).pipe(Effect.provide(NodeSdk.layer(() => ({ resource: { serviceName: "test" }, - spanProcessor: [new SimpleSpanProcessor(exporter)] + spanProcessor: [new SimpleSpanProcessor({ exporter })] })))) }) it.effect("exports homogeneous primitive arrays as array attributes", () => Effect.gen(function*() { const exporter = new InMemorySpanExporter() - const spanProcessor = new SimpleSpanProcessor(exporter) + const spanProcessor = new SimpleSpanProcessor({ exporter }) yield* Effect.void.pipe( Effect.withSpan("array-span", { diff --git a/packages/opentelemetry/test/WebSdk.test.ts b/packages/opentelemetry/test/WebSdk.test.ts new file mode 100644 index 0000000000..965fa5bb9e --- /dev/null +++ b/packages/opentelemetry/test/WebSdk.test.ts @@ -0,0 +1,22 @@ +import * as WebSdk from "@effect/opentelemetry/WebSdk" +import { assert, describe, it } from "@effect/vitest" +import { InMemorySpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace" +import * as Effect from "effect/Effect" + +describe("WebSdk", () => { + it.effect("exports spans with the configured service resource", () => { + const exporter = new InMemorySpanExporter() + return Effect.gen(function*() { + yield* Effect.void.pipe(Effect.withSpan("test")) + const spans = exporter.getFinishedSpans() + assert.strictEqual(spans.length, 1) + assert.strictEqual(spans[0]!.name, "test") + assert.strictEqual(spans[0]!.resource.attributes["service.name"], "web-service") + }).pipe( + Effect.provide(WebSdk.layer(() => ({ + resource: { serviceName: "web-service" }, + spanProcessor: new SimpleSpanProcessor({ exporter }) + }))) + ) + }) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d2f3f3d7df..9cfb585d4c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -390,42 +390,33 @@ importers: '@opentelemetry/api': specifier: ^1.10.0 version: 1.10.0 - '@opentelemetry/api-logs': - specifier: ^0.223.0 - version: 0.223.0 '@opentelemetry/context-async-hooks': - specifier: ^2.12.0 - version: 2.12.0(@opentelemetry/api@1.10.0) + specifier: ^3.0.0 + version: 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/exporter-metrics-otlp-http': - specifier: 0.223.0 - version: 0.223.0(@opentelemetry/api@1.10.0) + specifier: 0.300.0 + version: 0.300.0(@opentelemetry/api@1.10.0) '@opentelemetry/exporter-prometheus': - specifier: ^0.223.0 - version: 0.223.0(@opentelemetry/api@1.10.0) + specifier: ^0.300.0 + version: 0.300.0(@opentelemetry/api@1.10.0) '@opentelemetry/exporter-trace-otlp-http': - specifier: ^0.223.0 - version: 0.223.0(@opentelemetry/api@1.10.0) + specifier: ^0.300.0 + version: 0.300.0(@opentelemetry/api@1.10.0) '@opentelemetry/otlp-exporter-base': - specifier: ^0.223.0 - version: 0.223.0(@opentelemetry/api@1.10.0) + specifier: ^0.300.0 + version: 0.300.0(@opentelemetry/api@1.10.0) '@opentelemetry/resources': - specifier: ^2.12.0 - version: 2.12.0(@opentelemetry/api@1.10.0) + specifier: ^3.0.0 + version: 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/sdk-logs': - specifier: ^0.223.0 - version: 0.223.0(@opentelemetry/api@1.10.0) + specifier: ^3.0.0 + version: 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/sdk-metrics': - specifier: ^2.12.0 - version: 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-trace-base': - specifier: ^2.12.0 - version: 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-trace-node': - specifier: ^2.12.0 - version: 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-trace-web': - specifier: ^2.12.0 - version: 2.12.0(@opentelemetry/api@1.10.0) + specifier: ^3.0.0 + version: 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-trace': + specifier: ^3.0.0 + version: 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': specifier: ^1.44.0 version: 1.44.0 @@ -2534,100 +2525,75 @@ packages: '@sqlite.org/sqlite-wasm': optional: true - '@opentelemetry/api-logs@0.223.0': - resolution: {integrity: sha512-Oepm6etVPFCn0VWB1t833iOTgz1eYBDUPxcrOR/XvwzD1+Ag9VzSPSrrKAFNJ/haatj+8CXbG47pZXvdNQKDJw==} - engines: {node: '>=8.0.0'} - '@opentelemetry/api@1.10.0': resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==} engines: {node: '>=8.0.0'} - '@opentelemetry/context-async-hooks@2.12.0': - resolution: {integrity: sha512-iK/1nD7mmZVkuYjVjkdFBiCvzntJdFny1S3CYbUYyOq7V5enL6XX+gJ7eh965L1LnS11VA8mQ7Ej/ck04SB0MQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/context-async-hooks@3.0.0': + resolution: {integrity: sha512-qDZeKSgTT+qTaL99eRbpvWO5+oZ0MKvMH4pqvzi6xYKyhiMTDBxBeTLI6BpdeMt58T5TpxHJvFl9P52i6CDWGA==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' + '@opentelemetry/api': '>=1.0.0 <1.11.0' - '@opentelemetry/core@2.12.0': - resolution: {integrity: sha512-1HsSAuvT4/my0QrXWsyXFdWjKaPeCHsismKZgEEIb8NK13LP6DrMRlsUbvD/0F9mDWK3xDom9AMv3IscxgOnOQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/core@3.0.0': + resolution: {integrity: sha512-whOLlww0R/RLtCWGBXhK1fdvL9t2/TL0fqdjZvcaoUUuNilRPjXecqQdzyVwV68s6XEDA5oYbm7/bZT62GXF4A==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/exporter-metrics-otlp-http@0.223.0': - resolution: {integrity: sha512-hNC8yai/+xCNyTuiOy6JFepXXA/sb/2jCzQRY7c2cUWz6owaidihlHUpO20B9/dj8JKPNo8rcn7ikTy7Cj+JaQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-metrics-otlp-http@0.300.0': + resolution: {integrity: sha512-y8KYKyM69l9PG4Ax9DKlKH5jaVJCJo9hXOpT6v0/PDX+uC302AhHVitEz8M600ljqLGdPYodnyn+wbYIYXPh6g==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-prometheus@0.223.0': - resolution: {integrity: sha512-HhbN3/B8vG+JNKH2oLMynFFrz2O/o+WFklfwiVq3ffdRWOEZx1zHeYe6r86fn9BUSpQ2U5cXfQja+otTdzi5qQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-prometheus@0.300.0': + resolution: {integrity: sha512-x8MCVBUPYZeQcL14HJUiYuF6IL4/YZ5OtR5ObnznUaTrhPdZUEvOQ4EpkLvfFph/nvk4lEs0cJ6uK5oMrFyjGQ==} + engines: {node: '>=22.15.0'} + peerDependencies: + '@opentelemetry/api': '>=1.10.0 <1.11.0' + + '@opentelemetry/exporter-trace-otlp-http@0.300.0': + resolution: {integrity: sha512-Dwdagba93cdhROlFGbkU4yK4hvd3l0k7WV9nvTWIoN6KwxFP+HCvy9EkgIpyfN11fVdIWxY3XqOwWOq83OPfcA==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-trace-otlp-http@0.223.0': - resolution: {integrity: sha512-N8NWZaoQuF9e307S6xoVoI1lvxOOFkmBnynD42r02CPCfxoC95cJExAKBFrTD4C5iuhqthbzOZJN/W29ez4o/A==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/otlp-exporter-base@0.300.0': + resolution: {integrity: sha512-D+PhzYURtv6p7Kk1rUrilLtV+ZvS218tI0jiKTV5z1agOeELw78C+cFd3o9UUshUx1j+EIpFM62yGk8BuydQvg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/otlp-exporter-base@0.223.0': - resolution: {integrity: sha512-HlJMrJXjOqdQeoYNDHEvFTpaY2p9uWDK1GPl5AZ4wI5easzfoppTduOv47M8eiF+4ew42vfI/Xvt7THYgESnRw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/otlp-transformer@0.300.0': + resolution: {integrity: sha512-T55lRmjRwvXWyTFdy/BbJ3T5RRsq3bAwQgxxA7qHFxgRd4+pZzRk02ZwOFsYK5072OXGYjYFNJcp68eQV4i0Ig==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.3.0 + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/otlp-transformer@0.223.0': - resolution: {integrity: sha512-oxmmPL5/MbSsO8K588V9n/XLIe7FZTK30Fo+/U/lAnt0ZIK/hoPM03n2WpSTZVbUBGTUE7aLyxnAzh7nE2PD4Q==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/resources@3.0.0': + resolution: {integrity: sha512-4762KVmlDroRIt+4Ra8AnwcQqdXlkAR55jDrhzna8bzhJx1mUzvHW/Lh/OemFuY9+ouM4xaDc6CbUmoJmM6BFg==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.3.0 + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/resources@2.12.0': - resolution: {integrity: sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/sdk-logs@3.0.0': + resolution: {integrity: sha512-IysNZWrBk2PqYw4qU9PZcC7pjrZLa+KLk7vcLmPPNBUr97MgeamWhX0DUHsmxwJv3dnjYM6mLRmP8mw69ld+dA==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.3.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/sdk-logs@0.223.0': - resolution: {integrity: sha512-ApiAfUiUh6fmJt1GbsBuoeDn8D8IL42UvGyPUr8o1Z89ZeIiOCE1rZ78KkIUjEX3OV8Oorl9ez5Qjo43ZynDyw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/sdk-metrics@3.0.0': + resolution: {integrity: sha512-YozyS2rIlizvUNLZwcWxH0x2FhX02/mcZwzM8hsl8yvQk+xeKmAc7vcSieWiO4oSwIB20B8eS/zwdopAd/J5zQ==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.4.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/sdk-metrics@2.12.0': - resolution: {integrity: sha512-mVMaEHwCUJuY3S4Esn+nT0yQA3qCEGh+SOPJsXygU0Gl453WcsDNjtEa8EfdewMwoLyr1tlofB4fXytVpiXuow==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/sdk-trace@3.0.0': + resolution: {integrity: sha512-4T0DbDGdtsjNmYK5/lNalHro4fsMZ0UZ3JE+C8fcqYP25xaJC22FHg8kdJNJ21srjJY5XoT7WNFCtj88NNTl4Q==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.9.0 <1.10.0' - - '@opentelemetry/sdk-trace-base@2.12.0': - resolution: {integrity: sha512-JOERgZCxRM06FEJ5kEWxlSRChah6MmXDx3KwCruqEv/iEyLkTokCSemf2y1w8oIHtfrr8EVTpzebq/31vn2Cpg==} - engines: {node: ^18.19.0 || >=20.6.0} - deprecated: Use @opentelemetry/sdk-trace package - peerDependencies: - '@opentelemetry/api': '>=1.3.0 <1.10.0' - - '@opentelemetry/sdk-trace-node@2.12.0': - resolution: {integrity: sha512-9DufH1IlmQMoKAfot5y/FhTP1RnmhLb5K6eKmJO/bvzPjYwPAazoiAUbTZFdPbqxOXN0FEbhZx/e6SB1Og4jmg==} - engines: {node: ^18.19.0 || >=20.6.0} - deprecated: Use @opentelemetry/sdk-trace package - peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' - - '@opentelemetry/sdk-trace-web@2.12.0': - resolution: {integrity: sha512-y0hCzbnBHScmioF0drJOyaPk1sQf2wwbIuy3rWlM0Fcx8mLfPDvFsQ7tJ+zMm8yAqI06rSlFKkL7ZpcrFOqAdQ==} - engines: {node: ^18.19.0 || >=20.6.0} - deprecated: Use @opentelemetry/sdk-trace package - peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' - - '@opentelemetry/sdk-trace@2.12.0': - resolution: {integrity: sha512-ImVuRQ6faOsTi1Wna88s2avgrrf/iDgXPigIeynkUhjstMuoQUDOJXgkez2j1mlU4btjXcXBGa+q7qKFYR3GsA==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': '>=1.3.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' '@opentelemetry/semantic-conventions@1.44.0': resolution: {integrity: sha512-E3JkOlMBi3N8OGGkbl7tFyqk2MAS6/lySRZBK3Mu7AzjF1fT8oIChH9ChE48SUWzDn9Kdwta+G/p5LJ4xW4CLQ==} @@ -8309,107 +8275,79 @@ snapshots: react: 19.3.1 react-native: 0.83.0(@babel/core@8.0.10)(@types/react@19.3.0)(react@19.3.1)(supports-color@10.2.2) - '@opentelemetry/api-logs@0.223.0': - dependencies: - '@opentelemetry/api': 1.10.0 - '@opentelemetry/api@1.10.0': {} - '@opentelemetry/context-async-hooks@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/context-async-hooks@3.0.0(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/core@3.0.0(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 '@opentelemetry/semantic-conventions': 1.44.0 - '@opentelemetry/exporter-metrics-otlp-http@0.223.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/exporter-metrics-otlp-http@0.300.0(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/otlp-exporter-base': 0.223.0(@opentelemetry/api@1.10.0) - '@opentelemetry/otlp-transformer': 0.223.0(@opentelemetry/api@1.10.0) - '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-metrics': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-metrics': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/exporter-prometheus@0.223.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/exporter-prometheus@0.300.0(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-metrics': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-metrics': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.44.0 - '@opentelemetry/exporter-trace-otlp-http@0.223.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/exporter-trace-otlp-http@0.300.0(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/otlp-exporter-base': 0.223.0(@opentelemetry/api@1.10.0) - '@opentelemetry/otlp-transformer': 0.223.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-trace': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-trace': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/otlp-exporter-base@0.223.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/otlp-exporter-base@0.300.0(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/otlp-transformer': 0.223.0(@opentelemetry/api@1.10.0) + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) - '@opentelemetry/otlp-transformer@0.223.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/otlp-transformer@0.300.0(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/api-logs': 0.223.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-logs': 0.223.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-metrics': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-trace': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-logs': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-metrics': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-trace': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/resources@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/resources@3.0.0(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.44.0 - '@opentelemetry/sdk-logs@0.223.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/sdk-logs@3.0.0(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/api-logs': 0.223.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.44.0 - '@opentelemetry/sdk-metrics@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/sdk-metrics@3.0.0(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-trace-base@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/sdk-trace@3.0.0(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-trace': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/semantic-conventions': 1.44.0 - - '@opentelemetry/sdk-trace-node@2.12.0(@opentelemetry/api@1.10.0)': - dependencies: - '@opentelemetry/api': 1.10.0 - '@opentelemetry/context-async-hooks': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-trace-base': 2.12.0(@opentelemetry/api@1.10.0) - - '@opentelemetry/sdk-trace-web@2.12.0(@opentelemetry/api@1.10.0)': - dependencies: - '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/sdk-trace-base': 2.12.0(@opentelemetry/api@1.10.0) - - '@opentelemetry/sdk-trace@2.12.0(@opentelemetry/api@1.10.0)': - dependencies: - '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.44.0 '@opentelemetry/semantic-conventions@1.44.0': {} From 13c66eb84b9352186b6ec5d69097ba4f772f553f Mon Sep 17 00:00:00 2001 From: Sebastian Lorenz Date: Wed, 4 Nov 2026 03:56:53 +0100 Subject: [PATCH 13/15] feat(effect): add Supervisor for observing fiber lifecycles (#10258) Co-authored-by: Effect Bot --- .changeset/supervisor.md | 7 + migration/annotations/effect__Effect.yaml | 4 +- migration/annotations/effect__Fiber.yaml | 4 +- migration/annotations/effect__FiberRef.yaml | 4 +- migration/annotations/effect__Supervisor.yaml | 25 +- migration/v3-to-v4.md | 23 +- packages/effect/src/Deferred.ts | 2 +- packages/effect/src/Effect.ts | 53 +++- packages/effect/src/Fiber.ts | 12 +- packages/effect/src/Latch.ts | 14 + packages/effect/src/PartitionedSemaphore.ts | 23 +- packages/effect/src/Pool.ts | 2 +- packages/effect/src/PubSub.ts | 39 ++- packages/effect/src/Queue.ts | 11 +- packages/effect/src/RequestResolver.ts | 11 +- packages/effect/src/Semaphore.ts | 20 +- packages/effect/src/Supervisor.ts | 290 ++++++++++++++++++ packages/effect/src/TxRef.ts | 15 + packages/effect/src/index.ts | 6 + packages/effect/src/internal/effect.ts | 192 +++++++----- packages/effect/src/testing/TestClock.ts | 18 ++ packages/effect/test/Latch.test.ts | 7 +- .../effect/test/PartitionedSemaphore.test.ts | 8 +- packages/effect/test/PubSub.test.ts | 7 + packages/effect/test/Semaphore.test.ts | 5 + packages/effect/test/Supervisor.test.ts | 209 +++++++++++++ packages/effect/test/TestClock.test.ts | 39 +++ packages/effect/test/TxRef.test.ts | 10 + packages/tools/bundle/fixtures/supervisor.ts | 17 + 29 files changed, 945 insertions(+), 132 deletions(-) create mode 100644 .changeset/supervisor.md create mode 100644 packages/effect/src/Supervisor.ts create mode 100644 packages/effect/test/Supervisor.test.ts create mode 100644 packages/effect/test/TxRef.test.ts create mode 100644 packages/tools/bundle/fixtures/supervisor.ts diff --git a/.changeset/supervisor.md b/.changeset/supervisor.md new file mode 100644 index 0000000000..25b5194a2c --- /dev/null +++ b/.changeset/supervisor.md @@ -0,0 +1,7 @@ +--- +"effect": minor +--- + +Add a `blockedOn` option to `Effect.callback`, which tells a Supervisor what the waiting fiber is blocked on; existing calls are unchanged. + +Also add the experimental `Supervisor` module for observing fiber lifecycles. A Supervisor is called when each fiber starts, blocks, unblocks and ends, and is told what a blocked fiber waits on. Install one with `Effect.withSupervisor` or `Supervisor.layer`, and combine several with `Supervisor.combine`. This release also adds `TestClock.stateUnsafe` for reading the pending test sleeps, and the guards `Latch.isLatch`, `Semaphore.isSemaphore`, `PartitionedSemaphore.isPartitionedSemaphore`, `TxRef.isTxRef` and `PubSub.isSubscription`. diff --git a/migration/annotations/effect__Effect.yaml b/migration/annotations/effect__Effect.yaml index c596249919..b347a5a268 100644 --- a/migration/annotations/effect__Effect.yaml +++ b/migration/annotations/effect__Effect.yaml @@ -479,8 +479,8 @@ effect/Effect#summarized: replacement: "Effect.gen" note: "Run the summary Effect before and after the target Effect and combine the two measurements explicitly. Adapt arguments and imports to the v4 API." effect/Effect#supervised: - replacement: "FiberSet" - note: "Track explicitly forked Fibers in a scoped `FiberSet` instead of installing a runtime Supervisor. Adapt arguments and imports to the v4 API." + replacement: "Effect.withSupervisor" + note: "`Effect.withSupervisor` adds a Supervisor for an effect, but now runs the effect in a new child fiber and joins it, so the effect's own fiber is observed too. To track fibers you fork yourself, use a scoped `FiberSet`." effect/Effect#Tag: replacement: "Context.Service" note: "Define services with `Context.Service`; use the generated `.use` helper for accessors. Adapt arguments and imports to the v4 API." diff --git a/migration/annotations/effect__Fiber.yaml b/migration/annotations/effect__Fiber.yaml index 659066b25b..619c0ba7c7 100644 --- a/migration/annotations/effect__Fiber.yaml +++ b/migration/annotations/effect__Fiber.yaml @@ -102,7 +102,7 @@ effect/Fiber#pretty: note: "Runtime fiber pretty-printing was removed; format the public id and polled Exit explicitly." effect/Fiber#roots: replacement: "none" - note: "The runtime no longer exposes a global root-fiber registry; track application fibers explicitly." + note: "The runtime no longer exposes a global root-fiber registry; track application fibers explicitly, or install a `Supervisor.Supervisor` at the runtime with `Supervisor.layer` to discover them." effect/Fiber#RuntimeFiber: replacement: "Fiber.Fiber" note: "RuntimeFiber and Fiber were collapsed into the single v4 Fiber interface." @@ -126,7 +126,7 @@ effect/Fiber#succeed: note: "Synthetic Fiber constructors were removed; run the corresponding Effect when a Fiber handle is required." effect/Fiber#unsafeRoots: replacement: "none" - note: "The runtime no longer exposes a global root-fiber registry; track application fibers explicitly." + note: "The runtime no longer exposes a global root-fiber registry; track application fibers explicitly, or install a `Supervisor.Supervisor` at the runtime with `Supervisor.layer` to discover them." effect/Fiber#void: replacement: "Effect.runFork(Effect.void)" note: "Synthetic Fiber constants were removed; run Effect.void when a completed Fiber is required." diff --git a/migration/annotations/effect__FiberRef.yaml b/migration/annotations/effect__FiberRef.yaml index 403eb277f9..67d6209b8a 100644 --- a/migration/annotations/effect__FiberRef.yaml +++ b/migration/annotations/effect__FiberRef.yaml @@ -44,8 +44,8 @@ effect/FiberRef#currentSchedulingPriority: replacement: "none" note: "The ambient scheduling-priority FiberRef was removed; use explicit scheduler operations where priority is needed." effect/FiberRef#currentSupervisor: - replacement: "none" - note: "The Supervisor and ambient supervisor FiberRef APIs were removed; track fibers explicitly with FiberSet or FiberMap." + replacement: "Supervisor.Supervisor" + note: "`Supervisor.Supervisor` is the reference. A fiber reads it once, when it is created; providing it directly replaces the Supervisor in place, while `Supervisor.layer` and `Effect.withSupervisor` add to it." effect/FiberRef#currentTracerEnabled: replacement: "References.TracerEnabled" note: "Built-in FiberRefs are now Context.Reference values; yield the reference or provide it with Effect.provideService." diff --git a/migration/annotations/effect__Supervisor.yaml b/migration/annotations/effect__Supervisor.yaml index 3399df3608..133d05779b 100644 --- a/migration/annotations/effect__Supervisor.yaml +++ b/migration/annotations/effect__Supervisor.yaml @@ -1,27 +1,30 @@ effect/Supervisor#AbstractSupervisor: - replacement: "none" - note: "The ambient Supervisor abstraction and runtime event hooks were removed." + replacement: "Supervisor.Supervisor" + note: "Implement the `Supervisor.Supervisor` interface with an object literal or a class; there is no abstract base class." effect/Supervisor#addSupervisor: - replacement: "none" - note: "Layer-installed ambient supervision was removed; use structured concurrency and explicit FiberSet or FiberMap tracking." + replacement: "Supervisor.layer" + note: "`Supervisor.layer` adds a Supervisor to the one in place, as `addSupervisor` did. Under a built `ManagedRuntime` it observes the root fibers; under `Layer.launch` or a platform `runMain` only forks, so use `Effect.withSupervisor` around `main`." effect/Supervisor#fibersIn: replacement: "FiberSet" - note: "Use a scoped FiberSet and explicitly run or add fibers; it does not ambiently observe every descendant." + note: "Use a scoped FiberSet and explicitly run or add fibers. To observe every descendant instead, install a `Supervisor.Supervisor` and keep a set in `onStart`/`onEnd`." effect/Supervisor#fromEffect: replacement: "none" note: "The Supervisor abstraction and its effect-valued observation hook were removed." effect/Supervisor#none: - replacement: "none" - note: "The Supervisor abstraction was removed; normal structured concurrency needs no no-op supervisor." + replacement: "undefined" + note: "There is no no-op Supervisor: `undefined` means none. Provide `undefined` to `Supervisor.Supervisor` to opt a region's forks out." effect/Supervisor#Supervisor: - replacement: "none" - note: "Ambient fiber supervision was removed; use structured concurrency or explicit FiberSet and FiberMap tracking." + replacement: "Supervisor.Supervisor" + note: "Now a plain interface with four required methods, `onStart`, `onEnd`, `onBlock` and `onUnblock`, and no `value` or `zip`. `onSuspend`/`onResume` became `onBlock`/`onUnblock`, which fire only when a fiber waits, never when it yields. There is no `onEffect`: use `Tracer.context` for per-operation interposition. `Supervisor.Supervisor` is also the reference that installs one." effect/Supervisor#Supervisor.Variance: replacement: "none" note: "The Supervisor abstraction and its variance marker were removed." effect/Supervisor#SupervisorTypeId: replacement: "none" note: "The Supervisor abstraction and its type identifier were removed." +effect/Supervisor#track: + replacement: "none" + note: "There is no built-in tracking Supervisor. Keep a `Set` of fibers in `onStart`/`onEnd` of a `Supervisor.Supervisor` (holding them weakly if they may block forever), or use `FiberSet` for fibers you fork yourself." effect/Supervisor#unsafeTrack: - replacement: "FiberSet" - note: "Use scoped FiberSet.make and explicitly run or add fibers; there is no unsafe unscoped ambient tracker." + replacement: "none" + note: "There is no built-in tracking Supervisor. Keep a `Set` of fibers in `onStart`/`onEnd` of a `Supervisor.Supervisor`, or use `FiberSet` for fibers you fork yourself." diff --git a/migration/v3-to-v4.md b/migration/v3-to-v4.md index 916789a566..bba8fbcb5e 100644 --- a/migration/v3-to-v4.md +++ b/migration/v3-to-v4.md @@ -738,7 +738,6 @@ effect/rpc/Utils (barrel: effect/rpc) - `effect/StreamHaltStrategy`: No single module replacement; follow the curated per-API guidance below. - `effect/Streamable` -> `none`: Removed in v4 with no direct replacement. Instead of extending Streamable.Class, expose the underlying stream as a value (e.g. a property or method built with Stream.suspend). - `effect/Subscribable`: No single module replacement; follow the curated per-API guidance below. -- `effect/Supervisor`: No single module replacement; follow the curated per-API guidance below. - `effect/TArray`: No single module replacement; follow the curated per-API guidance below. - `effect/TDeferred` -> `effect/TxDeferred` - `effect/TMap` -> `effect/TxHashMap` @@ -10274,7 +10273,7 @@ Arbitrary.schema(schema) - `Effect.summarized` -> `Effect.gen`: Run the summary Effect before and after the target Effect and combine the two measurements explicitly. Adapt arguments and imports to the v4 API. -- `Effect.supervised` -> `FiberSet`: Track explicitly forked Fibers in a scoped `FiberSet` instead of installing a runtime Supervisor. Adapt arguments and imports to the v4 API. +- `Effect.supervised` -> `Effect.withSupervisor`: `Effect.withSupervisor` adds a Supervisor for an effect, but now runs the effect in a new child fiber and joins it, so the effect's own fiber is observed too. To track fibers you fork yourself, use a scoped `FiberSet`. - `Effect.tagMetrics` -> `Metric.withAttributes`: Convert key/value tags to metric attributes. Adapt arguments and imports to the v4 API. @@ -11292,7 +11291,7 @@ FastCheck.uuid({ version: 4 }) - `Fiber.pretty` -> `none`: Runtime fiber pretty-printing was removed; format the public id and polled Exit explicitly. -- `Fiber.roots` -> `none`: The runtime no longer exposes a global root-fiber registry; track application fibers explicitly. +- `Fiber.roots` -> `none`: The runtime no longer exposes a global root-fiber registry; track application fibers explicitly, or install a `Supervisor.Supervisor` at the runtime with `Supervisor.layer` to discover them. - `Fiber.scoped` -> `Fiber.runIn`: Register the Fiber in an explicit Scope with Fiber.runIn; acquire the current Scope when migrating the old effectful form. @@ -11300,7 +11299,7 @@ FastCheck.uuid({ version: 4 }) - `Fiber.succeed` -> `Effect.runFork(Effect.succeed(value))`: Synthetic Fiber constructors were removed; run the corresponding Effect when a Fiber handle is required. -- `Fiber.unsafeRoots` -> `none`: The runtime no longer exposes a global root-fiber registry; track application fibers explicitly. +- `Fiber.unsafeRoots` -> `none`: The runtime no longer exposes a global root-fiber registry; track application fibers explicitly, or install a `Supervisor.Supervisor` at the runtime with `Supervisor.layer` to discover them. - `Fiber.void` -> `Effect.runFork(Effect.void)`: Synthetic Fiber constants were removed; run Effect.void when a completed Fiber\ is required. @@ -11422,7 +11421,7 @@ FastCheck.uuid({ version: 4 }) - `FiberRef.currentSchedulingPriority` -> `none`: The ambient scheduling-priority FiberRef was removed; use explicit scheduler operations where priority is needed. -- `FiberRef.currentSupervisor` -> `none`: The Supervisor and ambient supervisor FiberRef APIs were removed; track fibers explicitly with FiberSet or FiberMap. +- `FiberRef.currentSupervisor` -> `Supervisor.Supervisor`: `Supervisor.Supervisor` is the reference. A fiber reads it once, when it is created; providing it directly replaces the Supervisor in place, while `Supervisor.layer` and `Effect.withSupervisor` add to it. - `FiberRef.currentTracerEnabled` -> `References.TracerEnabled`: Built-in FiberRefs are now Context.Reference values; yield the reference or provide it with Effect.provideService. @@ -16300,23 +16299,25 @@ switch (strategy) { ### `effect/Supervisor` -- `Supervisor.AbstractSupervisor` -> `none`: The ambient Supervisor abstraction and runtime event hooks were removed. +- `Supervisor.AbstractSupervisor` -> `Supervisor.Supervisor`: Implement the `Supervisor.Supervisor` interface with an object literal or a class; there is no abstract base class. -- `Supervisor.Supervisor` -> `none`: Ambient fiber supervision was removed; use structured concurrency or explicit FiberSet and FiberMap tracking. +- `Supervisor.Supervisor` -> `Supervisor.Supervisor`: Now a plain interface with four required methods, `onStart`, `onEnd`, `onBlock` and `onUnblock`, and no `value` or `zip`. `onSuspend`/`onResume` became `onBlock`/`onUnblock`, which fire only when a fiber waits, never when it yields. There is no `onEffect`: use `Tracer.context` for per-operation interposition. `Supervisor.Supervisor` is also the reference that installs one. - `Supervisor.Supervisor.Variance` -> `none`: The Supervisor abstraction and its variance marker were removed. - `Supervisor.SupervisorTypeId` -> `none`: The Supervisor abstraction and its type identifier were removed. -- `Supervisor.addSupervisor` -> `none`: Layer-installed ambient supervision was removed; use structured concurrency and explicit FiberSet or FiberMap tracking. +- `Supervisor.addSupervisor` -> `Supervisor.layer`: `Supervisor.layer` adds a Supervisor to the one in place, as `addSupervisor` did. Under a built `ManagedRuntime` it observes the root fibers; under `Layer.launch` or a platform `runMain` only forks, so use `Effect.withSupervisor` around `main`. -- `Supervisor.fibersIn` -> `FiberSet`: Use a scoped FiberSet and explicitly run or add fibers; it does not ambiently observe every descendant. +- `Supervisor.fibersIn` -> `FiberSet`: Use a scoped FiberSet and explicitly run or add fibers. To observe every descendant instead, install a `Supervisor.Supervisor` and keep a set in `onStart`/`onEnd`. - `Supervisor.fromEffect` -> `none`: The Supervisor abstraction and its effect-valued observation hook were removed. -- `Supervisor.none` -> `none`: The Supervisor abstraction was removed; normal structured concurrency needs no no-op supervisor. +- `Supervisor.none` -> `undefined`: There is no no-op Supervisor: `undefined` means none. Provide `undefined` to `Supervisor.Supervisor` to opt a region's forks out. -- `Supervisor.unsafeTrack` -> `FiberSet`: Use scoped FiberSet.make and explicitly run or add fibers; there is no unsafe unscoped ambient tracker. +- `Supervisor.track` -> `none`: There is no built-in tracking Supervisor. Keep a `Set` of fibers in `onStart`/`onEnd` of a `Supervisor.Supervisor` (holding them weakly if they may block forever), or use `FiberSet` for fibers you fork yourself. + +- `Supervisor.unsafeTrack` -> `none`: There is no built-in tracking Supervisor. Keep a `Set` of fibers in `onStart`/`onEnd` of a `Supervisor.Supervisor`, or use `FiberSet` for fibers you fork yourself. ### `effect/Symbol` diff --git a/packages/effect/src/Deferred.ts b/packages/effect/src/Deferred.ts index 663d79a2dd..73af054be2 100644 --- a/packages/effect/src/Deferred.ts +++ b/packages/effect/src/Deferred.ts @@ -190,7 +190,7 @@ const _await = (self: Deferred): Effect => const index = resumes.indexOf(resume) if (index >= 0) resumes.splice(index, 1) }) - }) + }, { blockedOn: self }) export { /** diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 90257c94da..4bdb34d3d0 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -46,6 +46,7 @@ import type * as Result from "./Result.ts" import type { Metadata as ScheduleMetadata, Schedule } from "./Schedule.ts" import type { Scheduler } from "./Scheduler.ts" import type { Scope } from "./Scope.ts" +import * as Supervisor from "./Supervisor.ts" import type { AnySpan, ParentSpan, @@ -1254,6 +1255,11 @@ export { * the fiber; later calls are ignored. Return an optional cleanup effect from * the registration function to run if the fiber is interrupted. * + * Pass `blockedOn` when only the program itself can complete the wait, as in + * a custom synchronization primitive. A `Supervisor` receives it in + * `onBlock` while the fiber waits; without it, `onBlock` receives + * `undefined`. + * * **Gotchas** * * The parameter check reads the registration function's `length` property, @@ -1290,7 +1296,10 @@ export const callback: ( this: Scheduler, resume: (effect: Effect) => void, signal: AbortSignal - ) => void | Effect + ) => void | Effect, + options?: { + readonly blockedOn?: object | undefined + } | undefined ) => Effect = internal.callback /** @@ -15183,6 +15192,39 @@ export const withLogger: { (loggers) => new Set([...loggers, logger]) )) +/** + * Runs an effect in a new child fiber whose context adds `supervisor` to the + * Supervisor in place, and joins it. + * + * **Details** + * + * It forks so that the region's own fiber is observed, as well as everything + * it forks: inside, `Fiber.getCurrent()` is the child, and a Supervisor + * already in place sees the caller block on that child. + * + * @stability experimental + * @category forking + * @since 4.1.2 + */ +export const withSupervisor: { + (supervisor: Supervisor.Supervisor): (self: Effect) => Effect + (self: Effect, supervisor: Supervisor.Supervisor): Effect +} = dual( + 2, + (self: Effect, supervisor: Supervisor.Supervisor): Effect => + core.withFiber((fiber) => { + const current = fiber.getRef(Supervisor.Supervisor) + return internal.flatMap( + internal.provideService( + internal.forkChild(self, { startImmediately: true, uninterruptible: "inherit" }), + Supervisor.Supervisor, + current === undefined ? supervisor : Supervisor.combine(current, supervisor) + ), + (child) => internal.onInterrupt(internal.fiberJoin(child), () => internal.fiberInterrupt(child)) + ) + }) +) + /** * Adds an annotation to each log line in this effect. * @@ -15981,8 +16023,9 @@ const isTransactionConsistent = (state: TransactionMeta) => { return true } -const awaitPendingTransaction = (state: TransactionMeta) => - callback((resume) => { +const awaitPendingTransaction = (state: TransactionMeta) => { + const refs = Array.from(state.journal.keys()) + return internal.callback((resume) => { // Validate the read set and register the waiter in one synchronous step. // A commit that landed after the reads has already signalled its waiters // and will not signal this one, so a stale read set reruns immediately. @@ -15990,7 +16033,6 @@ const awaitPendingTransaction = (state: TransactionMeta) => return resume(void_) } const key = {} - const refs = Array.from(state.journal.keys()) const clearPending = () => { for (const clear of refs) { clear.pending.delete(key) @@ -16004,7 +16046,8 @@ const awaitPendingTransaction = (state: TransactionMeta) => ref.pending.set(key, onCall) } return sync(clearPending) - }) + }, { blockedOn: refs }) +} function commitTransaction(fiber: Fiber, state: TransactionMeta) { for (const [ref, { value, written }] of state.journal) { diff --git a/packages/effect/src/Fiber.ts b/packages/effect/src/Fiber.ts index 672e12429a..ef735fdb1b 100644 --- a/packages/effect/src/Fiber.ts +++ b/packages/effect/src/Fiber.ts @@ -20,6 +20,7 @@ import { hasProperty } from "./Predicate.ts" import type { StackFrame } from "./References.ts" import type { Scheduler, SchedulerDispatcher } from "./Scheduler.ts" import type { Scope } from "./Scope.ts" +import type { Supervisor } from "./Supervisor.ts" import type { AnySpan, Tracer } from "./Tracer.ts" import type { Covariant } from "./Types.ts" @@ -170,7 +171,7 @@ export declare namespace Fiber { * @category models * @since 4.0.0 */ - export interface Cache { + export interface Cache extends CacheExperimental { readonly scheduler: Scheduler readonly tracer: Tracer | undefined readonly tracerContext: Tracer["context"] | undefined @@ -185,6 +186,15 @@ export declare namespace Fiber { } } +interface CacheExperimental { + /** + * The Supervisor installed in the fiber's context, if any. + * + * @stability experimental + */ + readonly supervisor?: Supervisor | undefined +} + const await_: (self: Fiber) => Effect> = effect.fiberAwait export { /** diff --git a/packages/effect/src/Latch.ts b/packages/effect/src/Latch.ts index 59c2c47874..78c0f933f8 100644 --- a/packages/effect/src/Latch.ts +++ b/packages/effect/src/Latch.ts @@ -163,6 +163,20 @@ export interface Latch { */ export const makeUnsafe: (open?: boolean | undefined) => Latch = internal.makeLatchUnsafe +/** + * Checks whether a value is a `Latch`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries before treating them as + * `Latch` values. + * + * @stability stable + * @category guards + * @since 4.1.2 + */ +export const isLatch: (u: unknown) => u is Latch = internal.isLatch + /** * Creates a `Latch` inside `Effect`. * diff --git a/packages/effect/src/PartitionedSemaphore.ts b/packages/effect/src/PartitionedSemaphore.ts index 13df19ddfd..129fc86970 100644 --- a/packages/effect/src/PartitionedSemaphore.ts +++ b/packages/effect/src/PartitionedSemaphore.ts @@ -14,6 +14,7 @@ import { dual } from "./Function.ts" import * as internalEffect from "./internal/effect.ts" import * as MutableHashMap from "./MutableHashMap.ts" import * as Option from "./Option.ts" +import { hasProperty } from "./Predicate.ts" /** * Runtime type identifier used to mark values that implement @@ -30,6 +31,21 @@ import * as Option from "./Option.ts" */ export const PartitionedTypeId: PartitionedTypeId = "~effect/PartitionedSemaphore" +/** + * Checks whether a value is a `PartitionedSemaphore`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries before treating them as + * `PartitionedSemaphore` values. + * + * @stability stable + * @category guards + * @since 4.1.2 + */ +export const isPartitionedSemaphore = (u: unknown): u is PartitionedSemaphore => + hasProperty(u, PartitionedTypeId) + /** * Literal type of the `PartitionedSemaphore` runtime type identifier. * @@ -228,7 +244,7 @@ export const makeUnsafe = (options: { return Effect.void } - return Effect.callback((resume) => { + return internalEffect.callback((resume) => { if (totalPermits >= permits) { resume(take(key, permits)) return @@ -272,7 +288,7 @@ export const makeUnsafe = (options: { waitingPermits -= entry.permits releaseUnsafe(permits - entry.permits) }) - }) + }, { blockedOn: self }) }) } @@ -310,7 +326,7 @@ export const makeUnsafe = (options: { return true } - return { + const self: PartitionedSemaphore = { [PartitionedTypeId]: PartitionedTypeId, capacity: maxPermits, available: Effect.sync(() => totalPermits), @@ -338,6 +354,7 @@ export const makeUnsafe = (options: { }) } } + return self } /** diff --git a/packages/effect/src/Pool.ts b/packages/effect/src/Pool.ts index 17796d36f4..d0a3a74522 100644 --- a/packages/effect/src/Pool.ts +++ b/packages/effect/src/Pool.ts @@ -744,7 +744,7 @@ const waitForItem = (self: Pool, waiter: Waiter): Effect.Effec state.waiters.delete(waiter) } }) - }) + }, { blockedOn: self }) const wakeWaiters = (self: Pool, fiber: Fiber.Fiber, count: number) => { const waiters = self.state.waiters diff --git a/packages/effect/src/PubSub.ts b/packages/effect/src/PubSub.ts index 44d9444add..1611f368b9 100644 --- a/packages/effect/src/PubSub.ts +++ b/packages/effect/src/PubSub.ts @@ -19,6 +19,7 @@ import * as Exit from "./Exit.ts" import type { LazyArg } from "./Function.ts" import { dual, identity } from "./Function.ts" import * as Count from "./internal/count.ts" +import * as internalEffect from "./internal/effect.ts" import * as Latch from "./Latch.ts" import * as MutableList from "./MutableList.ts" import * as MutableRef from "./MutableRef.ts" @@ -170,13 +171,18 @@ export declare namespace PubSub { * * The publisher may have yielded since `publish` checked `ended`, so it * must be checked again before registering or publishing the surplus. + * + * `owner` is the `PubSub` being published to. A strategy that makes the + * publisher wait reports it to the publisher's `Supervisor` as what the + * publisher is blocked on (since 4.1.2). */ handleSurplus( pubsub: Atomic, subscribers: Subscribers, elements: Iterable, isShutdown: MutableRef.MutableRef, - ended: MutableRef.MutableRef> + ended: MutableRef.MutableRef>, + owner?: PubSub ): Effect.Effect /** @@ -240,6 +246,20 @@ export const isPubSub = (u: unknown): u is PubSub => hasProperty const SubscriptionTypeId = "~effect/PubSub/Subscription" +/** + * Checks whether a value is a `Subscription`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries before treating them as + * `Subscription` values. + * + * @stability stable + * @category guards + * @since 4.1.2 + */ +export const isSubscription = (u: unknown): u is Subscription => hasProperty(u, SubscriptionTypeId) + /** * A subscription represents a consumer's connection to a PubSub, allowing them to take messages. * @@ -1095,7 +1115,8 @@ export const publish: { self.subscribers, [value], self.shutdownFlag, - self.ended + self.ended, + self ) })) @@ -1200,7 +1221,8 @@ export const publishAll: { self.subscribers, surplus, self.shutdownFlag, - self.ended + self.ended, + self ) })) @@ -1394,7 +1416,7 @@ export const takeAll = (self: Subscription): Effect.Effect(self: Subscription) => - Effect.callback((resume) => { + internalEffect.callback((resume) => { if (self.shutdownFlag.current) return resume(Effect.interrupt) if (Option.isSome(self.ended.current)) { // Messages may have been published after the empty check, before this callback ran. @@ -1424,7 +1446,7 @@ const pollForItem = (self: Subscription) => if (deferred.effect) return resume(deferred.effect) deferred.resumes = [resume] return Effect.sync(() => MutableList.remove(self.pollers, deferred)) - }) + }, { blockedOn: self }) /** * Takes up to the specified number of messages from the subscription without @@ -2585,9 +2607,10 @@ export class BackPressureStrategy implements PubSub.Strategy { subscribers: PubSub.Subscribers, elements: Iterable, isShutdown: MutableRef.MutableRef, - ended: MutableRef.MutableRef> + ended: MutableRef.MutableRef>, + owner?: PubSub ): Effect.Effect { - return Effect.callback((resume) => { + return internalEffect.callback((resume) => { // The publisher may have yielded since `publish` checked `ended`, and // `end` only rejects publishers that are already registered. if (Option.isSome(ended.current)) return resume(Effect.succeed(false)) @@ -2602,7 +2625,7 @@ export class BackPressureStrategy implements PubSub.Strategy { if (deferred.effect) return resume(deferred.effect) deferred.resumes = [resume] return Effect.sync(() => this.removeUnsafe(deferred)) - }) + }, { blockedOn: owner }) } onPubSubEmptySpaceUnsafe( diff --git a/packages/effect/src/Queue.ts b/packages/effect/src/Queue.ts index c499bbaf47..a6e7b6493c 100644 --- a/packages/effect/src/Queue.ts +++ b/packages/effect/src/Queue.ts @@ -808,7 +808,7 @@ export const offerAll: { return resume(core.exitSucceed(remaining)) } return waitToOffer(self, { _tag: "Array", remaining, offset: 0, resume }) - })) + }, { blockedOn: self })) /** * Adds multiple messages to the queue synchronously. Returns the remaining messages that @@ -1733,7 +1733,7 @@ const await_ = (self: Dequeue): Effect> => self.state.awaiters.delete(awaiter) } }) - }) + }, { blockedOn: self }) export { /** @@ -2065,11 +2065,12 @@ const awaitTake = (self: Dequeue, ready: () => boolean) => return internalEffect.sync(() => { if (self.state._tag !== "Done") self.state.takers.delete(taker) }) - }) + }, { blockedOn: self }) const offerOrWait = (self: Enqueue, message: A) => - internalEffect.callback((resume) => - offerUnsafe(self, message) ? resume(exitTrue) : waitToOffer(self, { _tag: "Single", message, resume }) + internalEffect.callback( + (resume) => offerUnsafe(self, message) ? resume(exitTrue) : waitToOffer(self, { _tag: "Single", message, resume }), + { blockedOn: self } ) const waitToOffer = (self: Enqueue, entry: Queue.OfferEntry) => { diff --git a/packages/effect/src/RequestResolver.ts b/packages/effect/src/RequestResolver.ts index dd78faa103..fe770d228d 100644 --- a/packages/effect/src/RequestResolver.ts +++ b/packages/effect/src/RequestResolver.ts @@ -17,6 +17,7 @@ import * as Context from "./Context.ts" import type * as Duration from "./Duration.ts" import * as Effect from "./Effect.ts" import * as Exit from "./Exit.ts" +import type * as Fiber from "./Fiber.ts" import { constTrue, dual, identity } from "./Function.ts" import { exitSucceed } from "./internal/core.ts" import * as Count from "./internal/count.ts" @@ -475,8 +476,9 @@ export const fromEffect = ( f: (entry: Request.Entry) => Effect.Effect, Request.Error> ): RequestResolver => { effect.interruptChildrenPatch() // ensure middleware is registered - return make((entries) => - Effect.callback((resume) => { + return make((entries) => { + const fibers = new Set>() + return effect.callback((resume) => { const parent = effect.getCurrentFiber()! let done = 0 for (let i = 0; i < entries.length; i++) { @@ -486,6 +488,7 @@ export const fromEffect = ( effect.setContext(f(entry), entry.context), true ) + fibers.add(fiber) fiber.addObserver((exit) => { entry.completeUnsafe(exit) done++ @@ -494,8 +497,8 @@ export const fromEffect = ( } }) } - }) - ) + }, { blockedOn: fibers }) + }) } /** diff --git a/packages/effect/src/Semaphore.ts b/packages/effect/src/Semaphore.ts index 54eb829b37..93bf196ec8 100644 --- a/packages/effect/src/Semaphore.ts +++ b/packages/effect/src/Semaphore.ts @@ -17,6 +17,7 @@ import { dual, identity } from "./Function.ts" import * as core from "./internal/core.ts" import * as internal from "./internal/effect.ts" import type * as Option from "./Option.ts" +import { hasProperty } from "./Predicate.ts" import type * as Scope from "./Scope.ts" /** @@ -233,6 +234,20 @@ export interface Semaphore { */ export const makeUnsafe = (permits: number): Semaphore => new SemaphoreImpl(permits) +/** + * Checks whether a value is a `Semaphore`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries before treating them as + * `Semaphore` values. + * + * @stability stable + * @category guards + * @since 4.1.2 + */ +export const isSemaphore = (u: unknown): u is Semaphore => hasProperty(u, TypeId) + interface Waiter { readonly permits: number resume: ((effect: Effect.Effect) => void) | undefined @@ -273,7 +288,7 @@ const takePermits = ( } else { waiter.resume = resume } - })) + }, { blockedOn: self })) const loop: Effect.Effect = internal.flatMap(wait, () => { if (firstAvailableWaiter(self) !== waiter) return loop self.taken += n @@ -283,7 +298,10 @@ const takePermits = ( return loop }) +const TypeId = "~effect/Semaphore" + class SemaphoreImpl implements Semaphore { + readonly [TypeId] = TypeId public waiters = new Set() public taken = 0 public permits: number diff --git a/packages/effect/src/Supervisor.ts b/packages/effect/src/Supervisor.ts new file mode 100644 index 0000000000..0fe364718e --- /dev/null +++ b/packages/effect/src/Supervisor.ts @@ -0,0 +1,290 @@ +/** + * Observes the lifecycles of fibers: when each one starts, blocks, unblocks + * and ends, and what a blocked fiber waits on. + * + * A Supervisor only observes. Use it to know which fibers a part of a program + * started and what each one is doing, for example in a test runner that + * reports the fibers a test left running, or a diagnostic dump of a program + * that hangs. + * + * **Installing a Supervisor** + * + * A fiber reports to the Supervisor in its context when it is created, for + * its whole life. So where a Supervisor is installed decides which fibers it + * sees: + * + * - `Effect.withSupervisor(effect, supervisor)` runs the effect in a new child + * fiber and sees that fiber and everything it forks. Use it around `main`. + * - `Supervisor.layer(supervisor)` sees the root fibers of a built + * `ManagedRuntime` and what they fork. Under `Layer.launch`, a platform + * `runMain`, or a `ManagedRuntime` that is not built yet, the root fiber + * exists before the layer, so only forks are seen. + * - `Effect.provideService(Supervisor.Supervisor, supervisor)` and + * `Effect.provide(layer)` inside a fiber see only the fibers forked inside + * the region, never the fiber already running it. + * + * `withSupervisor` and `layer` add to the Supervisor in place, which is + * called first; adding one already in place changes nothing. Providing the + * reference directly replaces it, and providing `undefined` opts a region's + * forks out. + * + * **What a blocked fiber waits on** + * + * `onBlock` receives the object the fiber waits on. A defined value means + * only the program itself can complete the wait; `undefined` means something + * outside the program may (I/O, a timer, a promise). The objects are: + * + * - `Deferred.await`: the Deferred. + * - Queue take, offer and await: the Queue. + * - `PubSub` publish (back-pressure): the PubSub. `PubSub` take: the + * Subscription. + * - `Latch` await: the Latch. + * - `Semaphore`, `PartitionedSemaphore`: the semaphore. + * - `Pool` get: the Pool. + * - `Fiber.await`, `Fiber.join`: the fiber. + * - `Fiber.awaitAll`, `Fiber.joinAll`: an array of the fibers. + * - `Effect.race` and its variants, a concurrent `Effect.forEach` (and what is + * built on it), `RequestResolver.fromEffect`: the `Set` of fibers it forked. + * - A transaction's retry: an array of the `TxRef`s it read. `TxQueue`, + * `TxDeferred` and the other Tx structures show up as their `TxRef`s. + * - `Effect.never`: `Effect.never` itself. + * - A `TestClock` sleep: the Latch of that sleep (see `TestClock.stateUnsafe`). + * - `Effect.callback`: its `blockedOn` option. + * - `Effect.promise`, `Effect.tryPromise`, a sleep on the live clock, and + * anything else: `undefined`. + * + * A collection means "these fibers" (or "these refs"), not whether the wait + * completes on one of them or on all of them. It is full when `onBlock` is + * called. Narrow with the guards `Deferred.isDeferred`, `Queue.isQueue`, + * `PubSub.isPubSub`, `PubSub.isSubscription`, `Latch.isLatch`, + * `Semaphore.isSemaphore`, `PartitionedSemaphore.isPartitionedSemaphore`, + * `Pool.isPool`, `Fiber.isFiber`, `TxRef.isTxRef`, with `Array.isArray` and + * `instanceof Set`, and by identity for `Effect.never`. More waits may be + * labelled in later versions. + * + * **Example** (Keeping a weak set of live fibers) + * + * ```ts import.meta.vitest + * import { Effect, Fiber, Supervisor } from "effect" + * + * // WeakRefs let fibers that block forever be collected; the WeakMap keeps + * // per-fiber state without pinning the fiber or what it waits on + * const live = new Set>>() + * const refs = new WeakMap, WeakRef>>() + * const waitingOn = new WeakMap, object | undefined>() + * const registry = new FinalizationRegistry>>((ref) => live.delete(ref)) + * + * const tracker: Supervisor.Supervisor = { + * onStart: (fiber) => { + * const ref = new WeakRef(fiber) + * live.add(ref) + * refs.set(fiber, ref) + * registry.register(fiber, ref) + * }, + * onEnd: (fiber) => { + * const ref = refs.get(fiber) + * if (ref !== undefined) live.delete(ref) + * }, + * onBlock: (fiber, blockedOn) => waitingOn.set(fiber, blockedOn), + * onUnblock: (fiber) => waitingOn.delete(fiber) + * } + * + * const program = Effect.gen(function*() { + * yield* Effect.forkChild(Effect.never) + * yield* Effect.yieldNow + * return Array.from(live, (ref) => ref.deref()).filter((fiber) => fiber !== undefined).length + * }) + * + * await Effect.runPromise(Effect.withSupervisor(program, tracker)) // => 2 + * ``` + * + * @stability experimental + * @since 4.1.2 + */ +import * as Context from "./Context.ts" +import type * as Exit from "./Exit.ts" +import type * as Fiber from "./Fiber.ts" +import { constUndefined, dual } from "./Function.ts" +import { withFiber } from "./internal/core.ts" +import * as effect from "./internal/effect.ts" +import * as Layer from "./Layer.ts" +import { hasProperty } from "./Predicate.ts" + +/** + * Receives the lifecycle events of the fibers created in a context that + * provides it through the {@link Supervisor} reference. + * + * **When to use** + * + * Use to observe which fibers a part of a program starts and what each one + * waits on. Implement it with an object literal or a class. + * + * **Details** + * + * - `onStart` is called when a fiber is created, before it runs. `parent` is + * the fiber that forked it, attached or detached, and `undefined` for a root + * fiber (`Effect.runFork` and friends), even one started inside another + * fiber. + * - `onBlock` is called when a fiber suspends on a wait that did not complete + * at once. Yielding to the scheduler is not blocking. `blockedOn` is what it + * waits on (see the module documentation). + * - `onUnblock` is called when the fiber leaves that wait, because it + * completed or because the fiber was interrupted, before the fiber runs + * again. + * - `onEnd` is called once, when the fiber's exit is set. + * + * For each fiber, `onStart` comes first, then pairs of `onBlock` and + * `onUnblock` with no other event of that fiber between them, then at most + * one `onEnd`, never while blocked. A child's `onStart` comes before its + * forker continues, and a fiber's `onEnd` comes before any fiber waiting on + * it is unblocked. Nothing else about the order across fibers is promised. + * A fiber that is never unblocked gets no further event, so a long-lived + * Supervisor should hold fibers weakly. + * + * **Gotchas** + * + * The methods are called synchronously inside the runtime. They may read the + * fiber (`id`, `getRef`, `pollUnsafe`) and update the Supervisor's own state, + * and must be cheap. They must not throw, and must not act on the runtime: + * no interrupting, resuming (`Deferred.doneUnsafe`, `Queue.offerUnsafe`, ...), + * forking, running effects, `setContext` or `addObserver`. To act, defer the + * work with `queueMicrotask` or a scheduler task. A method that throws or acts + * leaves the runtime in an unspecified state: fibers may hang, a fiber may be + * killed, and the order above no longer holds. + * + * **Example** (Counting the fibers a program starts) + * + * ```ts import.meta.vitest + * import { Effect, Fiber, Supervisor } from "effect" + * + * let started = 0 + * const counter: Supervisor.Supervisor = { + * onStart: () => started++, + * onEnd: () => {}, + * onBlock: () => {}, + * onUnblock: () => {} + * } + * + * const program = Effect.gen(function*() { + * const fibers = yield* Effect.forEach([1, 2, 3], (n) => Effect.forkChild(Effect.succeed(n * 2))) + * return yield* Fiber.joinAll(fibers) + * }) + * + * await Effect.runPromise(Effect.withSupervisor(program, counter)) // => [2, 4, 6] + * // the region's own fiber and the three forks + * started // => 4 + * ``` + * + * @stability experimental + * @category models + * @since 4.1.2 + */ +export interface Supervisor { + readonly onStart: (fiber: Fiber.Fiber, parent: Fiber.Fiber | undefined) => void + readonly onEnd: (fiber: Fiber.Fiber, exit: Exit.Exit) => void + readonly onBlock: (fiber: Fiber.Fiber, blockedOn: object | undefined) => void + readonly onUnblock: (fiber: Fiber.Fiber) => void +} + +/** + * The {@link Supervisor} the fibers created in this context report to; none + * by default. + * + * **Details** + * + * A fiber reads it once, when it is created. Providing a value directly + * replaces the Supervisor in place, and providing `undefined` opts the + * region's forks out; use {@link layer} or `Effect.withSupervisor` to add one + * instead. Inside a region with several Supervisors, it holds their + * combination, so keep your own reference to your Supervisor if you need it. + * + * @stability experimental + * @category references + * @since 4.1.2 + */ +export const Supervisor: Context.Reference = Context.Reference( + effect.SupervisorKey, + { fiberCached: true, defaultValue: constUndefined } +) + +const CombinedTypeId = "~effect/Supervisor/Combined" + +class Combined implements Supervisor { + readonly [CombinedTypeId] = CombinedTypeId + readonly members: ReadonlyArray + constructor(members: ReadonlyArray) { + this.members = members + } + onStart(fiber: Fiber.Fiber, parent: Fiber.Fiber | undefined) { + for (const member of this.members) member.onStart(fiber, parent) + } + onEnd(fiber: Fiber.Fiber, exit: Exit.Exit) { + for (const member of this.members) member.onEnd(fiber, exit) + } + onBlock(fiber: Fiber.Fiber, blockedOn: object | undefined) { + for (const member of this.members) member.onBlock(fiber, blockedOn) + } + onUnblock(fiber: Fiber.Fiber) { + for (const member of this.members) member.onUnblock(fiber) + } +} + +const membersOf = (supervisor: Supervisor): ReadonlyArray => + hasProperty(supervisor, CombinedTypeId) ? (supervisor as Combined).members : [supervisor] + +/** + * Combines two Supervisors into one that calls `outer`, then `inner`, on + * every hook. + * + * **When to use** + * + * Use to install several Supervisors at once, for example at a root with + * `Effect.runForkWith`. + * + * **Details** + * + * Supervisors are compared by identity, and each one is called once even + * when `outer` and `inner` overlap: `combine(a, a)` is `a`, and when every + * Supervisor of `inner` is already part of `outer`, the result is `outer`. + * + * @stability experimental + * @category combinators + * @since 4.1.2 + */ +export const combine: { + (inner: Supervisor): (outer: Supervisor) => Supervisor + (outer: Supervisor, inner: Supervisor): Supervisor +} = dual( + 2, + (outer: Supervisor, inner: Supervisor): Supervisor => { + const members = membersOf(outer) + const added = membersOf(inner).filter((member) => !members.includes(member)) + return added.length === 0 ? outer : new Combined([...members, ...added]) + } +) + +/** + * A layer that adds `supervisor` to the Supervisor in place. + * + * **Details** + * + * The Supervisor in place, if any, is still called first. Under a built + * `ManagedRuntime` the root fibers are observed; under `Layer.launch`, a + * platform `runMain`, or `Effect.provide` inside a fiber, only the fibers + * forked after the layer is built are. Use `Effect.withSupervisor` around + * `main` to observe the main fiber. To replace the Supervisor in place + * instead, use `Layer.succeed(Supervisor.Supervisor)(supervisor)`. Unlike + * `Logger.layer`, adding is the default. + * + * @stability experimental + * @category layers + * @since 4.1.2 + */ +export const layer = (supervisor: Supervisor): Layer.Layer => + Layer.effect( + Supervisor, + withFiber((fiber) => { + const current = fiber.getRef(Supervisor) + return effect.succeed(current === undefined ? supervisor : combine(current, supervisor)) + }) + ) diff --git a/packages/effect/src/TxRef.ts b/packages/effect/src/TxRef.ts index 2819ff57f2..547ff6d5fe 100644 --- a/packages/effect/src/TxRef.ts +++ b/packages/effect/src/TxRef.ts @@ -17,6 +17,7 @@ import type { TransactionMetaInner } from "./Effect.ts" import { dual } from "./Function.ts" import { pipeArguments } from "./Pipeable.ts" import type { Pipeable } from "./Pipeable.ts" +import { hasProperty } from "./Predicate.ts" import type { NoInfer } from "./Types.ts" const TypeId = "~effect/TxRef" @@ -69,6 +70,20 @@ export interface TxRef extends Pipeable { value: A } +/** + * Checks whether a value is a `TxRef`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries before treating them as + * `TxRef` values. + * + * @stability stable + * @category guards + * @since 4.1.2 + */ +export const isTxRef = (u: unknown): u is TxRef => hasProperty(u, TypeId) + /** * Creates a new `TxRef` with the specified initial value. * diff --git a/packages/effect/src/index.ts b/packages/effect/src/index.ts index 621b878590..8f7c320520 100644 --- a/packages/effect/src/index.ts +++ b/packages/effect/src/index.ts @@ -764,6 +764,12 @@ export * as Struct from "./Struct.ts" */ export * as SubscriptionRef from "./SubscriptionRef.ts" +/** + * @stability experimental + * @since 4.1.2 + */ +export * as Supervisor from "./Supervisor.ts" + /** * @stability stable * @since 2.0.0 diff --git a/packages/effect/src/internal/effect.ts b/packages/effect/src/internal/effect.ts index e5c8c4a26e..0dcdbb29b9 100644 --- a/packages/effect/src/internal/effect.ts +++ b/packages/effect/src/internal/effect.ts @@ -28,6 +28,7 @@ import type { StackFrame } from "../References.ts" import * as Result from "../Result.ts" import * as Scheduler from "../Scheduler.ts" import type * as Scope from "../Scope.ts" +import type * as Supervisor from "../Supervisor.ts" import * as Tracer from "../Tracer.ts" import type { Concurrency, @@ -514,6 +515,9 @@ const AsyncResource: (new(type: string) => AsyncContext) | undefined = (() => { const captureAsyncContext = (): AsyncContext | undefined => AsyncResource === undefined ? undefined : new AsyncResource("effect/Fiber") +/** @internal */ +export const SupervisorKey = "effect/Supervisor" + /** @internal */ export const getCurrentFiber = (): Fiber.Fiber | undefined => (globalThis as any)[currentFiberTypeId] @@ -521,7 +525,8 @@ export const getCurrentFiber = (): Fiber.Fiber | undefined => (globalT export class FiberImpl implements Fiber.Fiber { constructor( context: Context.Context, - interruptible: boolean = true + interruptible: boolean = true, + parent?: FiberImpl ) { this.setContext(context) this.id = ++fiberIdStore.id @@ -538,6 +543,8 @@ export class FiberImpl implements Fiber.Fiber { this._parent = undefined this._asyncContext = undefined this.cache.runtimeMetrics?.recordFiberStart(this.context) + this.supervisor = this.cache.supervisor + this.supervisor?.onStart(this, parent) } get [FiberTypeId](): Fiber.Fiber.Variance { @@ -546,6 +553,7 @@ export class FiberImpl implements Fiber.Fiber { declare readonly id: number declare interruptible: boolean + declare readonly supervisor: Supervisor.Supervisor | undefined declare currentOpCount: number declare readonly _stack: Array declare _observers: Array<(exit: Exit.Exit) => void> | undefined @@ -651,6 +659,7 @@ export class FiberImpl implements Fiber.Fiber { this._parent._children?.delete(this) this._parent = undefined } + this.supervisor?.onEnd(this, exit) if (this._observers !== undefined) { const observers = this._observers this._observers = undefined @@ -802,6 +811,7 @@ const makeFiberContextCache = (context: Context.Context): Fiber.Fiber.Cac minimumLogLevel: Context.get(context, MinimumLogLevel), stackFrame: Context.get(context, CurrentStackFrame), runtimeMetrics: Context.getOrUndefinedUnsafe(context, InternalMetric.FiberRuntimeMetricsKey), + supervisor: Context.getOrUndefinedUnsafe(context, SupervisorKey), maxOpsBeforeYield: Context.get(context, Scheduler.MaxOpsBeforeYield), preventYield: Context.get(context, Scheduler.PreventSchedulerYield) } @@ -848,7 +858,7 @@ export const fiberAwait = ( return callback((resume) => { if (impl._exit) return resume(succeed(impl._exit)) return sync(self.addObserver((exit) => resume(succeed(exit)))) - }) + }, { blockedOn: impl }) } /** @internal */ @@ -862,28 +872,31 @@ export const fiberAwaitAll = >( > > > => - callback((resume) => { - const iter = self[Symbol.iterator]() as Iterator - const exits: Array> = [] - let cancel: (() => void) | undefined = undefined - function loop() { - let result = iter.next() - while (!result.done) { - if (result.value._exit) { - exits.push(result.value._exit) - result = iter.next() - continue + suspend(() => { + // Read once, when the effect runs: the Supervisor gets this array, and a + // one-shot iterable is not consumed twice + const fibers = Array.from(self as Iterable) as Array + return callback((resume) => { + const exits: Array> = [] + let cancel: (() => void) | undefined = undefined + function loop() { + while (exits.length < fibers.length) { + const fiber = fibers[exits.length] + if (fiber._exit) { + exits.push(fiber._exit) + continue + } + cancel = fiber.addObserver((exit) => { + exits.push(exit) + loop() + }) + return } - cancel = result.value.addObserver((exit) => { - exits.push(exit) - loop() - }) - return + resume(succeed(exits)) } - resume(succeed(exits)) - } - loop() - return sync(() => cancel?.()) + loop() + return sync(() => cancel?.()) + }, { blockedOn: fibers }) }) /** @internal */ @@ -893,7 +906,7 @@ export const fiberJoin = (self: Fiber.Fiber): Effect.Effect => return callback((resume) => { if (impl._exit) return resume(impl._exit) return sync(self.addObserver(resume)) - }) + }, { blockedOn: impl }) } /** @internal */ @@ -901,39 +914,41 @@ export const fiberJoinAll = >>(self: A) Arr.ReadonlyArray.With> ? _A : never>, A extends Iterable> ? _E : never > => - callback((resume) => { + suspend(() => { const fibers = Array.from(self) as Array - if (fibers.length === 0) return resume(succeed(Arr.empty() as any)) - const out = new Array(fibers.length) as Arr.NonEmptyArray - const observers = Arr.empty<(exit: Exit.Exit) => void>() - const removeObservers = () => { - for (let i = 0; i < observers.length; i++) { - fibers[i].removeObserver(observers[i]) - } - } - let done = 0 - let failed = false - for (let i = 0; i < fibers.length; i++) { - if (failed) break - const observer = (exit: Exit.Exit) => { - done++ - if (exit._tag === "Failure") { - failed = true - removeObservers() - return resume(exit as any) - } - out[i] = exit.value - if (done === fibers.length) { - resume(succeed(out)) + if (fibers.length === 0) return succeed(Arr.empty() as any) + return callback((resume) => { + const out = new Array(fibers.length) as Arr.NonEmptyArray + const observers = Arr.empty<(exit: Exit.Exit) => void>() + const removeObservers = () => { + for (let i = 0; i < observers.length; i++) { + fibers[i].removeObserver(observers[i]) } } - observers.push(observer) - fibers[i].addObserver(observer) - } - return sync(() => { - failed = true - removeObservers() - }) + let done = 0 + let failed = false + for (let i = 0; i < fibers.length; i++) { + if (failed) break + const observer = (exit: Exit.Exit) => { + done++ + if (exit._tag === "Failure") { + failed = true + removeObservers() + return resume(exit as any) + } + out[i] = exit.value + if (done === fibers.length) { + resume(succeed(out)) + } + } + observers.push(observer) + fibers[i].addObserver(observer) + } + return sync(() => { + failed = true + removeObservers() + }) + }, { blockedOn: fibers }) }) /** @internal */ @@ -1195,7 +1210,8 @@ const callbackOptions: ( resume: (effect: Effect.Effect) => void, signal?: AbortSignal ) => void | Effect.Effect, - withSignal: boolean + withSignal: boolean, + blockedOn?: object ) => Effect.Effect = (function() { const Proto = makePrimitiveProto({ op: "Async", @@ -1214,10 +1230,20 @@ const callbackOptions: ( }, controller?.signal) if (yielded !== false) return yielded yielded = true - // V8 pretenures closures assigned to a property; a method argument avoids that and survives minification - fiber.yieldWith(() => { - resumed = true - }) + if (fiber.supervisor === undefined) { + // V8 pretenures closures assigned to a property; a method argument avoids that and survives minification + fiber.yieldWith(() => { + resumed = true + }) + } else { + fiber.supervisor.onBlock(fiber, this.blockedOn) + // Read from the fiber rather than captured, so that no blocked fiber's + // closure context grows by a slot + fiber.yieldWith(() => { + resumed = true + fiber.supervisor!.onUnblock(fiber) + }) + } if (controller === undefined && onCancel === undefined) { return Yield } @@ -1231,13 +1257,14 @@ const callbackOptions: ( return Yield } }) - const AsyncImpl = function(this: any, register: any, withSignal: boolean) { + const AsyncImpl = function(this: any, register: any, withSignal: boolean, blockedOn: object | undefined) { this.register = register this.withSignal = withSignal - } as unknown as PrimitiveCtor<[register: any, withSignal: boolean]> + this.blockedOn = blockedOn + } as unknown as PrimitiveCtor<[register: any, withSignal: boolean, blockedOn: object | undefined]> AsyncImpl.prototype = Proto - return function(register: any, withSignal: boolean) { - return new AsyncImpl(register, withSignal) + return function(register: any, withSignal: boolean, blockedOn?: object) { + return new AsyncImpl(register, withSignal, blockedOn) } as any })() @@ -1264,11 +1291,20 @@ export const callback = ( this: Scheduler.Scheduler, resume: (effect: Effect.Effect) => void, signal: AbortSignal - ) => void | Effect.Effect -): Effect.Effect => callbackOptions(register as any, register.length >= 2) + ) => void | Effect.Effect, + options?: { + readonly blockedOn?: object | undefined + } | undefined +): Effect.Effect => callbackOptions(register as any, register.length >= 2, options?.blockedOn) /** @internal */ -export const never: Effect.Effect = callback(constVoid) +export const never: Effect.Effect = (() => { + // A fiber blocked on `never` reports `never` itself to its Supervisor; built + // in a function so that bundlers can still drop it when it is unused + const self = callback(constVoid) + ;(self as any).blockedOn = self + return self +})() /** @internal */ export const gen = < @@ -1722,7 +1758,7 @@ export const raceAll = >( }) if (done) break } - }) + }, { blockedOn: fibers }) }) /** @internal */ @@ -1762,7 +1798,7 @@ export const raceAllFirst = >( } }) } - }) + }, { blockedOn: fibers }) }) // Interrupt the losers as soon as the race settles. Waiting for the parent to @@ -4582,7 +4618,11 @@ const makeCachedUnsafe = ( } exit = undefined const clock = fiber.getRef(ClockRef) - const run: CachedRun = { fiber: new FiberImpl(fiber.context), awaiters: 0, done: false } + const run: CachedRun = { + fiber: new FiberImpl(fiber.context, true, fiber as FiberImpl), + awaiters: 0, + done: false + } current = run // Join before evaluating, which may synchronously re-enter and interrupt other awaiters. const joined = join(fiber, run) @@ -5182,9 +5222,9 @@ const iterateConcurrentImpl = (options: IterateOptions { parentFiber = getCurrentFiber()! - fibers = new Set() effect = eff resume = cb let result: Effect.Effect | undefined @@ -5201,7 +5241,7 @@ const iterateConcurrentImpl = (options: IterateOptions terminal?._tag === "Failure" ? terminal : void_ ) }) - }) + }, { blockedOn: fibers }) } else { // Clear the effect cached before the parent fiber was available. effect = undefined @@ -5606,7 +5646,7 @@ export const forkUnsafe = ( ): FiberImpl => { const parentRuntime = parent as FiberImpl const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible - const child = new FiberImpl(parentRuntime.context, interruptible) + const child = new FiberImpl(parentRuntime.context, interruptible, parentRuntime) if (!daemon) { parentRuntime.children().add(child) child._parent = parentRuntime @@ -5710,7 +5750,7 @@ export const forkIn: { withFiber((parent) => { // A closed scope gets an unstarted fiber, which is interrupted below const fiber = scope.state._tag === "Closed" - ? new FiberImpl(parent.context) + ? new FiberImpl(parent.context, true, parent as FiberImpl) : forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible) if (!(fiber as FiberImpl)._exit) { if (scope.state._tag !== "Closed") { @@ -5911,7 +5951,10 @@ export const runSync: (effect: Effect.Effect) => A = runSyncWith(Con const succeedTrue = succeed(true) const succeedFalse = succeed(false) +const LatchTypeId = "~effect/Latch" + class Latch implements _Latch.Latch { + readonly [LatchTypeId] = LatchTypeId waiters: Array<(_: Effect.Effect) => void> = [] scheduled: Array<(_: Effect.Effect) => void> | undefined = undefined private _isOpen: boolean @@ -5983,7 +6026,7 @@ class Latch implements _Latch.Latch { } } }) - }) + }, { blockedOn: this }) closeUnsafe() { if (!this._isOpen) return false this._isOpen = false @@ -5999,6 +6042,9 @@ class Latch implements _Latch.Latch { /** @internal */ export const makeLatchUnsafe = (open?: boolean | undefined): _Latch.Latch => new Latch(open ?? false) +/** @internal */ +export const isLatch = (u: unknown): u is _Latch.Latch => hasProperty(u, LatchTypeId) + /** @internal */ export const makeLatch = (open?: boolean | undefined) => sync(() => makeLatchUnsafe(open)) diff --git a/packages/effect/src/testing/TestClock.ts b/packages/effect/src/testing/TestClock.ts index 2c208c0211..d923d817af 100644 --- a/packages/effect/src/testing/TestClock.ts +++ b/packages/effect/src/testing/TestClock.ts @@ -25,6 +25,7 @@ import * as Layer from "../Layer.ts" import * as Scheduler from "../Scheduler.ts" import type * as Scope from "../Scope.ts" import * as Semaphore from "../Semaphore.ts" +import * as Supervisor from "../Supervisor.ts" /** * A `TestClock` simplifies deterministic and efficient testing of effects that @@ -116,6 +117,15 @@ export interface TestClock extends Clock.Clock { * `TestClock`. */ withLive(effect: Effect.Effect): Effect.Effect + /** + * Returns the current time and the pending sleeps, soonest first: each + * deadline with the `Latch` its sleeping fiber waits on, which is what that + * fiber's `Supervisor` sees it blocked on. Each call returns a fresh + * snapshot. + * + * @since 4.1.2 + */ + stateUnsafe(): TestClock.State } /** @@ -316,6 +326,12 @@ class TestClockImpl implements TestClock { // The `TestClock` methods are own arrow functions, so they still work when // detached from the clock or copied with a spread. + readonly stateUnsafe = (): TestClock.State => { + // `sleeps` is kept latest first + const pending = this.sleeps.map((entry): [number, Latch.Latch] => [entry.timestamp, entry.latch]).reverse() + return { timestamp: this.currentTimestamp, sleeps: pending } + } + readonly currentTimeMillisUnsafe = (): number => this.currentTimestamp readonly currentTimeNanosUnsafe = (): bigint => this.currentWallNanos readonly monotonicTimeNanosUnsafe = (): bigint => this.currentMonotonicNanos @@ -378,6 +394,8 @@ class TestClockImpl implements TestClock { Effect.delay(this.config.warningDelay), this.withLive, Effect.forkChild, + // A test's Supervisor must not see the warning timer as a pending wait + Effect.provideService(Supervisor.Supervisor, undefined), Effect.interruptible, Effect.flatMap((fiber) => Effect.sync(() => { diff --git a/packages/effect/test/Latch.test.ts b/packages/effect/test/Latch.test.ts index 5f4e3705f6..2da3868348 100644 --- a/packages/effect/test/Latch.test.ts +++ b/packages/effect/test/Latch.test.ts @@ -1,8 +1,13 @@ import { assert, describe, it } from "@effect/vitest" -import { Effect, Exit, Fiber, Latch } from "effect" +import { Effect, Exit, Fiber, Latch, Semaphore } from "effect" import * as Scheduler from "effect/Scheduler" describe("Latch", () => { + it("isLatch accepts a Latch and rejects a Semaphore", () => { + assert.isTrue(Latch.isLatch(Latch.makeUnsafe())) + assert.isFalse(Latch.isLatch(Semaphore.makeUnsafe(1))) + }) + it.effect("release wakes current waiters and keeps the latch closed", () => Effect.gen(function*() { const latch = yield* Latch.make(false) diff --git a/packages/effect/test/PartitionedSemaphore.test.ts b/packages/effect/test/PartitionedSemaphore.test.ts index f98c4146a5..ead06464d3 100644 --- a/packages/effect/test/PartitionedSemaphore.test.ts +++ b/packages/effect/test/PartitionedSemaphore.test.ts @@ -1,7 +1,13 @@ import { assert, describe, it } from "@effect/vitest" -import { Effect, Exit, Fiber, Option, PartitionedSemaphore, Scheduler } from "effect" +import { Effect, Exit, Fiber, Option, PartitionedSemaphore, Scheduler, Semaphore } from "effect" describe("PartitionedSemaphore", () => { + it("isPartitionedSemaphore accepts a PartitionedSemaphore and rejects a Semaphore", () => { + assert.isTrue(PartitionedSemaphore.isPartitionedSemaphore(PartitionedSemaphore.makeUnsafe({ permits: 1 }))) + assert.isTrue(PartitionedSemaphore.isPartitionedSemaphore(PartitionedSemaphore.makeUnsafe({ permits: Infinity }))) + assert.isFalse(PartitionedSemaphore.isPartitionedSemaphore(Semaphore.makeUnsafe(1))) + }) + it.effect("multi-permit waiters in different partitions do not deadlock", () => Effect.gen(function*() { const sem = yield* PartitionedSemaphore.make({ permits: 2 }) diff --git a/packages/effect/test/PubSub.test.ts b/packages/effect/test/PubSub.test.ts index d61577b9ef..6f6962b5bf 100644 --- a/packages/effect/test/PubSub.test.ts +++ b/packages/effect/test/PubSub.test.ts @@ -3,6 +3,13 @@ import { Array, Effect, Exit, Fiber, Latch, MutableList, PubSub, Scheduler, Scop import { pipe } from "effect/Function" describe("PubSub", () => { + it.effect("isSubscription accepts a Subscription and rejects its PubSub", () => + Effect.gen(function*() { + const pubsub = yield* PubSub.unbounded() + assert.isTrue(PubSub.isSubscription(yield* PubSub.subscribe(pubsub))) + assert.isFalse(PubSub.isSubscription(pubsub)) + })) + it.effect("isPubSub type guard", () => Effect.gen(function*() { const pubsub = yield* PubSub.bounded(10) diff --git a/packages/effect/test/Semaphore.test.ts b/packages/effect/test/Semaphore.test.ts index 60862c3f13..c94b627e7e 100644 --- a/packages/effect/test/Semaphore.test.ts +++ b/packages/effect/test/Semaphore.test.ts @@ -4,6 +4,11 @@ import * as Scheduler from "effect/Scheduler" import { TestClock } from "effect/testing" describe("Semaphore", () => { + it("isSemaphore accepts a Semaphore and rejects a PartitionedSemaphore", () => { + assert.isTrue(Semaphore.isSemaphore(Semaphore.makeUnsafe(1))) + assert.isFalse(Semaphore.isSemaphore(PartitionedSemaphore.makeUnsafe({ permits: 1 }))) + }) + it.effect("take admits requests in FIFO order when a holder immediately reacquires", () => Effect.gen(function*() { const sem = yield* Semaphore.make(1) diff --git a/packages/effect/test/Supervisor.test.ts b/packages/effect/test/Supervisor.test.ts new file mode 100644 index 0000000000..3258915bb3 --- /dev/null +++ b/packages/effect/test/Supervisor.test.ts @@ -0,0 +1,209 @@ +import { assert, describe, it } from "@effect/vitest" +import { Context, Deferred, Effect, Fiber, Supervisor, TxRef } from "effect" + +type Event = + | { readonly _tag: "start"; readonly fiber: Fiber.Fiber; readonly parent: unknown } + | { readonly _tag: "end"; readonly fiber: Fiber.Fiber } + | { + readonly _tag: "block" + readonly fiber: Fiber.Fiber + readonly blockedOn: unknown + // what a collection held when the block was reported + readonly members: ReadonlyArray | undefined + } + | { readonly _tag: "unblock"; readonly fiber: Fiber.Fiber } + | { readonly _tag: "mark"; readonly label: string } + +const recorder = () => { + const events: Array = [] + const supervisor: Supervisor.Supervisor = { + onStart: (fiber, parent) => events.push({ _tag: "start", fiber, parent }), + onEnd: (fiber) => events.push({ _tag: "end", fiber }), + onBlock: (fiber, blockedOn) => + events.push({ + _tag: "block", + fiber, + blockedOn, + members: Array.isArray(blockedOn) || blockedOn instanceof Set ? Array.from(blockedOn) : undefined + }), + onUnblock: (fiber) => events.push({ _tag: "unblock", fiber }) + } + const mark = (label: string) => Effect.sync(() => events.push({ _tag: "mark", label })) + const tagsOf = (fiber: Fiber.Fiber) => + events.flatMap((event) => event._tag !== "mark" && event.fiber === fiber ? [event._tag] : []) + return { events, supervisor, mark, tagsOf } +} + +const logging = (log: Array, name: string): Supervisor.Supervisor => ({ + onStart: () => log.push(`${name} start`), + onEnd: () => log.push(`${name} end`), + onBlock: () => log.push(`${name} block`), + onUnblock: () => log.push(`${name} unblock`) +}) + +// Runs `wait` in a fiber under a recording Supervisor and returns the block it reported +const blockOf = Effect.fnUntraced(function*(wait: Effect.Effect) { + const { events, supervisor } = recorder() + const fiber = yield* Effect.forkChild(wait, { startImmediately: true }).pipe( + Effect.provideService(Supervisor.Supervisor, supervisor) + ) + const block = events.find((event) => event._tag === "block" && event.fiber === fiber) + yield* Fiber.interrupt(fiber) + assert(block?._tag === "block", "the fiber did not block") + return block +}) + +describe("Supervisor", () => { + describe("events", () => { + it.effect("a fork reports the forker as parent before the forker continues, and a root fiber has none", () => + Effect.gen(function*() { + const { events, mark, supervisor } = recorder() + const forker = yield* Effect.fiber + const [child, root] = yield* Effect.gen(function*() { + const child = yield* Effect.forkChild(Effect.void) + yield* mark("forker continues") + const root = Effect.runForkWith(Context.make(Supervisor.Supervisor, supervisor))(Effect.void) + return [child, root] as const + }).pipe(Effect.provideService(Supervisor.Supervisor, supervisor)) + assert.deepStrictEqual(events.filter((event) => event._tag === "start" || event._tag === "mark"), [ + { _tag: "start", fiber: child, parent: forker }, + { _tag: "mark", label: "forker continues" }, + { _tag: "start", fiber: root, parent: undefined } + ]) + })) + + it.effect("a wait that completes at once, or a yield, does not block", () => + Effect.gen(function*() { + const { supervisor, tagsOf } = recorder() + const child = yield* Effect.forkChild( + Effect.andThen(Effect.callback((resume) => resume(Effect.void)), Effect.yieldNow) + ).pipe(Effect.provideService(Supervisor.Supervisor, supervisor)) + yield* Fiber.join(child) + assert.deepStrictEqual(tagsOf(child), ["start", "end"]) + })) + + it.effect("a blocked fiber unblocks when its wait completes or it is interrupted", () => + Effect.gen(function*() { + const { supervisor, tagsOf } = recorder() + const deferred = Deferred.makeUnsafe() + const [completed, interrupted] = yield* Effect.all([ + Effect.forkChild(Deferred.await(deferred), { startImmediately: true }), + Effect.forkChild(Effect.never, { startImmediately: true }) + ]).pipe(Effect.provideService(Supervisor.Supervisor, supervisor)) + assert.deepStrictEqual(tagsOf(completed), ["start", "block"]) + yield* Deferred.succeed(deferred, 1) + yield* Fiber.join(completed) + yield* Fiber.interrupt(interrupted) + assert.deepStrictEqual(tagsOf(completed), ["start", "block", "unblock", "end"]) + assert.deepStrictEqual(tagsOf(interrupted), ["start", "block", "unblock", "end"]) + })) + + it.effect("a fiber keeps its first Supervisor when its context changes, and its forks take the new one", () => + Effect.gen(function*() { + const first = recorder() + const second = recorder() + const outer = yield* Effect.forkChild(Effect.void).pipe( + Effect.provideService(Supervisor.Supervisor, second.supervisor), + Effect.forkChild, + Effect.provideService(Supervisor.Supervisor, first.supervisor) + ) + const inner = yield* Fiber.join(outer) + yield* Fiber.await(inner) + assert.deepStrictEqual(first.tagsOf(outer), ["start", "end"]) + assert.deepStrictEqual(second.tagsOf(outer), []) + assert.deepStrictEqual(second.tagsOf(inner), ["start", "end"]) + assert.deepStrictEqual(first.tagsOf(inner), []) + })) + }) + + describe("blocked on", () => { + it.effect("a Deferred wait reports the Deferred", () => + Effect.gen(function*() { + const deferred = Deferred.makeUnsafe() + assert.strictEqual((yield* blockOf(Deferred.await(deferred))).blockedOn, deferred) + })) + + it.effect("a race reports the Set of fibers it forked", () => + Effect.gen(function*() { + const block = yield* blockOf(Effect.race(Effect.never, Effect.never)) + assert.instanceOf(block.blockedOn, Set) + assert.strictEqual(block.members?.length, 2) + assert.isTrue(block.members?.every((member) => Fiber.isFiber(member))) + })) + + it.effect("a transaction that retries reports the TxRefs it read", () => + Effect.gen(function*() { + const first = yield* TxRef.make(0) + const second = yield* TxRef.make(0) + const block = yield* blockOf(Effect.tx(Effect.gen(function*() { + yield* TxRef.get(first) + yield* TxRef.get(second) + return yield* Effect.txRetry + }))) + assert.isTrue(Array.isArray(block.blockedOn)) + assert.deepStrictEqual(block.members, [first, second]) + })) + + it.effect("Effect.callback reports its blockedOn option, or undefined without one", () => + Effect.gen(function*() { + const blockedOn = {} + let signal: AbortSignal | undefined + const withOption = Effect.callback((_resume, signal_) => { + signal = signal_ + }, { blockedOn }) + assert.strictEqual((yield* blockOf(withOption)).blockedOn, blockedOn) + assert.isTrue(signal?.aborted) + assert.isUndefined((yield* blockOf(Effect.callback(() => {}))).blockedOn) + })) + }) + + describe("installation and composition", () => { + it.effect("combine calls each Supervisor once, outer first, even when the combinations overlap", () => + Effect.gen(function*() { + const log: Array = [] + const a = logging(log, "a") + const b = logging(log, "b") + const c = logging(log, "c") + const ab = Supervisor.combine(a, b) + const fiber = yield* Effect.fiber + const starts = (supervisor: Supervisor.Supervisor) => { + log.length = 0 + supervisor.onStart(fiber, undefined) + return [...log] + } + assert.deepStrictEqual(starts(Supervisor.combine(ab, Supervisor.combine(b, c))), [ + "a start", + "b start", + "c start" + ]) + assert.deepStrictEqual(starts(Supervisor.combine(a, ab)), ["a start", "b start"]) + })) + + it.effect("Supervisor.layer adds to the Supervisor in place, unless it is already there", () => + Effect.gen(function*() { + const log: Array = [] + const a = logging(log, "a") + yield* Effect.forkChild(Effect.void).pipe( + Effect.andThen(Effect.yieldNow), + Effect.provide(Supervisor.layer(a)), + Effect.provide(Supervisor.layer(logging(log, "b"))), + Effect.provideService(Supervisor.Supervisor, a) + ) + assert.deepStrictEqual(log, ["a start", "b start", "a end", "b end"]) + })) + + it.effect("Effect.withSupervisor observes its own child fiber and what it forks, and returns the result", () => + Effect.gen(function*() { + const { events, supervisor } = recorder() + const caller = yield* Effect.fiber + const [region, forked, result] = yield* Effect.gen(function*() { + const forked = yield* Effect.forkChild(Effect.void) + return [yield* Effect.fiber, forked, "result"] as const + }).pipe(Effect.withSupervisor(supervisor)) + assert.strictEqual(result, "result") + assert.notStrictEqual(region, caller) + const starts = events.flatMap((event) => event._tag === "start" ? [[event.fiber, event.parent]] : []) + assert.deepStrictEqual(starts, [[region, caller], [forked, region]]) + })) + }) +}) diff --git a/packages/effect/test/TestClock.test.ts b/packages/effect/test/TestClock.test.ts index b7cdcda5d9..c904381f19 100644 --- a/packages/effect/test/TestClock.test.ts +++ b/packages/effect/test/TestClock.test.ts @@ -6,11 +6,50 @@ import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" import * as Scheduler from "effect/Scheduler" +import * as Supervisor from "effect/Supervisor" import * as TestClock from "effect/testing/TestClock" import * as TestConsole from "effect/testing/TestConsole" import { vi } from "vitest" describe("TestClock", () => { + describe("observed by a Supervisor", () => { + const recorder = () => { + const blocks = new Map, object | undefined>() + const started: Array> = [] + const supervisor: Supervisor.Supervisor = { + onStart: (fiber) => started.push(fiber), + onEnd: () => {}, + onBlock: (fiber, blockedOn) => blocks.set(fiber, blockedOn), + onUnblock: () => {} + } + return { blocks, started, supervisor } + } + + it.effect("stateUnsafe lists the pending sleeps soonest first, with the Latch each sleeper blocks on", () => + Effect.gen(function*() { + const { blocks, supervisor } = recorder() + const [later, sooner] = yield* Effect.forEach( + ["2 minutes", "1 minute"] as const, + (duration) => Effect.forkChild(Effect.sleep(duration), { startImmediately: true }) + ).pipe(Effect.provideService(Supervisor.Supervisor, supervisor)) + const { sleeps } = yield* TestClock.testClockWith((clock) => Effect.sync(() => clock.stateUnsafe())) + assert.deepStrictEqual(sleeps.map(([deadline]) => deadline), [60_000, 120_000]) + assert.strictEqual(sleeps[0][1], blocks.get(sooner)) + assert.strictEqual(sleeps[1][1], blocks.get(later)) + })) + + it.effect("a test's Supervisor never sees the warning timer", () => + Effect.gen(function*() { + const { started, supervisor } = recorder() + const sleeper = yield* Effect.forkChild(Effect.sleep("1 minute"), { startImmediately: true }).pipe( + Effect.provideService(Supervisor.Supervisor, supervisor) + ) + yield* TestClock.adjust("1 minute") + yield* Fiber.join(sleeper) + assert.deepStrictEqual(started, [sleeper]) + })) + }) + describe("warnings", { concurrent: false }, () => { for (const warning of ["not advancing the test clock", "still running without suspending"] as const) { it.effect(`warnings bypass TestConsole - ${warning}`, () => diff --git a/packages/effect/test/TxRef.test.ts b/packages/effect/test/TxRef.test.ts new file mode 100644 index 0000000000..dab86ffb23 --- /dev/null +++ b/packages/effect/test/TxRef.test.ts @@ -0,0 +1,10 @@ +import { assert, describe, it } from "@effect/vitest" +import { Effect, Ref, TxRef } from "effect" + +describe("TxRef", () => { + it.effect("isTxRef accepts a TxRef and rejects a Ref", () => + Effect.gen(function*() { + assert.isTrue(TxRef.isTxRef(yield* TxRef.make(0))) + assert.isFalse(TxRef.isTxRef(yield* Ref.make(0))) + })) +}) diff --git a/packages/tools/bundle/fixtures/supervisor.ts b/packages/tools/bundle/fixtures/supervisor.ts new file mode 100644 index 0000000000..58072d6bad --- /dev/null +++ b/packages/tools/bundle/fixtures/supervisor.ts @@ -0,0 +1,17 @@ +import * as Effect from "effect/Effect" +import * as Fiber from "effect/Fiber" +import type * as Supervisor from "effect/Supervisor" + +const supervisor: Supervisor.Supervisor = { + onStart: () => {}, + onEnd: () => {}, + onBlock: () => {}, + onUnblock: () => {} +} + +const program = Effect.gen(function*() { + const fiber = yield* Effect.forkChild(Effect.sleep("10 millis")) + yield* Fiber.join(fiber) +}) + +Effect.runFork(Effect.withSupervisor(program, supervisor)) From 55422dc1909b8de3fe320742aeabda6ea120dcf5 Mon Sep 17 00:00:00 2001 From: Tim Date: Wed, 4 Nov 2026 16:17:52 +1300 Subject: [PATCH 14/15] Make McpSchema.InputRequired a schema class (#10368) --- .changeset/mcp-input-required-schema.md | 10 +++++ packages/effect/MCP.md | 9 ++-- packages/effect/src/ai/McpSchema.ts | 43 ++++++++++++++----- .../ai/McpServer/ProtocolAdapters.test.ts | 4 +- packages/effect/typetest/ai/McpServer.tst.ts | 2 +- 5 files changed, 51 insertions(+), 17 deletions(-) create mode 100644 .changeset/mcp-input-required-schema.md diff --git a/.changeset/mcp-input-required-schema.md b/.changeset/mcp-input-required-schema.md new file mode 100644 index 0000000000..0c202eadef --- /dev/null +++ b/.changeset/mcp-input-required-schema.md @@ -0,0 +1,10 @@ +--- +"effect": minor +--- + +`McpSchema.InputRequired` is now a schema class and `McpSchema.McpInputRequest` is now a schema, so a toolkit tool can declare `failure: McpSchema.InputRequired`. + +### Migration + +- The `McpSchema.InputRequired` constructor now validates its fields and throws when they are invalid, for example for an unknown input request `method`. +- A `Schema.instanceOf(McpSchema.InputRequired)` failure schema has no JSON codec, so in `failureMode: "return"` it fails with `ToolResultEncodingError`. Declare `failure: McpSchema.InputRequired` instead. diff --git a/packages/effect/MCP.md b/packages/effect/MCP.md index f863ade80c..7d02fd263c 100644 --- a/packages/effect/MCP.md +++ b/packages/effect/MCP.md @@ -480,7 +480,7 @@ import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai" const ArchiveNote = Tool.make("ArchiveNote", { parameters: Schema.Struct({ noteId: Schema.String }), success: Schema.Struct({ archived: Schema.String }), - failure: Schema.instanceOf(McpSchema.InputRequired), + failure: McpSchema.InputRequired, dependencies: [McpSchema.McpRequestContext] }) @@ -531,9 +531,10 @@ const NotesLayer = McpServer.toolkit(NotesToolkit).pipe( The first call fails with `InputRequired`, which the client receives as an `input_required` result. On the retry, the handler reads the answer and the state from `McpRequestContext`. -- `InputRequired` is not an error class, so fail with `Effect.fail(new McpSchema.InputRequired(...))`. - It can also be one member of a union failure schema. For a tool you do not own, widen its failure - with `tool.setFailure(Schema.Union([...]))` before building the toolkit. +- `InputRequired` is a schema class, not an error class. Declare it directly as the failure schema and + fail with `Effect.fail(new McpSchema.InputRequired(...))`. It can also be one member of a union + failure schema. For a tool you do not own, widen its failure with + `tool.setFailure(Schema.Union([...]))` before building the toolkit. - Protocols before `v2026_07_28` reject the result with an `InvalidParams` error ("Client input is not supported by this MCP protocol"), as they do for `addTool`. - The client must declare the capability each input request needs, such as `elicitation`. diff --git a/packages/effect/src/ai/McpSchema.ts b/packages/effect/src/ai/McpSchema.ts index ba6c8308c3..e5ffd2a161 100644 --- a/packages/effect/src/ai/McpSchema.ts +++ b/packages/effect/src/ai/McpSchema.ts @@ -3028,6 +3028,19 @@ export const ElicitResult = Schema.Union([ */ export type ElicitResult = typeof ElicitResult.Type +/** + * Version-neutral request for additional MCP client input. + * + * @stability unstable + * @category schemas + * @since 4.0.0 + */ +export const McpInputRequest = Schema.Union([ + Schema.Struct({ method: Schema.Literal("roots/list"), params: optional(UnknownObject) }), + Schema.Struct({ method: Schema.Literal("sampling/createMessage"), params: UnknownObject }), + Schema.Struct({ method: Schema.Literal("elicitation/create"), params: UnknownObject }) +]).annotate({ identifier: "McpInputRequest" }) + /** * Version-neutral request for additional MCP client input. * @@ -3035,10 +3048,7 @@ export type ElicitResult = typeof ElicitResult.Type * @category models * @since 4.0.0 */ -export type McpInputRequest = - | { readonly method: "roots/list"; readonly params?: Readonly> | undefined } - | { readonly method: "sampling/createMessage"; readonly params: Readonly> } - | { readonly method: "elicitation/create"; readonly params: Readonly> } +export type McpInputRequest = typeof McpInputRequest.Type /** * Version-neutral response supplied by an MCP client for a prior input request. @@ -3062,14 +3072,26 @@ export type McpInputResponse = Readonly> * `requestState` is opaque to the client and is returned unchanged with the * keyed input responses. * + * `InputRequired` is also a schema, so a toolkit tool can declare it as its + * `failure`. The constructor validates its fields and throws when they are + * invalid. + * * @stability unstable * @category models * @since 4.0.0 */ -export class InputRequired extends Data.TaggedClass("InputRequired")<{ - readonly inputRequests?: Readonly> | undefined - readonly requestState?: string | undefined -}> { +export class InputRequired extends Schema.TaggedClass("@effect/ai/McpSchema/InputRequired")( + "InputRequired", + Schema.Struct({ + inputRequests: optional(Schema.Record(Schema.String, McpInputRequest)), + requestState: optional(Schema.String) + }).check( + Schema.makeFilter( + (fields) => fields.inputRequests !== undefined || fields.requestState !== undefined, + { message: "InputRequired requires at least one of inputRequests or requestState" } + ) + ) +) { // The overload preserves the requirement that at least one of inputRequests or requestState is present. // oxlint-disable-next-line no-useless-constructor constructor( @@ -3081,9 +3103,10 @@ export class InputRequired extends Data.TaggedClass("InputRequired")<{ | { readonly inputRequests?: Readonly> | undefined readonly requestState: string - } + }, + options?: Schema.MakeOptions ) { - super(fields) + super(fields, options) } } diff --git a/packages/effect/test/ai/McpServer/ProtocolAdapters.test.ts b/packages/effect/test/ai/McpServer/ProtocolAdapters.test.ts index f8265f135b..f912329e3b 100644 --- a/packages/effect/test/ai/McpServer/ProtocolAdapters.test.ts +++ b/packages/effect/test/ai/McpServer/ProtocolAdapters.test.ts @@ -99,14 +99,14 @@ class RootsUnavailable extends Schema.TaggedError()("RootsUnav const InputRequiredTool = Tool.make("input-required", { parameters: Tool.EmptyParams, success: Schema.String, - failure: Schema.instanceOf(McpSchema.InputRequired), + failure: McpSchema.InputRequired, dependencies: [McpSchema.McpRequestContext] }) const InputRequiredReturnTool = Tool.make("input-required-return", { parameters: Tool.EmptyParams, success: Schema.String, - failure: Schema.Union([Schema.instanceOf(McpSchema.InputRequired), RootsUnavailable]), + failure: Schema.Union([McpSchema.InputRequired, RootsUnavailable]), failureMode: "return", dependencies: [McpSchema.McpRequestContext] }) diff --git a/packages/effect/typetest/ai/McpServer.tst.ts b/packages/effect/typetest/ai/McpServer.tst.ts index 6379f97fbb..aeac4e1c6e 100644 --- a/packages/effect/typetest/ai/McpServer.tst.ts +++ b/packages/effect/typetest/ai/McpServer.tst.ts @@ -210,7 +210,7 @@ describe("McpServer", () => { }) it("should accept InputRequired as a declared toolkit failure", () => { - const toolkit = Toolkit.make(Tool.make("Confirm", { failure: Schema.instanceOf(McpSchema.InputRequired) })) + const toolkit = Toolkit.make(Tool.make("Confirm", { failure: McpSchema.InputRequired })) const layer = McpServer.toolkit(toolkit).pipe( Layer.provide(toolkit.toLayer({ Confirm: () => Effect.fail(new McpSchema.InputRequired({ requestState: "state" })) From 9a26b283d6fec8611a69a3b8b14270aad12a3b50 Mon Sep 17 00:00:00 2001 From: clean99 <53188310+clean99@users.noreply.github.com> Date: Thu, 5 Nov 2026 07:38:25 +0800 Subject: [PATCH 15/15] Accept null service_tier and tool_calls in openai-compat responses (#10371) Co-authored-by: Effect Bot --- ...nai-compat-null-service-tier-tool-calls.md | 7 ++ packages/ai/openai-compat/src/OpenAiClient.ts | 6 +- .../openai-compat/src/OpenAiLanguageModel.ts | 6 +- .../test/OpenAiLanguageModel.test.ts | 85 +++++++++++++++++++ 4 files changed, 98 insertions(+), 6 deletions(-) create mode 100644 .changeset/openai-compat-null-service-tier-tool-calls.md diff --git a/.changeset/openai-compat-null-service-tier-tool-calls.md b/.changeset/openai-compat-null-service-tier-tool-calls.md new file mode 100644 index 0000000000..5fe7d8540c --- /dev/null +++ b/.changeset/openai-compat-null-service-tier-tool-calls.md @@ -0,0 +1,7 @@ +--- +"@effect/ai-openai-compat": minor +--- + +Accept `null` for `service_tier` and `message.tool_calls` in chat completion responses and stream chunks, treating them like absent fields. Servers that serialize unset fields as `null` (for example vLLM) previously failed `generateText` with a decode error and had their null-tier stream chunks dropped. + +Raw `OpenAiClient` response and chunk types now include `null` for these fields; check for nullish values rather than only `undefined`. diff --git a/packages/ai/openai-compat/src/OpenAiClient.ts b/packages/ai/openai-compat/src/OpenAiClient.ts index 1c535b6daf..d59f38f2a0 100644 --- a/packages/ai/openai-compat/src/OpenAiClient.ts +++ b/packages/ai/openai-compat/src/OpenAiClient.ts @@ -1165,7 +1165,7 @@ const ChatCompletionMessage = Schema.Struct({ content: Schema.optionalKey(Schema.NullOr(Schema.String)), reasoning: Schema.optionalKey(Schema.NullOr(Schema.String)), reasoning_content: Schema.optionalKey(Schema.NullOr(Schema.String)), - tool_calls: Schema.optionalKey(Schema.Array(ChatCompletionToolCall)) + tool_calls: Schema.optionalKey(Schema.NullOr(Schema.Array(ChatCompletionToolCall))) }) const ChatCompletionDelta = Schema.Struct({ @@ -1201,7 +1201,7 @@ const ChatCompletionResponse = Schema.Struct({ created: Schema.Int, choices: Schema.Array(ChatCompletionChoice), usage: Schema.optionalKey(Schema.NullOr(ChatCompletionUsage)), - service_tier: Schema.optionalKey(Schema.String) + service_tier: Schema.optionalKey(Schema.NullOr(Schema.String)) }) const ChatCompletionChunk = Schema.Struct({ @@ -1210,7 +1210,7 @@ const ChatCompletionChunk = Schema.Struct({ created: Schema.Int, choices: Schema.Array(ChatCompletionChoice), usage: Schema.optionalKey(Schema.NullOr(ChatCompletionUsage)), - service_tier: Schema.optionalKey(Schema.String) + service_tier: Schema.optionalKey(Schema.NullOr(Schema.String)) }) /** diff --git a/packages/ai/openai-compat/src/OpenAiLanguageModel.ts b/packages/ai/openai-compat/src/OpenAiLanguageModel.ts index ce3de492cf..e44aa06480 100644 --- a/packages/ai/openai-compat/src/OpenAiLanguageModel.ts +++ b/packages/ai/openai-compat/src/OpenAiLanguageModel.ts @@ -1008,7 +1008,7 @@ const makeResponse = Effect.fnUntraced( parts.push({ type: "text", text: message.content }) } - if (message.tool_calls !== undefined) { + if (Predicate.isNotNullish(message.tool_calls)) { for (const [index, toolCall] of message.tool_calls.entries()) { const toolId = toolCall.id ?? `${rawResponse.id}_tool_${index}` const toolName = toolNameMapper.getCustomName(toolCall.function?.name ?? "unknown_tool") @@ -1047,7 +1047,7 @@ const makeResponse = Effect.fnUntraced( choice?.finish_reason, hasToolCalls ) - const serviceTier = normalizeServiceTier(rawResponse.service_tier) + const serviceTier = normalizeServiceTier(rawResponse.service_tier ?? undefined) parts.push({ type: "finish", @@ -1160,7 +1160,7 @@ const makeStreamResponse = Effect.fnUntraced( return parts } - if (event.service_tier !== undefined) { + if (Predicate.isNotNullish(event.service_tier)) { serviceTier = event.service_tier } if (event.usage !== undefined && Predicate.isNotNull(event.usage)) { diff --git a/packages/ai/openai-compat/test/OpenAiLanguageModel.test.ts b/packages/ai/openai-compat/test/OpenAiLanguageModel.test.ts index 4e5868ca3a..12154e473b 100644 --- a/packages/ai/openai-compat/test/OpenAiLanguageModel.test.ts +++ b/packages/ai/openai-compat/test/OpenAiLanguageModel.test.ts @@ -1087,6 +1087,46 @@ describe("OpenAiLanguageModel", () => { }) })) + it.effect("decodes null service_tier and tool_calls in non-streaming responses", () => + Effect.gen(function*() { + const layer = OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe( + Layer.provide(Layer.succeed( + HttpClient.HttpClient, + makeHttpClient((request) => + Effect.succeed(jsonResponse( + request, + makeChatCompletion({ + choices: [{ + index: 0, + finish_reason: "stop", + message: { + role: "assistant", + content: "Hello", + tool_calls: null + } + }], + service_tier: null + }) + )) + ) + )) + ) + + const result = yield* LanguageModel.generateText({ prompt: "hello" }).pipe( + Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")), + Effect.provide(layer) + ) + + assert.strictEqual(result.text, "Hello") + assert.strictEqual(result.finishReason, "stop") + + const finish = result.content.find((part) => part.type === "finish") + assert.isDefined(finish) + if (finish?.type === "finish") { + assert.isUndefined(finish.metadata["openai-compat"]?.serviceTier) + } + })) + it.effect("surfaces reasoning from non-streaming responses", () => Effect.gen(function*() { const layer = OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe( @@ -1641,6 +1681,51 @@ describe("OpenAiLanguageModel", () => { assert.strictEqual(text, "Hello") })) + it.effect("keeps streamed text and service tier when a chunk has null service_tier", () => + Effect.gen(function*() { + const chunk = (serviceTier: string | null, delta: Record, finishReason: string | null) => ({ + id: "chatcmpl_nullable_service_tier", + object: "chat.completion.chunk", + model: "gpt-4o-mini", + created: 1, + service_tier: serviceTier, + choices: [{ index: 0, delta, finish_reason: finishReason }] + }) + + const layer = OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe( + Layer.provide(Layer.succeed( + HttpClient.HttpClient, + makeHttpClient((request) => + Effect.succeed(sseResponse(request, [ + chunk("default", { content: "Hel", role: "assistant" }, null), + chunk(null, { content: "lo" }, "stop"), + "[DONE]" + ])) + ) + )) + ) + + const partsChunk = yield* LanguageModel.streamText({ prompt: "test" }).pipe( + Stream.runCollect, + Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")), + Effect.provide(layer) + ) + + const parts = Array.from(partsChunk) + const text = parts + .filter((part) => part.type === "text-delta") + .map((part) => part.delta) + .join("") + const finish = parts.find((part) => part.type === "finish") + + assert.strictEqual(text, "Hello") + assert.isDefined(finish) + if (finish?.type === "finish") { + assert.strictEqual(finish.reason, "stop") + assert.strictEqual(finish.metadata["openai-compat"]?.serviceTier, "default") + } + })) + it.effect("preserves streamed text and tool args with nullable delta fields", () => Effect.gen(function*() { const extraContent = { google: { thought_signature: "signature-1" } }