diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index 31c4a2fc38..fb9e3637ce 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -45,6 +45,24 @@ export const isCause: (self: unknown) => self is Cause = core.isCause */ export type Failure = Fail | Die | Interrupt +/** + * @since 4.0.0 + * @category guards + */ +export const failureIsFail: (self: Failure) => self is Fail = core.failureIsFail + +/** + * @since 4.0.0 + * @category guards + */ +export const failureIsDie: (self: Failure) => self is Die = core.failureIsDie + +/** + * @since 4.0.0 + * @category guards + */ +export const failureIsInterrupt: (self: Failure) => self is Interrupt = core.failureIsInterrupt + /** * @since 2.0.0 * @category models diff --git a/packages/effect/src/Channel.ts b/packages/effect/src/Channel.ts index 15bb5f8fc3..2ded2df7b3 100644 --- a/packages/effect/src/Channel.ts +++ b/packages/effect/src/Channel.ts @@ -2,7 +2,7 @@ * @since 2.0.0 */ import type * as Arr from "./Array.js" -import type * as Cause from "./Cause.js" +import * as Cause from "./Cause.js" import * as Chunk from "./Chunk.js" import * as Context from "./Context.js" import * as Effect from "./Effect.js" @@ -14,6 +14,7 @@ import * as Iterable from "./Iterable.js" import * as Option from "./Option.js" import type { Pipeable } from "./Pipeable.js" import { pipeArguments } from "./Pipeable.js" +import type { Refinement } from "./Predicate.js" import { hasProperty } from "./Predicate.js" import * as PubSub from "./PubSub.js" import * as Pull from "./Pull.js" @@ -481,6 +482,14 @@ export const failCauseSync = ( evaluate: LazyArg> ): Channel => fromPull(Effect.failCauseSync(evaluate)) +/** + * Constructs a channel that fails immediately with the specified defect. + * + * @since 2.0.0 + * @category constructors + */ +export const die = (defect: unknown): Channel => failCause(Cause.die(defect)) + /** * Use an effect to write a single value to the channel. * @@ -1179,6 +1188,287 @@ export const flattenArray = < }) ) +/** + * @since 4.0.0 + * @category Error handling + */ +export const catchCause: { + ( + f: (d: Cause.Cause) => Channel + ): < + OutElem, + OutDone, + InElem, + InErr, + InDone, + Env + >(self: Channel) => Channel< + OutElem | OutElem1, + OutErr1, + OutDone | OutDone1, + InElem & InElem1, + InErr & InErr1, + InDone & InDone1, + Env | Env1 + > + < + OutElem, + OutErr, + OutDone, + InElem, + InErr, + InDone, + Env, + OutElem1, + OutErr1, + OutDone1, + InElem1, + InErr1, + InDone1, + Env1 + >( + self: Channel, + f: (d: Cause.Cause) => Channel + ): Channel< + OutElem | OutElem1, + OutErr1, + OutDone | OutDone1, + InElem & InElem1, + InErr & InErr1, + InDone & InDone1, + Env | Env1 + > +} = dual(2, < + OutElem, + OutErr, + OutDone, + InElem, + InErr, + InDone, + Env, + OutElem1, + OutErr1, + OutDone1, + InElem1, + InErr1, + InDone1, + Env1 +>( + self: Channel, + f: (d: Cause.Cause) => Channel +): Channel< + OutElem | OutElem1, + OutErr1, + OutDone | OutDone1, + InElem & InElem1, + InErr & InErr1, + InDone & InDone1, + Env | Env1 +> => + fromTransform((upstream, scope) => + Effect.map(toTransform(self)(upstream, scope), (pull) => { + let currentPull: Pull.Pull = pull.pipe( + Effect.catchCause((cause): Pull.Pull => { + if (Pull.isHaltCause(cause)) { + return Effect.failCause(cause as Cause.Cause>) + } + return toTransform(f(cause as Cause.Cause))(upstream, scope).pipe( + Effect.flatMap((childPull) => { + currentPull = childPull + return childPull + }) + ) + }) + ) + return Effect.suspend(() => currentPull) + }) + )) + +/** + * @since 4.0.0 + * @category Error handling + */ +export const catchFailure: { + , OutElem1, OutErr1, OutDone1, InElem1, InErr1, InDone1, Env1>( + refinement: Refinement, EB>, + f: (failure: EB, cause: Cause.Cause) => Channel + ): < + OutElem, + OutDone, + InElem, + InErr, + InDone, + Env + >(self: Channel) => Channel< + OutElem | OutElem1, + Exclude> | OutErr1, + OutDone | OutDone1, + InElem & InElem1, + InErr & InErr1, + InDone & InDone1, + Env | Env1 + > + < + OutElem, + OutErr, + OutDone, + InElem, + InErr, + InDone, + Env, + EB extends Cause.Failure, + OutElem1, + OutErr1, + OutDone1, + InElem1, + InErr1, + InDone1, + Env1 + >( + self: Channel, + refinement: Refinement, EB>, + f: (failure: EB, cause: Cause.Cause) => Channel + ): Channel< + OutElem | OutElem1, + Exclude> | OutErr1, + OutDone | OutDone1, + InElem & InElem1, + InErr & InErr1, + InDone & InDone1, + Env | Env1 + > +} = dual(3, < + OutElem, + OutErr, + OutDone, + InElem, + InErr, + InDone, + Env, + EB extends Cause.Failure, + OutElem1, + OutErr1, + OutDone1, + InElem1, + InErr1, + InDone1, + Env1 +>( + self: Channel, + refinement: Refinement, EB>, + f: (failure: EB, cause: Cause.Cause) => Channel +): Channel< + OutElem | OutElem1, + OutErr | OutErr1, + OutDone | OutDone1, + InElem & InElem1, + InErr & InErr1, + InDone & InDone1, + Env | Env1 +> => + catchCause(self, (cause): Channel => { + const failure = cause.failures.find(refinement) + return failure ? f(failure, cause) : failCause(cause) + })) + +const catch_: { + ( + f: (d: OutErr) => Channel + ): < + OutElem, + OutDone, + InElem, + InErr, + InDone, + Env + >(self: Channel) => Channel< + OutElem | OutElem1, + OutErr1, + OutDone | OutDone1, + InElem & InElem1, + InErr & InErr1, + InDone & InDone1, + Env | Env1 + > + < + OutElem, + OutErr, + OutDone, + InElem, + InErr, + InDone, + Env, + OutElem1, + OutErr1, + OutDone1, + InElem1, + InErr1, + InDone1, + Env1 + >( + self: Channel, + f: (d: OutErr) => Channel + ): Channel< + OutElem | OutElem1, + OutErr1, + OutDone | OutDone1, + InElem & InElem1, + InErr & InErr1, + InDone & InDone1, + Env | Env1 + > +} = dual(2, < + OutElem, + OutErr, + OutDone, + InElem, + InErr, + InDone, + Env, + OutElem1, + OutErr1, + OutDone1, + InElem1, + InErr1, + InDone1, + Env1 +>( + self: Channel, + f: (d: OutErr) => Channel +): Channel< + OutElem | OutElem1, + OutErr1, + OutDone | OutDone1, + InElem & InElem1, + InErr & InErr1, + InDone & InDone1, + Env | Env1 +> => catchFailure(self, Cause.failureIsFail, (failure) => f(failure.error))) + +export { + /** + * @since 4.0.0 + * @category Error handling + */ + catch_ as catch +} + +/** + * @since 4.0.0 + * @category Error handling + */ +export const orDie = < + OutElem, + OutErr, + OutDone, + InElem, + InErr, + InDone, + Env +>( + self: Channel +): Channel => catch_(self, die) + /** * Returns a new channel, which sequentially combines this channel, together * with the provided factory function, which creates a second channel based on diff --git a/packages/effect/src/FileSystem.ts b/packages/effect/src/FileSystem.ts index a3b7088f11..9e8a06d3e9 100644 --- a/packages/effect/src/FileSystem.ts +++ b/packages/effect/src/FileSystem.ts @@ -462,11 +462,12 @@ export const make = ( Effect.flatMap(impl.readFile(path), (_) => Effect.try({ try: () => new TextDecoder(encoding).decode(_), - catch: () => - BadArgument({ + catch: (cause) => + new BadArgument({ module: "FileSystem", method: "readFileString", - message: "invalid encoding" + description: "invalid encoding", + cause }) })), stream: Effect.fnUntraced(function*(path, options) { @@ -508,11 +509,12 @@ export const make = ( Effect.flatMap( Effect.try({ try: () => new TextEncoder().encode(data), - catch: () => - BadArgument({ + catch: (cause) => + new BadArgument({ module: "FileSystem", method: "writeFileString", - message: "could not encode string" + description: "could not encode string", + cause }) }), (_) => impl.writeFile(path, _, options) @@ -520,11 +522,11 @@ export const make = ( }) const notFound = (method: string, path: string) => - SystemError({ + new SystemError({ module: "FileSystem", method, reason: "NotFound", - message: "No such file or directory", + description: "No such file or directory", pathOrDescriptor: path }) diff --git a/packages/effect/src/PlatformError.ts b/packages/effect/src/PlatformError.ts index 8fe910823a..92fa89716f 100644 --- a/packages/effect/src/PlatformError.ts +++ b/packages/effect/src/PlatformError.ts @@ -1,131 +1,122 @@ /** * @since 4.0.0 */ -import type * as Cause from "effect/Cause" -import * as Data from "effect/Data" -import * as Predicate from "effect/Predicate" -import type { Simplify } from "effect/Types" +import * as Schema from "effect/Schema" /** - * @since 4.0.0 + * @since 1.0.0 * @category type id */ -export const PlatformErrorTypeId: unique symbol = Symbol.for("effect/PlatformError") +export const TypeId: unique symbol = Symbol.for("effect/PlatformError") /** - * @since 4.0.0 + * @since 1.0.0 * @category type id */ -export type PlatformErrorTypeId = typeof PlatformErrorTypeId +export type TypeId = typeof TypeId /** - * @since 4.0.0 - * @category refinements + * @since 1.0.0 + * @category Models */ -export const isPlatformError = (u: unknown): u is PlatformError => Predicate.hasProperty(u, PlatformErrorTypeId) +export const Module = Schema.Literals([ + "Clipboard", + "Command", + "FileSystem", + "KeyValueStore", + "Path", + "Stream", + "Terminal" +]) /** - * @since 4.0.0 - * @category error + * @since 1.0.0 + * @category Models + */ +export class BadArgument extends Schema.ErrorClass("@effect/platform/Error/BadArgument")({ + _tag: Schema.tag("BadArgument"), + module: Module, + method: Schema.String, + description: Schema.optional(Schema.String), + cause: Schema.optional(Schema.Unknown) +}) { + /** + * @since 1.0.0 + */ + readonly [TypeId]: typeof TypeId = TypeId + + /** + * @since 1.0.0 + */ + get message(): string { + return `${this.module}.${this.method}${this.description ? `: ${this.description}` : ""}` + } +} + +/** + * @since 1.0.0 + * @category Model + */ +export const SystemErrorReason = Schema.Literals([ + "AlreadyExists", + "BadResource", + "Busy", + "InvalidData", + "NotFound", + "PermissionDenied", + "TimedOut", + "UnexpectedEof", + "Unknown", + "WouldBlock", + "WriteZero" +]) + +/** + * @since 1.0.0 + * @category Model + */ +export type SystemErrorReason = typeof SystemErrorReason.Type + +/** + * @since 1.0.0 + * @category models + */ +export class SystemError extends Schema.ErrorClass("@effect/platform/Error/SystemError")({ + _tag: Schema.tag("SystemError"), + reason: SystemErrorReason, + module: Module, + method: Schema.String, + description: Schema.optional(Schema.String), + syscall: Schema.optional(Schema.String), + pathOrDescriptor: Schema.optional(Schema.Union([Schema.String, Schema.Number])), + cause: Schema.optional(Schema.Unknown) +}) { + /** + * @since 1.0.0 + */ + readonly [TypeId]: typeof TypeId = TypeId + + /** + * @since 1.0.0 + */ + get message(): string { + return `${this.reason}: ${this.module}.${this.method}${ + this.pathOrDescriptor !== undefined ? ` (${this.pathOrDescriptor})` : "" + }${this.description ? `: ${this.description}` : ""}` + } +} + +/** + * @since 1.0.0 + * @category Models */ export type PlatformError = BadArgument | SystemError /** - * @since 4.0.0 - * @category error + * @since 1.0.0 + * @category Models */ -export const TypeIdError = ( - typeId: TypeId, - tag: Tag -): new>( - args: Simplify -) => - & Cause.YieldableError - & Record - & { readonly _tag: Tag } - & Readonly => -{ - class Base extends Data.Error<{}> { - readonly _tag = tag - } - ;(Base.prototype as any)[typeId] = typeId - ;(Base.prototype as any).name = tag - return Base as any -} - -/** - * @since 4.0.0 - */ -export declare namespace PlatformError { - /** - * @since 4.0.0 - * @category models - */ - export interface Base { - readonly [PlatformErrorTypeId]: typeof PlatformErrorTypeId - readonly _tag: string - readonly module: "Clipboard" | "Command" | "FileSystem" | "KeyValueStore" | "Path" | "Stream" | "Terminal" - readonly method: string - readonly message: string - } - - /** - * @since 4.0.0 - */ - export type ProvidedFields = PlatformErrorTypeId | "_tag" -} - -const make = (tag: A["_tag"]) => (props: Omit): A => - Data.struct({ - [PlatformErrorTypeId]: PlatformErrorTypeId, - _tag: tag, - ...props - } as A) - -/** - * @since 4.0.0 - * @category error - */ -export interface BadArgument extends PlatformError.Base { - readonly _tag: "BadArgument" -} - -/** - * @since 4.0.0 - * @category error - */ -export const BadArgument: (props: Omit) => BadArgument = make("BadArgument") - -/** - * @since 4.0.0 - * @category model - */ -export type SystemErrorReason = - | "AlreadyExists" - | "BadResource" - | "Busy" - | "InvalidData" - | "NotFound" - | "PermissionDenied" - | "TimedOut" - | "UnexpectedEof" - | "Unknown" - | "WouldBlock" - | "WriteZero" - -/** - * @since 4.0.0 - * @category models - */ -export interface SystemError extends PlatformError.Base { - readonly _tag: "SystemError" - readonly reason: SystemErrorReason - readonly syscall?: string | undefined - readonly pathOrDescriptor: string | number -} - -/** - * @since 4.0.0 - * @category error - */ -export const SystemError: (props: Omit) => SystemError = make("SystemError") +export const PlatformError: Schema.Union<[ + typeof BadArgument, + typeof SystemError +]> = Schema.Union([BadArgument, SystemError]) diff --git a/packages/effect/src/Sink.ts b/packages/effect/src/Sink.ts index d4094e7af6..0991847278 100644 --- a/packages/effect/src/Sink.ts +++ b/packages/effect/src/Sink.ts @@ -173,6 +173,14 @@ export const failCauseSync = (evaluate: LazyArg>): Sink => fromChannel(Channel.die(defect)) + /** * A sink that executes the provided effectful function for every item fed * to it. diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index 378ea1399c..590bb77cc2 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -13,6 +13,7 @@ import { dual, identity } from "./Function.js" import type { TypeLambda } from "./HKT.js" import * as Option from "./Option.js" import { type Pipeable, pipeArguments } from "./Pipeable.js" +import type { Refinement } from "./Predicate.js" import { hasProperty } from "./Predicate.js" import type * as PubSub from "./PubSub.js" import * as Pull from "./Pull.js" @@ -799,6 +800,82 @@ export const concat: { flatten(fromArray>([self, that])) ) +/** + * @since 4.0.0 + * @category Error handling + */ +export const catchCause: { + ( + f: (cause: Cause.Cause) => Stream + ): (self: Stream) => Stream + ( + self: Stream, + f: (cause: Cause.Cause) => Stream + ): Stream +} = dual(2, ( + self: Stream, + f: (cause: Cause.Cause) => Stream +): Stream => + self.channel.pipe( + Channel.catchCause((cause) => f(cause).channel), + fromChannel + )) + +const catch_: { + ( + f: (error: E) => Stream + ): (self: Stream) => Stream + ( + self: Stream, + f: (error: E) => Stream + ): Stream +} = dual(2, ( + self: Stream, + f: (error: E) => Stream +): Stream => + self.channel.pipe( + Channel.catch((error) => f(error).channel), + fromChannel + )) + +export { + /** + * @since 4.0.0 + * @category Error handling + */ + catch_ as catch +} + +/** + * @since 4.0.0 + * @category Error handling + */ +export const catchFailure: { + , A2, E2, R2>( + refinement: Refinement, EB>, + f: (failure: EB, cause: Cause.Cause) => Stream + ): (self: Stream) => Stream> | E2, R2 | R> + , A2, E2, R2>( + self: Stream, + refinement: Refinement, EB>, + f: (failure: EB, cause: Cause.Cause) => Stream + ): Stream> | E2, R | R2> +} = dual(3, , A2, E2, R2>( + self: Stream, + refinement: Refinement, EB>, + f: (failure: EB, cause: Cause.Cause) => Stream +): Stream> | E2, R | R2> => + self.channel.pipe( + Channel.catchFailure(refinement, (failure, cause) => f(failure, cause).channel), + fromChannel + )) + +/** + * @since 2.0.0 + * @category Error handling + */ +export const orDie = (self: Stream): Stream => fromChannel(Channel.orDie(self.channel)) + /** * Takes the specified number of elements from this stream. * diff --git a/packages/effect/src/internal/core.ts b/packages/effect/src/internal/core.ts index a26f3016fc..c83b180c6c 100644 --- a/packages/effect/src/internal/core.ts +++ b/packages/effect/src/internal/core.ts @@ -7,7 +7,7 @@ import { identity } from "../Function.js" import * as Hash from "../Hash.js" import { format, NodeInspectSymbol } from "../Inspectable.js" import { pipeArguments } from "../Pipeable.js" -import { hasProperty, isObject, isTagged } from "../Predicate.js" +import { hasProperty, isObject } from "../Predicate.js" import type { Equals } from "../Types.js" import { SingleShotGen, YieldWrap } from "../Utils.js" import type { FiberImpl } from "./effect.js" @@ -306,10 +306,13 @@ export const causeDie = (defect: unknown): Cause.Cause => new CauseImpl([ /** @internal */ export const failureIsFail = ( self: Cause.Failure -): self is Cause.Fail => isTagged(self, "Fail") +): self is Cause.Fail => self._tag === "Fail" /** @internal */ -export const failureIsDie = (self: Cause.Failure): self is Cause.Die => isTagged(self, "Die") +export const failureIsDie = (self: Cause.Failure): self is Cause.Die => self._tag === "Die" + +/** @internal */ +export const failureIsInterrupt = (self: Cause.Failure): self is Cause.Interrupt => self._tag === "Interrupt" /** @internal */ export interface Primitive { diff --git a/packages/effect/src/unstable/HttpClient.ts b/packages/effect/src/unstable/HttpClient.ts index 744a31811b..0ccc266ee6 100644 --- a/packages/effect/src/unstable/HttpClient.ts +++ b/packages/effect/src/unstable/HttpClient.ts @@ -13,6 +13,7 @@ import { type Pipeable, pipeArguments } from "../Pipeable.js" import * as Predicate from "../Predicate.js" import * as Ref from "../Ref.js" import * as Schedule from "../Schedule.js" +import type * as Scope from "../Scope.js" import * as Stream from "../Stream.js" import * as Tracer from "../Tracer.js" import type { NoExcessProperties, NoInfer } from "../Types.js" @@ -577,7 +578,8 @@ export const make = ( makeWith((effect) => Effect.flatMap(effect, (request) => Effect.withFiber((fiber) => { - const controller = new AbortController() + const scopedController = scopedRequests.get(request) + const controller = scopedController ?? new AbortController() const urlResult = UrlParams.makeUrl(request.url, request.urlParams, request.hash) if (urlResult._tag === "Err") { return Effect.fail(new Error.RequestError({ request, reason: "InvalidUrl", cause: urlResult.err })) @@ -586,8 +588,10 @@ export const make = ( const tracerDisabled = fiber.getRef(Tracer.DisablePropagation) || fiber.getRef(TracerDisabledWhen)(request) if (tracerDisabled) { + const effect = f(request, url, controller.signal, fiber as any) + if (scopedController) return effect return Effect.uninterruptibleMask((restore) => - Effect.matchCauseEffect(restore(f(request, url, controller.signal, fiber as any)), { + Effect.matchCauseEffect(restore(effect), { onSuccess(response) { responseRegistry.register(response, controller) return Effect.succeed(new InterruptibleResponse(response, controller)) @@ -602,7 +606,7 @@ export const make = ( ) } return Effect.useSpan( - `http.client ${request.method}`, + fiber.getRef(SpanNameGenerator)(request), { kind: "client", captureStackTrace: false }, (span) => { span.attribute("http.request.method", request.method) @@ -636,11 +640,12 @@ export const make = ( span.attribute(`http.response.header.${name}`, String(redactedHeaders[name])) } + if (scopedController) return Effect.succeed(response) responseRegistry.register(response, controller) return Effect.succeed(new InterruptibleResponse(response, controller)) }, onFailure(cause) { - if (Cause.hasInterrupt(cause)) { + if (!scopedController && Cause.hasInterrupt(cause)) { controller.abort() } return Effect.failCause(cause) @@ -940,6 +945,27 @@ export const withCookiesRef: { ) ) +/** + * Ties the lifetime of the `HttpClientRequest` to a `Scope`. + * + * @since 4.0.0 + * @category Scope + */ +export const withScope = ( + self: HttpClient.With +): HttpClient.With => + transform( + self, + (effect, request) => { + const controller = new AbortController() + scopedRequests.set(request, controller) + return Effect.andThen( + Effect.addFinalizer(() => Effect.sync(() => controller.abort())), + effect + ) + } + ) + /** * Follows HTTP redirects up to a specified number of times. * @@ -980,7 +1006,7 @@ export const followRedirects: { /** * @since 4.0.0 - * @category fiber refs + * @category References */ export class TracerDisabledWhen extends Context.Reference< "effect/HttpClient/TracerDisabledWhen", @@ -991,12 +1017,23 @@ export class TracerDisabledWhen extends Context.Reference< /** * @since 4.0.0 - * @category fiber refs + * @category References */ export class TracerPropagationEnabled extends Context.Reference("effect/HttpClient/TracerPropagationEnabled", { defaultValue: () => constTrue }) {} +/** + * @since 4.0.0 + * @category References + */ +export class SpanNameGenerator extends Context.Reference< + "effect/HttpClient/SpanNameGenerator", + (request: HttpClientRequest.HttpClientRequest) => string +>("effect/HttpClient/SpanNameGenerator", { + defaultValue: () => (request) => `http.client ${request.method}` +}) {} + /** * @since 4.0.0 */ @@ -1046,6 +1083,8 @@ const responseRegistry = (() => { } })() +const scopedRequests = new WeakMap() + class InterruptibleResponse implements HttpClientResponse.HttpClientResponse { constructor( readonly original: HttpClientResponse.HttpClientResponse, diff --git a/packages/effect/src/unstable/HttpClientRequest.ts b/packages/effect/src/unstable/HttpClientRequest.ts index aa23217f3d..1ba41bb4da 100644 --- a/packages/effect/src/unstable/HttpClientRequest.ts +++ b/packages/effect/src/unstable/HttpClientRequest.ts @@ -10,6 +10,7 @@ import { type Pipeable, pipeArguments } from "../Pipeable.js" import type * as PlatformError from "../PlatformError.js" import { hasProperty } from "../Predicate.js" import * as Redacted from "../Redacted.js" +import * as Result from "../Result.js" import type * as Schema from "../Schema.js" import type { ParseOptions } from "../SchemaAST.js" import type * as Stream from "../Stream.js" @@ -697,6 +698,13 @@ export const bodyFile: { ) ) +/** + * @since 4.0.0 + * @category combinators + */ +export const toUrl = (self: HttpClientRequest): Option.Option => + Result.getOk(UrlParams.makeUrl(self.url, self.urlParams, self.hash)) + // ---------------------------------------------------------------------------- // internal // ---------------------------------------------------------------------------- diff --git a/packages/effect/src/unstable/UrlParams.ts b/packages/effect/src/unstable/UrlParams.ts index 85a8ad5052..1179a984b3 100644 --- a/packages/effect/src/unstable/UrlParams.ts +++ b/packages/effect/src/unstable/UrlParams.ts @@ -5,6 +5,7 @@ import * as Arr from "../Array.js" import { dual } from "../Function.js" import * as Option from "../Option.js" import * as Result from "../Result.js" +import * as Schema from "../Schema.js" /** * @since 4.0.0 @@ -193,11 +194,24 @@ export const remove: { (self: UrlParams, key: string): UrlParams } = dual(2, (self: UrlParams, key: string): UrlParams => Arr.filter(self, ([k]) => k !== key)) +/** + * @since 4.0.0 + * @category Errors + */ +export class UrlParamsError extends Schema.Class("effect/UrlParams/UrlParamsError")({ + _tag: Schema.tag("UrlParamsError"), + cause: Schema.Unknown +}) {} + /** * @since 4.0.0 * @category conversions */ -export const makeUrl = (url: string, params: UrlParams, hash: Option.Option): Result.Result => { +export const makeUrl = ( + url: string, + params: UrlParams, + hash: Option.Option +): Result.Result => { try { const urlInstance = new URL(url, baseUrl()) for (let i = 0; i < params.length; i++) { @@ -211,7 +225,7 @@ export const makeUrl = (url: string, params: UrlParams, hash: Option.Option { ) ] as const )).pipe(Stream.runCollect) - assert.deepStrictEqual(Array.from(result), [0, 1, 2, 3, 4, 5]) + assert.deepStrictEqual(result, [0, 1, 2, 3, 4, 5]) + })) + }) + + describe("error handling", () => { + it.effect("catch", () => + Effect.gen(function*() { + let error: string | undefined = undefined + const results = yield* Stream.make(1, 2, 3).pipe( + Stream.concat(Stream.fail("boom")), + Stream.catch((error_) => { + error = error_ + return Stream.make(4, 5, 6) + }), + Stream.runCollect + ) + assert.deepStrictEqual(results, [1, 2, 3, 4, 5, 6]) + assert.strictEqual(error, "boom") })) }) }) diff --git a/packages/platform-node-shared/src/NodeFileSystem.ts b/packages/platform-node-shared/src/NodeFileSystem.ts index bbf256fe1d..c8cbd8ccdb 100644 --- a/packages/platform-node-shared/src/NodeFileSystem.ts +++ b/packages/platform-node-shared/src/NodeFileSystem.ts @@ -19,10 +19,10 @@ import * as Path from "node:path" import { handleErrnoException } from "./internal/utils.js" const handleBadArgument = (method: string) => (err: unknown) => - Error.BadArgument({ + new Error.BadArgument({ module: "FileSystem", method, - message: (err as Error).message ?? String(err) + description: (err as Error).message ?? String(err) }) // == access @@ -336,13 +336,15 @@ const makeFile = (() => { nodeWriteAll(this.fd, buffer, undefined, undefined, this.append ? undefined : Number(position)), (bytesWritten) => { if (bytesWritten === 0) { - return Effect.fail(Error.SystemError({ - module: "FileSystem", - method: "writeAll", - reason: "WriteZero", - pathOrDescriptor: this.fd, - message: "write returned 0 bytes written" - })) + return Effect.fail( + new Error.SystemError({ + module: "FileSystem", + method: "writeAll", + reason: "WriteZero", + pathOrDescriptor: this.fd, + description: "write returned 0 bytes written" + }) + ) } if (!this.append) { @@ -549,12 +551,12 @@ const watchNode = (path: string) => Queue.unsafeDone( queue, Exit.fail( - Error.SystemError({ + new Error.SystemError({ module: "FileSystem", reason: "Unknown", method: "watch", pathOrDescriptor: path, - message: error.message + cause: error }) ) ) diff --git a/packages/platform-node-shared/src/NodePath.ts b/packages/platform-node-shared/src/NodePath.ts index b290c29b7c..a26522b8d4 100644 --- a/packages/platform-node-shared/src/NodePath.ts +++ b/packages/platform-node-shared/src/NodePath.ts @@ -11,22 +11,22 @@ import * as NodeUrl from "node:url" const fromFileUrl = (url: URL): Effect.Effect => Effect.try({ try: () => NodeUrl.fileURLToPath(url), - catch: (error) => - BadArgument({ + catch: (cause) => + new BadArgument({ module: "Path", method: "fromFileUrl", - message: `${error}` + cause }) }) const toFileUrl = (path: string): Effect.Effect => Effect.try({ try: () => NodeUrl.pathToFileURL(path), - catch: (error) => - BadArgument({ + catch: (cause) => + new BadArgument({ module: "Path", method: "toFileUrl", - message: `${error}` + cause }) }) diff --git a/packages/platform-node-shared/src/NodeSink.ts b/packages/platform-node-shared/src/NodeSink.ts index 0db5440cbe..70987d39de 100644 --- a/packages/platform-node-shared/src/NodeSink.ts +++ b/packages/platform-node-shared/src/NodeSink.ts @@ -5,6 +5,8 @@ import type { NonEmptyReadonlyArray } from "effect/Array" import * as Channel from "effect/Channel" import * as Effect from "effect/Effect" import { identity, type LazyArg } from "effect/Function" +import type { PlatformError } from "effect/PlatformError" +import { SystemError } from "effect/PlatformError" import * as Pull from "effect/Pull" import * as Sink from "effect/Sink" import type { Writable } from "node:stream" @@ -48,7 +50,7 @@ export const pullIntoWritable = (options: { readonly onError: (error: unknown) => E readonly endOnDone?: boolean | undefined readonly encoding?: BufferEncoding | undefined -}) => +}): Pull.Pull => options.pull.pipe( Effect.flatMap((chunk) => { let i = 0 @@ -76,3 +78,18 @@ export const pullIntoWritable = (options: { }) : identity ) + +/** + * @category stdio + * @since 1.0.0 + */ +export const stdout: Sink.Sink = fromWritable({ + evaluate: () => process.stdout, + onError: (cause) => + new SystemError({ + module: "Stream", + method: "stdout", + reason: "Unknown", + cause + }) +}) diff --git a/packages/platform-node-shared/src/NodeStream.ts b/packages/platform-node-shared/src/NodeStream.ts index d4426aae46..88b91e1836 100644 --- a/packages/platform-node-shared/src/NodeStream.ts +++ b/packages/platform-node-shared/src/NodeStream.ts @@ -262,6 +262,14 @@ export const toUint8Array = ( }) } +/** + * @since 1.0.0 + * @category stdio + */ +export const stdin: Stream.Stream = Stream.orDie(fromReadable({ + evaluate: () => process.stdin +})) + // ---------------------------------------------------------------------------- // internal // ---------------------------------------------------------------------------- @@ -315,7 +323,6 @@ class StreamAdapter extends Readable { this.readLatch = Effect.unsafeMakeLatch(false) this.fiber = Stream.runForEachChunk(stream, (chunk) => this.readLatch.whenOpen(Effect.sync(() => { - if (chunk.length === 0) return this.readLatch.unsafeClose() for (let i = 0; i < chunk.length; i++) { const item = chunk[i] diff --git a/packages/platform-node-shared/src/internal/utils.ts b/packages/platform-node-shared/src/internal/utils.ts index 3664182857..e4b5f6d659 100644 --- a/packages/platform-node-shared/src/internal/utils.ts +++ b/packages/platform-node-shared/src/internal/utils.ts @@ -40,12 +40,12 @@ export const handleErrnoException = (module: SystemError["module"], method: stri break } - return SystemError({ + return new SystemError({ reason, module, method, pathOrDescriptor: path as string | number, syscall: err.syscall, - message: err.message + cause: err }) }