diff --git a/packages/effect/package.json b/packages/effect/package.json index a353a6a430..9103b40a6f 100644 --- a/packages/effect/package.json +++ b/packages/effect/package.json @@ -101,6 +101,8 @@ }, "dependencies": { "@standard-schema/spec": "^1.0.0", - "fast-check": "^4.2.0" + "fast-check": "^4.2.0", + "find-my-way-ts": "^0.1.6", + "multipasta": "^0.2.5" } } diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index 4c7226b1d2..6ab73afc8e 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -355,6 +355,15 @@ export const fromFailures: ( failures: ReadonlyArray> ) => Cause = core.causeFromFailures +/** + * A `Cause` that that contains no failures, representing a successful + * computation or an empty state. + * + * @category constructors + * @since 2.0.0 + */ +export const empty: Cause = core.causeEmpty + /** * Creates a `Cause` that represents a typed error. * diff --git a/packages/effect/src/Channel.ts b/packages/effect/src/Channel.ts index 0d46be2a2a..ccadacf7e5 100644 --- a/packages/effect/src/Channel.ts +++ b/packages/effect/src/Channel.ts @@ -2621,6 +2621,29 @@ export { catch_ as catch } +/** + * Returns a new channel, which is the same as this one, except the failure + * value of the returned channel is created by applying the specified function + * to the failure value of this channel. + * + * @since 2.0.0 + * @category Error handling + */ +export const mapError: { + ( + f: (err: OutErr) => OutErr2 + ): ( + self: Channel + ) => Channel + ( + self: Channel, + f: (err: OutErr) => OutErr2 + ): Channel +} = dual(2, ( + self: Channel, + f: (err: OutErr) => OutErr2 +): Channel => catch_(self, (err) => fail(f(err)))) + /** * Converts all errors in the channel to defects (unrecoverable failures). * This is useful when you want to treat errors as programming errors. @@ -3438,6 +3461,26 @@ const runWith = < ) as any }) +/** + * @since 4.0.0 + * @category Services + */ +export const provideServices: { + ( + services: ServiceMap.ServiceMap + ): ( + self: Channel + ) => Channel> + ( + self: Channel, + services: ServiceMap.ServiceMap + ): Channel> +} = dual(2, ( + self: Channel, + services: ServiceMap.ServiceMap +): Channel> => + fromTransform((upstream, scope) => Effect.provideServices(toTransform(self)(upstream, scope), services))) + /** * Runs a channel and counts the number of elements it outputs. * diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index c4de4f122e..04fc1e02ee 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -1773,6 +1773,13 @@ export const flatMap: { ): Effect } = internal.flatMap +/** + * @since 2.0.0 + * @category Sequencing + */ +export const flatten: (self: Effect, E2, R2>) => Effect = + internal.flatten + /** * Chains two actions, where the second action can depend on the result of the * first. @@ -5121,6 +5128,20 @@ export const onExit: { ): Effect } = internal.onExit +/** + * @since 4.0.0 + * @category Resource management & finalization + */ +export const onExitInterruptible: { + ( + cleanup: (exit: Exit.Exit) => Effect + ): (self: Effect) => Effect + ( + self: Effect, + cleanup: (exit: Exit.Exit) => Effect + ): Effect +} = internal.onExitInterruptible + // ----------------------------------------------------------------------------- // Caching // ----------------------------------------------------------------------------- @@ -5188,9 +5209,7 @@ export const onExit: { * @since 2.0.0 * @category Caching */ -export const cached: ( - self: Effect -) => Effect, never, R> = internal.cached +export const cached: (self: Effect) => Effect> = internal.cached /** * Returns an effect that caches its result for a specified `Duration`, @@ -5259,13 +5278,8 @@ export const cached: ( * @category Caching */ export const cachedWithTTL: { - ( - timeToLive: Duration.DurationInput - ): (self: Effect) => Effect, never, R> - ( - self: Effect, - timeToLive: Duration.DurationInput - ): Effect, never, R> + (timeToLive: Duration.DurationInput): (self: Effect) => Effect> + (self: Effect, timeToLive: Duration.DurationInput): Effect> } = internal.cachedWithTTL /** @@ -5338,15 +5352,8 @@ export const cachedWithTTL: { * @category Caching */ export const cachedInvalidateWithTTL: { - ( - timeToLive: Duration.DurationInput - ): ( - self: Effect - ) => Effect<[Effect, Effect], never, R> - ( - self: Effect, - timeToLive: Duration.DurationInput - ): Effect<[Effect, Effect], never, R> + (timeToLive: Duration.DurationInput): (self: Effect) => Effect<[Effect, Effect]> + (self: Effect, timeToLive: Duration.DurationInput): Effect<[Effect, Effect]> } = internal.cachedInvalidateWithTTL // ----------------------------------------------------------------------------- diff --git a/packages/effect/src/Fiber.ts b/packages/effect/src/Fiber.ts index c1d6d15a77..083129511b 100644 --- a/packages/effect/src/Fiber.ts +++ b/packages/effect/src/Fiber.ts @@ -76,10 +76,10 @@ import type { Effect } from "./Effect.js" import type { Exit } from "./Exit.js" import * as effect from "./internal/effect.js" import { version } from "./internal/version.js" -import type { Option } from "./Option.js" import type { Pipeable } from "./Pipeable.js" import { hasProperty } from "./Predicate.js" import type { Scheduler } from "./Scheduler.js" +import type { Scope } from "./Scope.js" import type * as ServiceMap from "./ServiceMap.js" import type { AnySpan, Span } from "./Tracer.js" import type { Covariant } from "./Types.js" @@ -452,7 +452,7 @@ export const isFiber = ( /** * Returns the current fiber if called from within a fiber context, - * otherwise returns `None`. + * otherwise returns `undefined`. * * @example * ```ts @@ -460,8 +460,8 @@ export const isFiber = ( * * const program = Effect.gen(function* () { * const current = Fiber.getCurrent() - * if (Option.isSome(current)) { - * console.log(`Current fiber ID: ${current.value.id}`) + * if (current) { + * console.log(`Current fiber ID: ${current.id}`) * } * }) * ``` @@ -469,4 +469,13 @@ export const isFiber = ( * @since 2.0.0 * @category accessors */ -export const getCurrent: () => Option> = effect.getCurrentFiber +export const getCurrent: () => Fiber | undefined = effect.getCurrentFiber + +/** + * @since 4.0.0 + * @category Scope + */ +export const runIn: { + (scope: Scope): (self: Fiber) => Fiber + (self: Fiber, scope: Scope): Fiber +} = effect.fiberRunIn diff --git a/packages/effect/src/FileSystem.ts b/packages/effect/src/FileSystem.ts index 27a21b6e86..dda5b1db66 100644 --- a/packages/effect/src/FileSystem.ts +++ b/packages/effect/src/FileSystem.ts @@ -1063,9 +1063,9 @@ export interface SinkOptions extends OpenFileOptions {} * @category options */ export interface StreamOptions { - readonly bytesToRead?: SizeInput - readonly chunkSize?: SizeInput - readonly offset?: SizeInput + readonly bytesToRead?: SizeInput | undefined + readonly chunkSize?: SizeInput | undefined + readonly offset?: SizeInput | undefined } /** diff --git a/packages/effect/src/ManagedRuntime.ts b/packages/effect/src/ManagedRuntime.ts new file mode 100644 index 0000000000..230406a247 --- /dev/null +++ b/packages/effect/src/ManagedRuntime.ts @@ -0,0 +1,249 @@ +/** + * @since 2.0.0 + */ +import * as Effect from "./Effect.js" +import * as Exit from "./Exit.js" +import * as Fiber from "./Fiber.js" +import * as Layer from "./Layer.js" +import { hasProperty } from "./Predicate.js" +import * as Scope from "./Scope.js" +import type * as ServiceMap from "./ServiceMap.js" +import type { Mutable } from "./Types.js" + +/** + * @since 3.9.0 + * @category symbol + */ +export const TypeId: TypeId = "~effect/ManagedRuntime" + +/** + * @since 3.9.0 + * @category symbol + */ +export type TypeId = "~effect/ManagedRuntime" + +/** + * Checks if the provided argument is a `ManagedRuntime`. + * + * @since 3.9.0 + * @category guards + */ +export const isManagedRuntime = (input: unknown): input is ManagedRuntime => + hasProperty(input, TypeId) + +/** + * @since 3.4.0 + */ +export declare namespace ManagedRuntime { + /** + * @category type-level + * @since 4.0.0 + */ + export type Services> = [T] extends [ManagedRuntime] ? R + : never + /** + * @category type-level + * @since 3.4.0 + */ + export type Error> = [T] extends [ManagedRuntime] ? E : never +} + +/** + * @since 2.0.0 + * @category models + */ +export interface ManagedRuntime { + readonly [TypeId]: TypeId + readonly memoMap: Layer.MemoMap + readonly servicesEffect: Effect.Effect, ER> + readonly services: () => Promise> + + // internal + readonly scope: Scope.Scope.Closeable + // internal + cachedServices: ServiceMap.ServiceMap | undefined + + /** + * Executes the effect using the provided Scheduler or using the global + * Scheduler if not provided + */ + readonly runFork: ( + self: Effect.Effect, + options?: Effect.RunOptions + ) => Fiber.Fiber + + /** + * Executes the effect synchronously returning the exit. + * + * This method is effectful and should only be invoked at the edges of your + * program. + */ + readonly runSyncExit: (effect: Effect.Effect) => Exit.Exit + + /** + * Executes the effect synchronously throwing in case of errors or async boundaries. + * + * This method is effectful and should only be invoked at the edges of your + * program. + */ + readonly runSync: (effect: Effect.Effect) => A + + // /** + // * Executes the effect asynchronously, eventually passing the exit value to + // * the specified callback. + // * + // * This method is effectful and should only be invoked at the edges of your + // * program. + // */ + // readonly runCallback: ( + // effect: Effect.Effect, + // options?: Runtime.RunCallbackOptions | undefined + // ) => Runtime.Cancel + + /** + * Runs the `Effect`, returning a JavaScript `Promise` that will be resolved + * with the value of the effect once the effect has been executed, or will be + * rejected with the first error or exception throw by the effect. + * + * This method is effectful and should only be used at the edges of your + * program. + */ + readonly runPromise: (effect: Effect.Effect, options?: Effect.RunOptions) => Promise + + /** + * Runs the `Effect`, returning a JavaScript `Promise` that will be resolved + * with the `Exit` state of the effect once the effect has been executed. + * + * This method is effectful and should only be used at the edges of your + * program. + */ + readonly runPromiseExit: ( + effect: Effect.Effect, + options?: Effect.RunOptions + ) => Promise> + + /** + * Dispose of the resources associated with the runtime. + */ + readonly dispose: () => Promise + + /** + * Dispose of the resources associated with the runtime. + */ + readonly disposeEffect: Effect.Effect +} + +/** + * Convert a Layer into an ManagedRuntime, that can be used to run Effect's using + * your services. + * + * @since 2.0.0 + * @category runtime class + * @example + * ```ts + * import { Console, Effect, Layer, ManagedRuntime, ServiceMap } from "effect" + * + * class Notifications extends ServiceMap.Key< + * Notifications, + * { readonly notify: (message: string) => Effect.Effect } + * >()("Notifications") { + * static layer = Layer.succeed(this, { notify: (message) => Console.log(message) }) + * } + * + * async function main() { + * const runtime = ManagedRuntime.make(Notifications.layer) + * await runtime.runPromise(Effect.flatMap( + * Notifications.asEffect(), + * (_) => _.notify("Hello, world!") + * )) + * await runtime.dispose() + * } + * + * main() + * ``` + */ +export const make = ( + layer: Layer.Layer, + options?: { + readonly memoMap?: Layer.MemoMap | undefined + } | undefined +): ManagedRuntime => { + const memoMap = options?.memoMap ?? Layer.unsafeMakeMemoMap() + const scope = Scope.unsafeMake() + let buildFiber: Fiber.Fiber, ER> | undefined + const servicesEffect = Effect.withFiber, ER>((fiber) => { + if (!buildFiber) { + buildFiber = Fiber.runIn( + Effect.runFork( + Effect.tap( + Layer.buildWithMemoMap(layer, memoMap, scope), + (services) => { + self.cachedServices = services + } + ), + { scheduler: fiber.currentScheduler } + ), + scope + ) + } + return Effect.flatten(Fiber.await(buildFiber)) + }) + const self: ManagedRuntime = { + [TypeId]: TypeId, + memoMap, + scope, + servicesEffect, + cachedServices: undefined, + services() { + return self.cachedServices === undefined ? + Effect.runPromise(self.servicesEffect) : + Promise.resolve(self.cachedServices) + }, + dispose(): Promise { + return Effect.runPromise(self.disposeEffect) + }, + disposeEffect: Effect.suspend(() => { + ;(self as Mutable>).servicesEffect = Effect.die("ManagedRuntime disposed") + self.cachedServices = undefined + return Scope.close(self.scope, Exit.void) + }), + runFork(effect: Effect.Effect, options?: Effect.RunOptions): Fiber.Fiber { + return self.cachedServices === undefined ? + Effect.runFork(provide(self, effect), options) : + Effect.runForkWith(self.cachedServices)(effect, options) + }, + runSyncExit(effect: Effect.Effect): Exit.Exit { + return self.cachedServices === undefined ? + Effect.runSyncExit(provide(self, effect)) : + Effect.runSyncExitWith(self.cachedServices)(effect) + }, + runSync(effect: Effect.Effect): A { + return self.cachedServices === undefined ? + Effect.runSync(provide(self, effect)) : + Effect.runSyncWith(self.cachedServices)(effect) + }, + runPromiseExit(effect: Effect.Effect, options?: Effect.RunOptions): Promise> { + return self.cachedServices === undefined ? + Effect.runPromiseExit(provide(self, effect), options) : + Effect.runPromiseExitWith(self.cachedServices)(effect, options) + }, + runPromise(effect: Effect.Effect, options?: { + readonly signal?: AbortSignal | undefined + }): Promise { + return self.cachedServices === undefined ? + Effect.runPromise(provide(self, effect), options) : + Effect.runPromiseWith(self.cachedServices)(effect, options) + } + } + return self +} + +function provide( + managed: ManagedRuntime, + effect: Effect.Effect +): Effect.Effect { + return Effect.flatMap( + managed.servicesEffect, + (services) => Effect.provideServices(effect, services) + ) +} diff --git a/packages/effect/src/Path.ts b/packages/effect/src/Path.ts index b522def5c5..4d3a594c04 100644 --- a/packages/effect/src/Path.ts +++ b/packages/effect/src/Path.ts @@ -1,8 +1,10 @@ /** * @since 4.0.0 */ -import type { Effect } from "./Effect.js" -import type { BadArgument } from "./PlatformError.js" +import * as Effect from "./Effect.js" +import { identity } from "./Function.js" +import * as Layer from "./Layer.js" +import { BadArgument } from "./PlatformError.js" import * as ServiceMap from "./ServiceMap.js" /** @@ -75,14 +77,14 @@ export interface Path { readonly dirname: (path: string) => string readonly extname: (path: string) => string readonly format: (pathObject: Partial) => string - readonly fromFileUrl: (url: URL) => Effect + readonly fromFileUrl: (url: URL) => Effect.Effect readonly isAbsolute: (path: string) => boolean readonly join: (...paths: ReadonlyArray) => string readonly normalize: (path: string) => string readonly parse: (path: string) => Path.Parsed readonly relative: (from: string, to: string) => string readonly resolve: (...pathSegments: ReadonlyArray) => string - readonly toFileUrl: (path: string) => Effect + readonly toFileUrl: (path: string) => Effect.Effect readonly toNamespacedPath: (path: string) => string } @@ -211,3 +213,601 @@ export declare namespace Path { * ``` */ export const Path: ServiceMap.Key = ServiceMap.Key("effect/Path") + +/** + * The following functions are adapted from the Node.js source code: + * https://github.com/nodejs/node/blob/main/lib/internal/url.js + * + * The following license applies to these functions: + * - MIT + */ + +// Resolves . and .. elements in a path with directory names +function normalizeStringPosix(path: string, allowAboveRoot: boolean) { + let res = "" + let lastSegmentLength = 0 + let lastSlash = -1 + let dots = 0 + let code + for (let i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i) + } else if (code === 47 /*/*/) { + break + } else { + code = 47 /*/*/ + } + if (code === 47 /*/*/) { + if (lastSlash === i - 1 || dots === 1) { + // NOOP + } else if (lastSlash !== i - 1 && dots === 2) { + if ( + res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || + res.charCodeAt(res.length - 2) !== 46 /*.*/ + ) { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/") + if (lastSlashIndex !== res.length - 1) { + if (lastSlashIndex === -1) { + res = "" + lastSegmentLength = 0 + } else { + res = res.slice(0, lastSlashIndex) + lastSegmentLength = res.length - 1 - res.lastIndexOf("/") + } + lastSlash = i + dots = 0 + continue + } + } else if (res.length === 2 || res.length === 1) { + res = "" + lastSegmentLength = 0 + lastSlash = i + dots = 0 + continue + } + } + if (allowAboveRoot) { + if (res.length > 0) { + res += "/.." + } else { + res = ".." + } + lastSegmentLength = 2 + } + } else { + if (res.length > 0) { + res += "/" + path.slice(lastSlash + 1, i) + } else { + res = path.slice(lastSlash + 1, i) + } + lastSegmentLength = i - lastSlash - 1 + } + lastSlash = i + dots = 0 + } else if (code === 46 /*.*/ && dots !== -1) { + ++dots + } else { + dots = -1 + } + } + return res +} + +function _format(sep: string, pathObject: Partial) { + const dir = pathObject.dir || pathObject.root + const base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "") + if (!dir) { + return base + } + if (dir === pathObject.root) { + return dir + base + } + return dir + sep + base +} + +function fromFileUrl(url: URL): Effect.Effect { + if (url.protocol !== "file:") { + return Effect.fail( + new BadArgument({ + module: "Path", + method: "fromFileUrl", + description: "URL must be of scheme file" + }) + ) + } else if (url.hostname !== "") { + return Effect.fail( + new BadArgument({ + module: "Path", + method: "fromFileUrl", + description: "Invalid file URL host" + }) + ) + } + const pathname = url.pathname + for (let n = 0; n < pathname.length; n++) { + if (pathname[n] === "%") { + const third = pathname.codePointAt(n + 2)! | 0x20 + if (pathname[n + 1] === "2" && third === 102) { + return Effect.fail( + new BadArgument({ + module: "Path", + method: "fromFileUrl", + description: "must not include encoded / characters" + }) + ) + } + } + } + return Effect.succeed(decodeURIComponent(pathname)) +} + +const resolve: Path["resolve"] = function resolve() { + let resolvedPath = "" + let resolvedAbsolute = false + let cwd: string | undefined = undefined + + for (let i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + let path: string + if (i >= 0) { + path = arguments[i] + } else { + const process = (globalThis as any).process + if ( + cwd === undefined && "process" in globalThis && + typeof process === "object" && + process !== null && + typeof process.cwd === "function" + ) { + cwd = process.cwd() + } + path = cwd! + } + + // Skip empty entries + if (path.length === 0) { + continue + } + + resolvedPath = path + "/" + resolvedPath + resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/ + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute) + + if (resolvedAbsolute) { + if (resolvedPath.length > 0) { + return "/" + resolvedPath + } else { + return "/" + } + } else if (resolvedPath.length > 0) { + return resolvedPath + } else { + return "." + } +} + +const CHAR_FORWARD_SLASH = 47 + +function toFileUrl(filepath: string) { + const outURL = new URL("file://") + let resolved = resolve(filepath) + // path.resolve strips trailing slashes so we must add them back + const filePathLast = filepath.charCodeAt(filepath.length - 1) + if ( + (filePathLast === CHAR_FORWARD_SLASH) && + resolved[resolved.length - 1] !== "/" + ) { + resolved += "/" + } + outURL.pathname = encodePathChars(resolved) + return Effect.succeed(outURL) +} + +const percentRegEx = /%/g +const backslashRegEx = /\\/g +const newlineRegEx = /\n/g +const carriageReturnRegEx = /\r/g +const tabRegEx = /\t/g + +function encodePathChars(filepath: string) { + if (filepath.includes("%")) { + filepath = filepath.replace(percentRegEx, "%25") + } + if (filepath.includes("\\")) { + filepath = filepath.replace(backslashRegEx, "%5C") + } + if (filepath.includes("\n")) { + filepath = filepath.replace(newlineRegEx, "%0A") + } + if (filepath.includes("\r")) { + filepath = filepath.replace(carriageReturnRegEx, "%0D") + } + if (filepath.includes("\t")) { + filepath = filepath.replace(tabRegEx, "%09") + } + return filepath +} + +const posixImpl = Path.of({ + [TypeId]: TypeId, + resolve, + normalize(path) { + if (path.length === 0) return "." + + const isAbsolute = path.charCodeAt(0) === 47 /*/*/ + const trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/ + + // Normalize the path + path = normalizeStringPosix(path, !isAbsolute) + + if (path.length === 0 && !isAbsolute) path = "." + if (path.length > 0 && trailingSeparator) path += "/" + + if (isAbsolute) return "/" + path + return path + }, + + isAbsolute(path) { + return path.length > 0 && path.charCodeAt(0) === 47 /*/*/ + }, + + join() { + if (arguments.length === 0) { + return "." + } + let joined + for (let i = 0; i < arguments.length; ++i) { + const arg = arguments[i] + if (arg.length > 0) { + if (joined === undefined) { + joined = arg + } else { + joined += "/" + arg + } + } + } + if (joined === undefined) { + return "." + } + return posixImpl.normalize(joined) + }, + + relative(from, to) { + if (from === to) return "" + + from = posixImpl.resolve(from) + to = posixImpl.resolve(to) + + if (from === to) return "" + + // Trim any leading backslashes + let fromStart = 1 + for (; fromStart < from.length; ++fromStart) { + if (from.charCodeAt(fromStart) !== 47 /*/*/) { + break + } + } + const fromEnd = from.length + const fromLen = fromEnd - fromStart + + // Trim any leading backslashes + let toStart = 1 + for (; toStart < to.length; ++toStart) { + if (to.charCodeAt(toStart) !== 47 /*/*/) { + break + } + } + const toEnd = to.length + const toLen = toEnd - toStart + + // Compare paths to find the longest common path from root + const length = fromLen < toLen ? fromLen : toLen + let lastCommonSep = -1 + let i = 0 + for (; i <= length; ++i) { + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === 47 /*/*/) { + // We get here if `from` is the exact base path for `to`. + // For example: from='/foo/bar'; to='/foo/bar/baz' + return to.slice(toStart + i + 1) + } else if (i === 0) { + // We get here if `from` is the root + // For example: from='/'; to='/foo' + return to.slice(toStart + i) + } + } else if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === 47 /*/*/) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i + } else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo'; to='/' + lastCommonSep = 0 + } + } + break + } + const fromCode = from.charCodeAt(fromStart + i) + const toCode = to.charCodeAt(toStart + i) + if (fromCode !== toCode) { + break + } else if (fromCode === 47 /*/*/) { + lastCommonSep = i + } + } + + let out = "" + // Generate the relative path based on the path difference between `to` + // and `from` + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) { + if (out.length === 0) { + out += ".." + } else { + out += "/.." + } + } + } + + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) { + return out + to.slice(toStart + lastCommonSep) + } else { + toStart += lastCommonSep + if (to.charCodeAt(toStart) === 47 /*/*/) { + ++toStart + } + return to.slice(toStart) + } + }, + + dirname(path) { + if (path.length === 0) return "." + let code = path.charCodeAt(0) + const hasRoot = code === 47 /*/*/ + let end = -1 + let matchedSlash = true + for (let i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i) + if (code === 47 /*/*/) { + if (!matchedSlash) { + end = i + break + } + } else { + // We saw the first non-path separator + matchedSlash = false + } + } + + if (end === -1) return hasRoot ? "/" : "." + if (hasRoot && end === 1) return "//" + return path.slice(0, end) + }, + + basename(path, ext) { + let start = 0 + let end = -1 + let matchedSlash = true + let i + + if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { + if (ext.length === path.length && ext === path) return "" + let extIdx = ext.length - 1 + let firstNonSlashEnd = -1 + for (i = path.length - 1; i >= 0; --i) { + const code = path.charCodeAt(i) + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1 + break + } + } else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false + firstNonSlashEnd = i + 1 + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i + } + } else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1 + end = firstNonSlashEnd + } + } + } + } + + if (start === end) end = firstNonSlashEnd + else if (end === -1) end = path.length + return path.slice(start, end) + } else { + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1 + break + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false + end = i + 1 + } + } + + if (end === -1) return "" + return path.slice(start, end) + } + }, + + extname(path) { + let startDot = -1 + let startPart = 0 + let end = -1 + let matchedSlash = true + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0 + for (let i = path.length - 1; i >= 0; --i) { + const code = path.charCodeAt(i) + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1 + break + } + continue + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false + end = i + 1 + } + if (code === 46 /*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) { + startDot = i + } else if (preDotState !== 1) { + preDotState = 1 + } + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1 + } + } + + if ( + startDot === -1 || end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1 + ) { + return "" + } + return path.slice(startDot, end) + }, + + format: function format(pathObject) { + if (pathObject === null || typeof pathObject !== "object") { + throw new TypeError("The \"pathObject\" argument must be of type Object. Received type " + typeof pathObject) + } + return _format("/", pathObject) + }, + + parse(path) { + const ret = { root: "", dir: "", base: "", ext: "", name: "" } + if (path.length === 0) return ret + let code = path.charCodeAt(0) + const isAbsolute = code === 47 /*/*/ + let start + if (isAbsolute) { + ret.root = "/" + start = 1 + } else { + start = 0 + } + let startDot = -1 + let startPart = 0 + let end = -1 + let matchedSlash = true + let i = path.length - 1 + + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0 + + // Get non-dir info + for (; i >= start; --i) { + code = path.charCodeAt(i) + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1 + break + } + continue + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false + end = i + 1 + } + if (code === 46 /*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i + else if (preDotState !== 1) preDotState = 1 + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1 + } + } + + if ( + startDot === -1 || end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1 + ) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end) + else ret.base = ret.name = path.slice(startPart, end) + } + } else { + if (startPart === 0 && isAbsolute) { + ret.name = path.slice(1, startDot) + ret.base = path.slice(1, end) + } else { + ret.name = path.slice(startPart, startDot) + ret.base = path.slice(startPart, end) + } + ret.ext = path.slice(startDot, end) + } + + if (startPart > 0) ret.dir = path.slice(0, startPart - 1) + else if (isAbsolute) ret.dir = "/" + + return ret + }, + + sep: "/", + fromFileUrl, + toFileUrl, + toNamespacedPath: identity +}) + +/** + * @since 4.0.0 + * @category Layers + */ +export const layer: Layer.Layer = Layer.succeed(Path, posixImpl) diff --git a/packages/effect/src/Scope.ts b/packages/effect/src/Scope.ts index 578943d7f7..9af41c4ec4 100644 --- a/packages/effect/src/Scope.ts +++ b/packages/effect/src/Scope.ts @@ -80,7 +80,7 @@ export type TypeId = "~effect/Scope" export interface Scope { readonly [TypeId]: TypeId readonly strategy: "sequential" | "parallel" - state: Scope.State.Open | Scope.State.Closed + state: Scope.State.Open | Scope.State.Closed | Scope.State.Empty } /** @@ -141,6 +141,29 @@ export declare namespace Scope { * @category models */ export namespace State { + /** + * Represents an open scope state where finalizers can be added and + * the scope is still accepting new resources. + * + * @example + * ```ts + * import { Scope, Effect, Exit } from "effect" + * + * const scope = Scope.unsafeMake() + * + * // When scope is open, you can check its state + * if (scope.state._tag === "Open") { + * console.log("Scope is open and accepting finalizers") + * console.log(scope.state.finalizers.size) // Number of registered finalizers + * } + * ``` + * + * @since 2.0.0 + * @category models + */ + export type Empty = { + readonly _tag: "Empty" + } /** * Represents an open scope state where finalizers can be added and * the scope is still accepting new resources. diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index 97e7d1cbf0..a97bc07289 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -299,6 +299,16 @@ export const fromChannel = , E, R>( return self } +/** + * Either emits the success value of this effect or terminates the stream + * with the failure value of this effect. + * + * @since 2.0.0 + * @category constructors + */ +export const fromEffect = (effect: Effect.Effect): Stream => + fromChannel(Channel.fromEffect(Effect.map(effect, Arr.of))) + /** * Creates a stream from a pull effect. * @@ -1410,11 +1420,7 @@ const catch_: { } = dual(2, ( self: Stream, f: (error: E) => Stream -): Stream => - self.channel.pipe( - Channel.catch((error) => f(error).channel), - fromChannel - )) +): Stream => fromChannel(Channel.catch(self.channel, (error) => f(error).channel))) export { /** @@ -1424,6 +1430,20 @@ export { catch_ as catch } +/** + * Transforms the errors emitted by this stream using `f`. + * + * @since 2.0.0 + * @category Error handling + */ +export const mapError: { + (f: (error: E) => E2): (self: Stream) => Stream + (self: Stream, f: (error: E) => E2): Stream +} = dual(2, ( + self: Stream, + f: (error: E) => E2 +): Stream => fromChannel(Channel.mapError(self.channel, f))) + /** * Conditionally handles stream failures based on a predicate applied to the Cause. * @@ -1994,15 +2014,47 @@ export const encodeText = (self: Stream): Stream( finalizer: (exit: Exit.Exit) => Effect.Effect - ) => (self: Stream) => Stream, + ): (self: Stream) => Stream ( self: Stream, finalizer: (exit: Exit.Exit) => Effect.Effect - ) => Stream ->(2, (self, finalizer) => fromChannel(Channel.onExit(self.channel, finalizer))) + ): Stream +} = dual(2, ( + self: Stream, + finalizer: (exit: Exit.Exit) => Effect.Effect +): Stream => fromChannel(Channel.onExit(self.channel, finalizer))) + +/** + * @since 4.0.0 + * @category utils + */ +export const ensuring: { + (finalizer: Effect.Effect): (self: Stream) => Stream + (self: Stream, finalizer: Effect.Effect): Stream +} = dual( + 2, + (self: Stream, finalizer: Effect.Effect): Stream => + fromChannel(Channel.ensuring(self.channel, finalizer)) +) + +/** + * Provides the stream with some of its required services, which eliminates its + * dependency on `R`. + * + * @since 4.0.0 + * @category context + */ +export const provideServices: { + (services: ServiceMap.ServiceMap): (self: Stream) => Stream> + (self: Stream, services: ServiceMap.ServiceMap): Stream> +} = dual( + 2, + (self: Stream, services: ServiceMap.ServiceMap): Stream> => + fromChannel(Channel.provideServices(self.channel, services)) +) /** * Runs the sink on the stream to produce either the sink's result or an error. diff --git a/packages/effect/src/index.ts b/packages/effect/src/index.ts index 5d749ac1ed..9c3e81248b 100644 --- a/packages/effect/src/index.ts +++ b/packages/effect/src/index.ts @@ -1239,6 +1239,11 @@ export * as Logger from "./Logger.js" */ export * as LogLevel from "./LogLevel.js" +/** + * @since 2.0.0 + */ +export * as ManagedRuntime from "./ManagedRuntime.js" + /** * The `effect/match` module provides a type-safe pattern matching system for * TypeScript. Inspired by functional programming, it simplifies conditional diff --git a/packages/effect/src/internal/core.ts b/packages/effect/src/internal/core.ts index 28185fcdea..a1224f759e 100644 --- a/packages/effect/src/internal/core.ts +++ b/packages/effect/src/internal/core.ts @@ -267,6 +267,9 @@ export const causeFromFailures = ( failures: ReadonlyArray> ): Cause.Cause => new CauseImpl(failures) +/** @internal */ +export const causeEmpty: Cause.Cause = new CauseImpl([]) + /** @internal */ export const causeFail = (error: E): Cause.Cause => new CauseImpl([new Fail(error)]) diff --git a/packages/effect/src/internal/effect.ts b/packages/effect/src/internal/effect.ts index 02b82433b7..741527d9ed 100644 --- a/packages/effect/src/internal/effect.ts +++ b/packages/effect/src/internal/effect.ts @@ -41,7 +41,7 @@ import type { Primitive } from "./core.js" import { args, causeAnnotate, - causeDie, + causeEmpty, causeFail, causeFromFailures, CauseImpl, @@ -49,6 +49,7 @@ import { contAll, contE, CurrentSpanKey, + Die, evaluate, exitDie, exitFail, @@ -416,11 +417,7 @@ const fiberIdStore = { id: 0 } const currentFiberUri = "effect/Fiber/currentFiber" /** @internal */ -export const getCurrentFiberOrUndefined = (): Fiber.Fiber | undefined => (globalThis as any)[currentFiberUri] - -/** @internal */ -export const getCurrentFiber = (): Option.Option> => - Option.fromNullable((globalThis as any)[currentFiberUri]) +export const getCurrentFiber = (): Fiber.Fiber | undefined => (globalThis as any)[currentFiberUri] const keepAlive = (() => { let count = 0 @@ -1081,7 +1078,10 @@ export const as: { ( self: Effect.Effect, value: B - ): Effect.Effect => map(self, (_) => value) + ): Effect.Effect => { + const b = succeed(value) + return flatMap(self, (_) => b) + } ) /** @internal */ @@ -2098,7 +2098,7 @@ export const forever: { ): Effect.Effect => whileLoop({ while: constTrue, - body: constant(options?.autoYield ? flatMap(self, () => yieldNow) : self), + body: constant(options?.autoYield ? flatMap(self, (_) => yieldNow) : self), step: constVoid }) as any) @@ -2811,10 +2811,16 @@ export const scopeTag: ServiceMap.Key = ServiceMap.Key const ScopeProto = { [ScopeTypeId]: ScopeTypeId, + state: { _tag: "Empty" }, close: fnUntraced(function*(this: Scope.Scope, exit_: Exit.Exit) { if (this.state._tag === "Closed") return + const closed: Scope.Scope.State.Closed = { _tag: "Closed", exit: exit_ } + if (this.state._tag === "Empty") { + this.state = closed + return + } const { finalizers } = this.state - this.state = { _tag: "Closed", exit: exit_ } + this.state = closed if (finalizers.size === 0) { return } else if (finalizers.size === 1) { @@ -2827,7 +2833,7 @@ const ScopeProto = { if (this.strategy === "sequential") { exits.push(yield* exit(finalizer(exit_))) } else { - fibers.push(unsafeFork(getCurrentFiberOrUndefined() as any, finalizer(exit_), true, true)) + fibers.push(unsafeFork(getCurrentFiber() as any, finalizer(exit_), true, true)) } } if (fibers.length > 0) { @@ -2849,7 +2855,7 @@ export const scopeUnsafeFork = (scope: Scope.Scope, finalizerStrategy?: "sequent return newScope } const key = {} - scope.state.finalizers.set(key, (exit) => newScope.close(exit)) + scopeUnsafeAddFinalizer(scope, key, (exit) => newScope.close(exit)) scopeUnsafeAddFinalizer(newScope, key, (_) => sync(() => scopeUnsafeRemoveFinalizer(scope, key))) return newScope } @@ -2860,11 +2866,11 @@ export const scopeAddFinalizerExit = ( finalizer: (exit: Exit.Exit) => Effect.Effect ): Effect.Effect => { return suspend(() => { - if (scope.state._tag === "Open") { - scope.state.finalizers.set({}, finalizer) - return void_ + if (scope.state._tag === "Closed") { + return finalizer(scope.state.exit) } - return finalizer(scope.state.exit) + scopeUnsafeAddFinalizer(scope, {}, finalizer) + return void_ }) } @@ -2880,7 +2886,9 @@ export const scopeUnsafeAddFinalizer = ( key: {}, finalizer: (exit: Exit.Exit) => Effect.Effect ): void => { - if (scope.state._tag === "Open") { + if (scope.state._tag === "Empty") { + scope.state = { _tag: "Open", finalizers: new Map([[key, finalizer]]) } + } else if (scope.state._tag === "Open") { scope.state.finalizers.set(key, finalizer) } } @@ -2899,7 +2907,6 @@ export const scopeUnsafeRemoveFinalizer = ( export const scopeUnsafeMake = (finalizerStrategy: "sequential" | "parallel" = "sequential"): Scope.Scope.Closeable => { const self = Object.create(ScopeProto) self.strategy = finalizerStrategy - self.state = { _tag: "Open", finalizers: new Map() } return self } @@ -2960,18 +2967,39 @@ export const onExit: { self: Effect.Effect, f: (exit: Exit.Exit) => Effect.Effect ): Effect.Effect +} = dual( + 2, + ( + self: Effect.Effect, + f: (exit: Exit.Exit) => Effect.Effect + ): Effect.Effect => uninterruptibleMask((restore) => onExitInterruptible(restore(self), f)) +) + +/** @internal */ +export const onExitInterruptible: { + ( + f: (exit: Exit.Exit) => Effect.Effect + ): (self: Effect.Effect) => Effect.Effect + ( + self: Effect.Effect, + f: (exit: Exit.Exit) => Effect.Effect + ): Effect.Effect } = dual( 2, ( self: Effect.Effect, f: (exit: Exit.Exit) => Effect.Effect ): Effect.Effect => - uninterruptibleMask((restore) => - matchCauseEffect(restore(self), { - onFailure: (cause) => flatMap(internalCall(() => f(exitFailCause(cause))), () => failCause(cause)), - onSuccess: (a) => flatMap(internalCall(() => f(exitSucceed(a))), () => succeed(a)) - }) - ) + matchCauseEffect(self, { + onFailure(cause) { + const exit = exitFailCause(cause) + return flatMap(f(exit), (_) => exit) + }, + onSuccess(a) { + const exit = exitSucceed(a) + return flatMap(f(exit), (_) => exit) + } + }) ) /** @internal */ @@ -3070,31 +3098,30 @@ export const acquireUseRelease = ( export const cachedInvalidateWithTTL: { (timeToLive: Duration.DurationInput): ( self: Effect.Effect - ) => Effect.Effect<[Effect.Effect, Effect.Effect], never, R> + ) => Effect.Effect<[Effect.Effect, Effect.Effect]> ( self: Effect.Effect, timeToLive: Duration.DurationInput - ): Effect.Effect<[Effect.Effect, Effect.Effect], never, R> + ): Effect.Effect<[Effect.Effect, Effect.Effect]> } = dual(2, ( self: Effect.Effect, ttl: Duration.DurationInput -): Effect.Effect<[Effect.Effect, Effect.Effect], never, R> => - withFiber((fiber) => { - const services = fiber.services as ServiceMap.ServiceMap +): Effect.Effect<[Effect.Effect, Effect.Effect]> => + sync(() => { const ttlMillis = Duration.toMillis(ttl) const latch = unsafeMakeLatch(false) let expiresAt = 0 let running = false let exit: Exit.Exit | undefined const wait = flatMap(latch.await, () => exit!) - return succeed([ + return [ withFiber((fiber) => { const now = fiber.getRef(ClockRef).unsafeCurrentTimeMillis() if (running || now < expiresAt) return exit ?? wait running = true latch.unsafeClose() exit = undefined - return onExit(provideServices(self, services), (exit_) => { + return onExit(self, (exit_) => { running = false expiresAt = now + ttlMillis exit = exit_ @@ -3106,28 +3133,28 @@ export const cachedInvalidateWithTTL: { latch.unsafeClose() exit = undefined }) - ]) + ] })) /** @internal */ export const cachedWithTTL: { ( timeToLive: Duration.DurationInput - ): (self: Effect.Effect) => Effect.Effect, never, R> + ): (self: Effect.Effect) => Effect.Effect> ( self: Effect.Effect, timeToLive: Duration.DurationInput - ): Effect.Effect, never, R> + ): Effect.Effect> } = dual( 2, ( self: Effect.Effect, timeToLive: Duration.DurationInput - ): Effect.Effect, never, R> => map(cachedInvalidateWithTTL(self, timeToLive), (tuple) => tuple[0]) + ): Effect.Effect> => map(cachedInvalidateWithTTL(self, timeToLive), (tuple) => tuple[0]) ) /** @internal */ -export const cached = (self: Effect.Effect): Effect.Effect, never, R> => +export const cached = (self: Effect.Effect): Effect.Effect> => cachedWithTTL(self, Duration.infinity) // ---------------------------------------------------------------------------- @@ -3382,7 +3409,7 @@ export const forEach: { } catch (err) { failed = true length = index - failures.push(causeDie(err).failures[0]) + failures.push(new Die(err)) fibers.forEach((fiber) => fiber.unsafeInterrupt(parent.id, span)) } } @@ -3643,7 +3670,7 @@ export const forkIn: { withFiber((parent) => { const fiber = unsafeFork(parent, self, options?.startImmediately, true, options?.uninterruptible) if (!(fiber as FiberImpl)._exit) { - if (scope.state._tag === "Open") { + if (scope.state._tag !== "Closed") { const key = {} const finalizer = () => withFiberId((interruptor) => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)) scopeUnsafeAddFinalizer(scope, key, finalizer) @@ -3693,6 +3720,8 @@ export const runForkWith = (services: ServiceMap.ServiceMap) => serviceMap.set(Scheduler.Scheduler.key, options?.scheduler ?? new Scheduler.MixedScheduler()) const fiber = makeFiber(ServiceMap.unsafeMake(serviceMap)) fiber.evaluate(effect as any) + if (fiber._exit) return fiber + if (options?.signal) { if (options.signal.aborted) { fiber.unsafeInterrupt() @@ -3705,6 +3734,27 @@ export const runForkWith = (services: ServiceMap.ServiceMap) => return fiber } +/** @internal */ +export const fiberRunIn: { + (scope: Scope.Scope): (self: Fiber.Fiber) => Fiber.Fiber + ( + self: Fiber.Fiber, + scope: Scope.Scope + ): Fiber.Fiber +} = dual(2, ( + self: FiberImpl, + scope: Scope.Scope +): Fiber.Fiber => { + if (scope.state._tag === "Closed") { + self.unsafeInterrupt(self.id) + return self + } + const key = {} + scopeUnsafeAddFinalizer(scope, {}, () => fiberInterrupt(self)) + self.addObserver(() => scopeUnsafeRemoveFinalizer(scope, key)) + return self +}) + /** @internal */ export const runFork: ( effect: Effect.Effect, @@ -4500,7 +4550,7 @@ export const logWithLevel = (level?: LogLevel.LogLevel) => } } if (cause === undefined) { - cause = causeFromFailures([]) + cause = causeEmpty } return withFiber((fiber) => { const logLevel = level ?? fiber.getRef(CurrentLogLevel) diff --git a/packages/effect/src/internal/request.ts b/packages/effect/src/internal/request.ts index 30100acf82..95b3be9729 100644 --- a/packages/effect/src/internal/request.ts +++ b/packages/effect/src/internal/request.ts @@ -41,7 +41,7 @@ export const request: { Request.Error, Request.Services >((resume) => { - const entry = addEntry(resolver, self, resume, effect.getCurrentFiberOrUndefined()!) + const entry = addEntry(resolver, self, resume, effect.getCurrentFiber()!) return maybeRemoveEntry(resolver, entry) }) return isEffect(resolver) ? effect.flatMap(resolver, withResolver) : withResolver(resolver) diff --git a/packages/effect/src/unstable/http/Etag.ts b/packages/effect/src/unstable/http/Etag.ts new file mode 100644 index 0000000000..ad48973e75 --- /dev/null +++ b/packages/effect/src/unstable/http/Etag.ts @@ -0,0 +1,97 @@ +/** + * @since 4.0.0 + */ +import * as Effect from "../../Effect.js" +import type * as FileSystem from "../../FileSystem.js" +import * as Layer from "../../Layer.js" +import * as ServiceMap from "../../ServiceMap.js" +import type * as Body from "./HttpBody.js" + +/** + * @since 4.0.0 + * @category models + */ +export type Etag = Weak | Strong + +/** + * @since 4.0.0 + * @category models + */ +export interface Weak { + readonly _tag: "Weak" + readonly value: string +} + +/** + * @since 4.0.0 + * @category models + */ +export interface Strong { + readonly _tag: "Strong" + readonly value: string +} + +/** + * @since 4.0.0 + * @category convertions + */ +export const toString = (self: Etag): string => { + switch (self._tag) { + case "Weak": + return `W/"${self.value}"` + case "Strong": + return `"${self.value}"` + } +} + +/** + * @since 4.0.0 + * @category models + */ +export class Generator extends ServiceMap.Key Effect.Effect + readonly fromFileWeb: (file: Body.HttpBody.FileLike) => Effect.Effect +}>()("effect/http/Etag/Generator") {} + +const fromFileInfo = (info: FileSystem.File.Info) => { + const mtime = info.mtime._tag === "Some" + ? info.mtime.value.getTime().toString(16) + : "0" + return `${info.size.toString(16)}-${mtime}` +} + +const fromFileWeb = (file: Body.HttpBody.FileLike) => { + return `${file.size.toString(16)}-${file.lastModified.toString(16)}` +} + +/** + * @since 4.0.0 + * @category Layers + */ +export const layer: Layer.Layer = Layer.succeed( + Generator, + Generator.of({ + fromFileInfo(info) { + return Effect.sync(() => ({ _tag: "Strong", value: fromFileInfo(info) })) + }, + fromFileWeb(file) { + return Effect.sync(() => ({ _tag: "Strong", value: fromFileWeb(file) })) + } + }) +) + +/** + * @since 4.0.0 + * @category Layers + */ +export const layerWeak: Layer.Layer = Layer.succeed( + Generator, + Generator.of({ + fromFileInfo(info) { + return Effect.sync(() => ({ _tag: "Weak", value: fromFileInfo(info) })) + }, + fromFileWeb(file) { + return Effect.sync(() => ({ _tag: "Weak", value: fromFileWeb(file) })) + } + }) +) diff --git a/packages/effect/src/unstable/http/FindMyWay.ts b/packages/effect/src/unstable/http/FindMyWay.ts new file mode 100644 index 0000000000..7f1a8d746f --- /dev/null +++ b/packages/effect/src/unstable/http/FindMyWay.ts @@ -0,0 +1,9 @@ +/** + * @since 4.0.0 + */ + +/** + * @since 4.0.0 + * @category re-exports + */ +export * from "find-my-way-ts" diff --git a/packages/effect/src/unstable/http/Headers.ts b/packages/effect/src/unstable/http/Headers.ts index 8abf00cb9a..fbcff2b22d 100644 --- a/packages/effect/src/unstable/http/Headers.ts +++ b/packages/effect/src/unstable/http/Headers.ts @@ -20,6 +20,7 @@ import type { Mutable } from "../../Types.js" * @since 4.0.0 * @category type ids */ +// note: this is a symbol to allow direct access of keys without conflicts export const TypeId: unique symbol = Symbol.for("effect/http/Headers") /** diff --git a/packages/effect/src/unstable/http/HttpEffect.ts b/packages/effect/src/unstable/http/HttpEffect.ts new file mode 100644 index 0000000000..eb8f87954a --- /dev/null +++ b/packages/effect/src/unstable/http/HttpEffect.ts @@ -0,0 +1,267 @@ +/** + * @since 4.0.0 + */ +import * as Effect from "../../Effect.js" +import * as Exit from "../../Exit.js" +import * as Fiber from "../../Fiber.js" +import { dual } from "../../Function.js" +import * as Layer from "../../Layer.js" +import * as Option from "../../Option.js" +import * as Scope from "../../Scope.js" +import * as ServiceMap from "../../ServiceMap.js" +import * as Stream from "../../Stream.js" +import * as HttpBody from "./HttpBody.js" +import { type HttpMiddleware, tracer } from "./HttpMiddleware.js" +import type { HttpServerError } from "./HttpServerError.js" +import { causeResponse, clientAbortFiberId } from "./HttpServerError.js" +import { HttpServerRequest } from "./HttpServerRequest.js" +import * as Request from "./HttpServerRequest.js" +import type { HttpServerResponse } from "./HttpServerResponse.js" +import * as Response from "./HttpServerResponse.js" + +/** + * @since 4.0.0 + * @category combinators + */ +export const toHandled = ( + self: Effect.Effect, + handleResponse: ( + request: HttpServerRequest, + response: HttpServerResponse + ) => Effect.Effect, + middleware?: HttpMiddleware | undefined +): Effect.Effect> => { + const responded = Effect.flatMap(self, (response) => { + const fiber = Fiber.getCurrent()! + const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest) + const handler = fiber.getRef(PreResponseHandlers) + if (handler._tag === "None") { + ;(request as any)[handledSymbol] = true + return Effect.as(handleResponse(request, response), response) + } + return Effect.tap(handler.value(request, response), (response) => { + ;(request as any)[handledSymbol] = true + return handleResponse(request, response) + }) + }) + + const withErrorHandling = Effect.catchCause( + responded, + (cause) => + Effect.flatMap(causeResponse(cause), ([response, cause]) => { + const fiber = Fiber.getCurrent()! + const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest) + const handler = fiber.getRef(PreResponseHandlers) + if (handler._tag === "None") { + ;(request as any)[handledSymbol] = true + return Effect.flatMap(handleResponse(request, response), () => Effect.failCause(cause)) + } + return Effect.flatMap( + Effect.flatMap(handler.value(request, response), (response) => { + ;(request as any)[handledSymbol] = true + return handleResponse(request, response) + }), + () => Effect.failCause(cause) + ) + }) + ) + + const withMiddleware: Effect.Effect< + unknown, + E | EH | HttpServerError, + HttpServerRequest | R | RH + > = middleware === undefined ? + tracer(withErrorHandling) : + Effect.matchCauseEffect(middleware(tracer(withErrorHandling)), { + onFailure: (cause): Effect.Effect => { + const fiber = Fiber.getCurrent()! + const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest) + if (handledSymbol in request) { + return Effect.void + } + return Effect.matchCauseEffect(causeResponse(cause), { + onFailure: (_cause) => handleResponse(request, Response.empty({ status: 500 })), + onSuccess: ([response]) => handleResponse(request, response) + }) + }, + onSuccess: (response): Effect.Effect => { + const fiber = Fiber.getCurrent()! + const request = ServiceMap.unsafeGet(fiber.services, Request.HttpServerRequest) + return handledSymbol in request ? Effect.void : handleResponse(request, response) + } + }) + + return Effect.uninterruptible(scoped(withMiddleware)) as any +} + +const handledSymbol = Symbol.for("effect/http/HttpEffect/handled") + +/** + * If you want to finalize the http request scope elsewhere, you can use this + * function to eject from the default scope closure. + * + * @since 4.0.0 + * @category Scope + */ +export const scopeDisableClose = (scope: Scope.Scope): void => { + ejectedScopes.add(scope) +} + +/** + * @since 4.0.0 + * @category Scope + */ +export const scopeTransferToStream = ( + response: HttpServerResponse +): HttpServerResponse => { + if (response.body._tag !== "Stream") { + return response + } + const fiber = Fiber.getCurrent()! + const scope = ServiceMap.unsafeGet(fiber.services, Scope.Scope) as Scope.Scope.Closeable + scopeDisableClose(scope) + return Response.setBody( + response, + HttpBody.stream( + Stream.onExit(response.body.stream, (exit) => Scope.close(scope, exit)), + response.body.contentType, + response.body.contentLength + ) + ) +} + +const ejectedScopes = new WeakSet() + +const scoped = (effect: Effect.Effect) => + Effect.flatMap(Scope.make(), (scope) => + Effect.onExitInterruptible(Scope.provide(effect, scope), (exit) => { + if (ejectedScopes.has(scope)) { + return Effect.void + } + return Scope.close(scope, exit) + })) + +/** + * @since 4.0.0 + * @category Pre-response handlers + */ +export type PreResponseHandler = ( + request: HttpServerRequest, + response: HttpServerResponse +) => Effect.Effect + +/** + * @since 4.0.0 + * @category Pre-response handlers + */ +export const PreResponseHandlers = ServiceMap.Reference>( + "effect/http/HttpEffect/PreResponseHandlers", + { defaultValue: Option.none } +) + +/** + * @since 4.0.0 + * @category fiber refs + */ +export const appendPreResponseHandler = (handler: PreResponseHandler): Effect.Effect => + Effect.withFiber((fiber) => { + const o = Option.match(fiber.getRef(PreResponseHandlers), { + onNone: () => Option.some(handler), + onSome: (prev) => + Option.some((request, response) => + Effect.flatMap(prev(request, response), (response) => handler(request, response)) + ) + }) + fiber.setServices(ServiceMap.add(fiber.services, PreResponseHandlers, o)) + return Effect.void + }) + +/** + * @since 4.0.0 + * @category fiber refs + */ +export const withPreResponseHandler: { + (handler: PreResponseHandler): (self: Effect.Effect) => Effect.Effect + (self: Effect.Effect, handler: PreResponseHandler): Effect.Effect +} = dual< + (handler: PreResponseHandler) => (self: Effect.Effect) => Effect.Effect, + (self: Effect.Effect, handler: PreResponseHandler) => Effect.Effect +>(2, (self, handler) => + Effect.updateService( + self, + PreResponseHandlers, + Option.match({ + onNone: () => Option.some(handler), + onSome: (prev) => + Option.some((request, response) => + Effect.flatMap(prev(request, response), (response) => handler(request, response)) + ) + }) + )) + +/** + * @since 4.0.0 + * @category conversions + */ +export const toWebHandlerWith = (services: ServiceMap.ServiceMap) => { + return ( + self: Effect.Effect, + middleware?: HttpMiddleware | undefined + ): (request: Request, services?: ServiceMap.ServiceMap | undefined) => Promise => { + const resolveSymbol = Symbol.for("@effect/platform/HttpApp/resolve") + const httpApp = toHandled(self, (request, response) => { + response = scopeTransferToStream(response) + ;(request as any)[resolveSymbol]( + Response.toWeb(response, { withoutBody: request.method === "HEAD", services }) + ) + return Effect.void + }, middleware) + return (request: Request, reqServices?: ServiceMap.ServiceMap | undefined): Promise => + new Promise((resolve) => { + const contextMap = new Map(services.unsafeMap) + if (ServiceMap.isServiceMap(reqServices)) { + for (const [key, value] of reqServices.unsafeMap) { + contextMap.set(key, value) + } + } + const httpServerRequest = Request.fromWeb(request) + contextMap.set(HttpServerRequest.key, httpServerRequest) + ;(httpServerRequest as any)[resolveSymbol] = resolve + const fiber = Effect.runForkWith(ServiceMap.unsafeMake(contextMap))(httpApp as any) + request.signal?.addEventListener("abort", () => { + fiber.unsafeInterrupt(clientAbortFiberId) + }, { once: true }) + }) + } +} + +/** + * @since 4.0.0 + * @category conversions + */ +export const toWebHandler: ( + self: Effect.Effect, + middleware?: HttpMiddleware | undefined +) => (request: Request, services?: ServiceMap.ServiceMap | undefined) => Promise = + toWebHandlerWith(ServiceMap.empty()) + +/** + * @since 4.0.0 + * @category conversions + */ +export const toWebHandlerLayer = ( + self: Effect.Effect, + layer: Layer.Layer, + middleware?: HttpMiddleware | undefined +): { + readonly close: () => Promise + readonly handler: (request: Request, context?: ServiceMap.ServiceMap | undefined) => Promise +} => { + const scope = Effect.runSync(Scope.make()) + const close = () => Effect.runPromise(Scope.close(scope, Exit.void)) + const build = Effect.map(Layer.build(layer), (_) => toWebHandlerWith(_)(self, middleware)) + const runner = Effect.runPromise(Scope.provide(build, scope)) + const handler = (request: Request, context?: ServiceMap.ServiceMap | undefined): Promise => + runner.then((handler) => handler(request, context)) + return { close, handler } as const +} diff --git a/packages/effect/src/unstable/http/HttpMiddleware.ts b/packages/effect/src/unstable/http/HttpMiddleware.ts new file mode 100644 index 0000000000..6ab7ead128 --- /dev/null +++ b/packages/effect/src/unstable/http/HttpMiddleware.ts @@ -0,0 +1,360 @@ +/** + * @since 4.0.0 + */ +import * as Effect from "effect/Effect" +import { constFalse } from "../../Function.js" +import * as Layer from "../../Layer.js" +import * as Option from "../../Option.js" +import type { Predicate } from "../../Predicate.js" +import type { ReadonlyRecord } from "../../Record.js" +import * as ServiceMap from "../../ServiceMap.js" +import * as Headers from "./Headers.js" +import type { PreResponseHandler } from "./HttpEffect.js" +import { causeResponseStripped, exitResponse } from "./HttpServerError.js" +import { HttpServerRequest } from "./HttpServerRequest.js" +import * as Request from "./HttpServerRequest.js" +import * as Response from "./HttpServerResponse.js" +import type { HttpServerResponse } from "./HttpServerResponse.js" +import * as TraceContext from "./HttpTraceContext.js" + +/** + * @since 4.0.0 + * @category models + */ +export interface HttpMiddleware { + (self: Effect.Effect): Effect.Effect +} + +/** + * @since 4.0.0 + */ +export declare namespace HttpMiddleware { + /** + * @since 4.0.0 + */ + export interface Applied, E, R> { + (self: Effect.Effect): A + } +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const make = (middleware: M): M => middleware + +/** + * @since 4.0.0 + * @category Logger + */ +export const LoggerDisabled = ServiceMap.Reference("effect/http/HttpMiddleware/LoggerDisabled", { + defaultValue: constFalse +}) + +/** + * @since 4.0.0 + * @category Logger + */ +export const withLoggerDisabled = (self: Effect.Effect): Effect.Effect => + Effect.withFiber((fiber) => { + fiber.setServices(ServiceMap.add(fiber.services, LoggerDisabled, true)) + return self + }) + +/** + * @since 4.0.0 + * @category Tracer + */ +export const TracerDisabledWhen = ServiceMap.Reference>( + "effect/http/HttpMiddleware/TracerDisabledWhen", + { defaultValue: () => constFalse } +) + +/** + * @since 4.0.0 + * @category Tracer + */ +export const layerTracerDisabledForUrls = ( + urls: ReadonlyArray +): Layer.Layer => Layer.succeed(TracerDisabledWhen, (req) => urls.includes(req.url)) + +/** + * @since 4.0.0 + * @category Tracer + */ +export const SpanNameGenerator = ServiceMap.Reference<(request: HttpServerRequest) => string>( + "@effect/platform/HttpMiddleware/SpanNameGenerator", + { defaultValue: () => (request) => `http.server ${request.method}` } +) + +/** + * @since 4.0.0 + * @category Logger + */ +export const logger: ( + httpApp: Effect.Effect +) => Effect.Effect = make((httpApp) => { + let counter = 0 + return Effect.withFiber((fiber) => { + const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest) + return Effect.withLogSpan( + Effect.flatMap(Effect.exit(httpApp), (exit) => { + if (fiber.getRef(LoggerDisabled)) { + return exit + } else if (exit._tag === "Failure") { + const [response, cause] = causeResponseStripped(exit.cause) + return Effect.andThen( + Effect.annotateLogs(Effect.log(cause._tag === "Some" ? cause.value : "Sent HTTP Response"), { + "http.method": request.method, + "http.url": request.url, + "http.status": response.status + }), + exit + ) + } + return Effect.andThen( + Effect.annotateLogs(Effect.log("Sent HTTP response"), { + "http.method": request.method, + "http.url": request.url, + "http.status": exit.value.status + }), + exit + ) + }), + `http.span.${++counter}` + ) + }) +}) + +/** + * @since 4.0.0 + * @category Tracer + */ +export const tracer: ( + httpApp: Effect.Effect +) => Effect.Effect = make((httpApp) => + Effect.withFiber((fiber) => { + const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest) + const disabled = fiber.getRef(TracerDisabledWhen)(request) + if (disabled) { + return httpApp + } + const url = Option.getOrUndefined(Request.toURL(request)) + if (url !== undefined && (url.username !== "" || url.password !== "")) { + url.username = "REDACTED" + url.password = "REDACTED" + } + const redactedHeaderNames = fiber.getRef(Headers.CurrentRedactedNames) + const redactedHeaders = Headers.redact(request.headers, redactedHeaderNames) + const nameGenerator = fiber.getRef(SpanNameGenerator) + return Effect.useSpan( + nameGenerator(request), + { + parent: Option.getOrUndefined(TraceContext.fromHeaders(request.headers)), + kind: "server", + captureStackTrace: false + }, + (span) => { + span.attribute("http.request.method", request.method) + if (url !== undefined) { + span.attribute("url.full", url.toString()) + span.attribute("url.path", url.pathname) + const query = url.search.slice(1) + if (query !== "") { + span.attribute("url.query", url.search.slice(1)) + } + span.attribute("url.scheme", url.protocol.slice(0, -1)) + } + if (request.headers["user-agent"] !== undefined) { + span.attribute("user_agent.original", request.headers["user-agent"]) + } + for (const name in redactedHeaders) { + span.attribute(`http.request.header.${name}`, String(redactedHeaders[name])) + } + if (request.remoteAddress._tag === "Some") { + span.attribute("client.address", request.remoteAddress.value) + } + return Effect.onExitInterruptible(Effect.withParentSpan(httpApp, span), (exit) => { + const response = exitResponse(exit) + span.attribute("http.response.status_code", response.status) + const redactedHeaders = Headers.redact(response.headers, redactedHeaderNames) + for (const name in redactedHeaders) { + span.attribute(`http.response.header.${name}`, String(redactedHeaders[name])) + } + return Effect.void + }) + } + ) + }) +) + +/** + * @since 4.0.0 + * @category Proxying + */ +export const xForwardedHeaders = make((httpApp) => + Effect.updateService(httpApp, HttpServerRequest, (request) => + request.headers["x-forwarded-host"] + ? request.modify({ + headers: Headers.set( + request.headers, + "host", + request.headers["x-forwarded-host"] + ), + remoteAddress: request.headers["x-forwarded-for"]?.split(",")[0].trim() + }) + : request) +) + +/** + * @since 4.0.0 + * @category Search params + */ +export const searchParamsParser = ( + httpApp: Effect.Effect +): Effect.Effect> => + Effect.withFiber((fiber) => { + const services = fiber.services + const request = ServiceMap.unsafeGet(services, HttpServerRequest) + const params = Request.searchParamsFromURL(new URL(request.originalUrl)) + return Effect.provideService( + httpApp, + Request.ParsedSearchParams, + params + ) as any + }) + +/** + * @since 4.0.0 + * @category CORS + */ +export const cors = (options?: { + readonly allowedOrigins?: ReadonlyArray | undefined + readonly allowedMethods?: ReadonlyArray | undefined + readonly allowedHeaders?: ReadonlyArray | undefined + readonly exposedHeaders?: ReadonlyArray | undefined + readonly maxAge?: number | undefined + readonly credentials?: boolean | undefined +}): ( + httpApp: Effect.Effect +) => Effect.Effect => { + const opts = { + allowedOrigins: options?.allowedOrigins ?? ["*"], + allowedMethods: options?.allowedMethods ?? ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"], + allowedHeaders: options?.allowedHeaders ?? [], + exposedHeaders: options?.exposedHeaders ?? [], + credentials: options?.credentials ?? false, + maxAge: options?.maxAge + } + + const isAllowedOrigin = (origin: string) => opts.allowedOrigins.includes(origin) + + const allowOrigin = (originHeader: string): ReadonlyRecord | undefined => { + if (opts.allowedOrigins.length === 0) { + return { "access-control-allow-origin": "*" } + } + + if (opts.allowedOrigins.length === 1) { + return { + "access-control-allow-origin": opts.allowedOrigins[0], + vary: "Origin" + } + } + + if (isAllowedOrigin(originHeader)) { + return { + "access-control-allow-origin": originHeader, + vary: "Origin" + } + } + + return undefined + } + + const allowMethods = opts.allowedMethods.length > 0 + ? { "access-control-allow-methods": opts.allowedMethods.join(", ") } + : undefined + + const allowCredentials = opts.credentials + ? { "access-control-allow-credentials": "true" } + : undefined + + const allowHeaders = ( + accessControlRequestHeaders: string | undefined + ): ReadonlyRecord | undefined => { + if (opts.allowedHeaders.length === 0 && accessControlRequestHeaders) { + return { + vary: "Access-Control-Request-Headers", + "access-control-allow-headers": accessControlRequestHeaders + } + } + + if (opts.allowedHeaders) { + return { + "access-control-allow-headers": opts.allowedHeaders.join(",") + } + } + + return undefined + } + + const exposeHeaders = opts.exposedHeaders.length > 0 + ? { "access-control-expose-headers": opts.exposedHeaders.join(",") } + : undefined + + const maxAge = opts.maxAge + ? { "access-control-max-age": opts.maxAge.toString() } + : undefined + + const headersFromRequest = (request: HttpServerRequest) => { + const origin = request.headers["origin"] + return Headers.unsafeFromRecord({ + ...allowOrigin(origin), + ...allowCredentials, + ...exposeHeaders + }) + } + + const headersFromRequestOptions = (request: HttpServerRequest) => { + const origin = request.headers["origin"] + const accessControlRequestHeaders = request.headers["access-control-request-headers"] + return Headers.unsafeFromRecord({ + ...allowOrigin(origin), + ...allowCredentials, + ...exposeHeaders, + ...allowMethods, + ...allowHeaders(accessControlRequestHeaders), + ...maxAge + }) + } + + const preResponseHandler = (request: HttpServerRequest, response: HttpServerResponse) => + Effect.succeed(Response.setHeaders(response, headersFromRequest(request))) + + return ( + httpApp: Effect.Effect + ): Effect.Effect => + Effect.withFiber((fiber) => { + const request = ServiceMap.unsafeGet(fiber.services, HttpServerRequest) + if (request.method === "OPTIONS") { + return Effect.succeed(Response.empty({ + status: 204, + headers: headersFromRequestOptions(request) + })) + } + const o = Option.match(fiber.getRef(PreResponseHandlers), { + onNone: () => Option.some(preResponseHandler), + onSome: (prev) => + Option.some((request, response) => + Effect.flatMap(prev(request, response), (response) => preResponseHandler(request, response)) + ) + }) + fiber.setServices(ServiceMap.add(fiber.services, PreResponseHandlers, o)) + return httpApp + }) +} + +const PreResponseHandlers = ServiceMap.Reference>( + "effect/http/HttpEffect/PreResponseHandlers", + { defaultValue: Option.none } +) diff --git a/packages/effect/src/unstable/http/HttpPlatform.ts b/packages/effect/src/unstable/http/HttpPlatform.ts new file mode 100644 index 0000000000..db2bfe93e6 --- /dev/null +++ b/packages/effect/src/unstable/http/HttpPlatform.ts @@ -0,0 +1,145 @@ +/** + * @since 4.0.0 + */ +import * as Effect from "../../Effect.js" +import * as FileSystem from "../../FileSystem.js" +import { identity } from "../../Function.js" +import * as Layer from "../../Layer.js" +import type { PlatformError } from "../../PlatformError.js" +import * as ServiceMap from "../../ServiceMap.js" +import * as Stream from "../../Stream.js" +import * as Etag from "./Etag.js" +import * as Headers from "./Headers.js" +import type * as Body from "./HttpBody.js" +import * as Response from "./HttpServerResponse.js" + +/** + * @since 4.0.0 + * @category type ids + */ +export const TypeId: TypeId = "~effect/http/HttpPlatform" + +/** + * @since 4.0.0 + * @category type ids + */ +export type TypeId = "~effect/http/HttpPlatform" + +/** + * @since 4.0.0 + * @category tags + */ +export class HttpPlatform extends ServiceMap.Key Effect.Effect + readonly fileWebResponse: ( + file: Body.HttpBody.FileLike, + options?: Response.Options.WithContent & FileSystem.StreamOptions + ) => Effect.Effect +}>()("effect/http/HttpPlatform") {} + +/** + * @since 4.0.0 + * @category constructors + */ +export const make: (impl: { + readonly fileResponse: ( + path: string, + status: number, + statusText: string | undefined, + headers: Headers.Headers, + start: number, + end: number | undefined, + contentLength: number + ) => Response.HttpServerResponse + readonly fileWebResponse: ( + file: Body.HttpBody.FileLike, + status: number, + statusText: string | undefined, + headers: Headers.Headers, + options?: FileSystem.StreamOptions + ) => Response.HttpServerResponse +}) => Effect.Effect< + HttpPlatform["Service"], + never, + Etag.Generator | FileSystem.FileSystem +> = Effect.fnUntraced(function*(impl) { + const fs = yield* FileSystem.FileSystem + const etagGen = yield* Etag.Generator + + return HttpPlatform.of({ + fileResponse: Effect.fnUntraced(function*(path, options) { + const info = yield* fs.stat(path) + const etag = yield* etagGen.fromFileInfo(info) + const start = Number(options?.offset ?? 0) + const end = options?.bytesToRead !== undefined ? start + Number(options.bytesToRead) : undefined + const headers = Headers.set( + options?.headers ? Headers.fromInput(options.headers) : Headers.empty, + "etag", + Etag.toString(etag) + ) + if (info.mtime._tag === "Some") { + ;(headers as any)["last-modified"] = info.mtime.value.toUTCString() + } + const contentLength = end !== undefined ? end - start : Number(info.size) - start + return impl.fileResponse( + path, + options?.status ?? 200, + options?.statusText, + headers, + start, + end, + contentLength + ) + }), + fileWebResponse(file, options) { + return Effect.map(etagGen.fromFileWeb(file), (etag) => { + const headers = Headers.merge( + options?.headers ? Headers.fromInput(options.headers) : Headers.empty, + Headers.unsafeFromRecord({ + etag: Etag.toString(etag), + "last-modified": new Date(file.lastModified).toUTCString() + }) + ) + return impl.fileWebResponse( + file, + options?.status ?? 200, + options?.statusText, + headers, + options + ) + }) + } + }) +}) + +/** + * @since 4.0.0 + * @category layers + */ +export const layer = Layer.effect( + HttpPlatform, + Effect.flatMap(FileSystem.FileSystem.asEffect(), (fs) => + make({ + fileResponse(path, status, statusText, headers, start, end, contentLength) { + return Response.stream( + fs.stream(path, { + offset: start, + bytesToRead: end !== undefined ? end - start : undefined + }), + { contentLength, headers, status, statusText } + ) + }, + fileWebResponse(file, status, statusText, headers, _options) { + return Response.stream( + Stream.fromReadableStream({ + evaluate: () => file.stream() as ReadableStream, + onError: identity + }), + { headers, status, statusText } + ) + } + })) +).pipe(Layer.provide(Etag.layerWeak)) diff --git a/packages/effect/src/unstable/http/HttpRouter.ts b/packages/effect/src/unstable/http/HttpRouter.ts new file mode 100644 index 0000000000..1fd8e5b292 --- /dev/null +++ b/packages/effect/src/unstable/http/HttpRouter.ts @@ -0,0 +1,1033 @@ +/** + * @since 4.0.0 + */ +import * as Arr from "../../Array.js" +import * as Effect from "../../Effect.js" +import { compose, dual, identity } from "../../Function.js" +import * as Layer from "../../Layer.js" +import * as ManagedRuntime from "../../ManagedRuntime.js" +import * as Option from "../../Option.js" +import * as Scope from "../../Scope.js" +import * as ServiceMap from "../../ServiceMap.js" +import * as Tracer from "../../Tracer.js" +import type * as Types from "../../Types.js" +import * as FindMyWay from "./FindMyWay.js" +import * as HttpEffect from "./HttpEffect.js" +import type * as HttpMethod from "./HttpMethod.js" +import * as HttpMiddleware from "./HttpMiddleware.js" +import * as HttpServer from "./HttpServer.js" +import * as HttpServerError from "./HttpServerError.js" +import * as HttpServerRequest from "./HttpServerRequest.js" +import type * as HttpServerResponse from "./HttpServerResponse.js" + +/** + * @since 4.0.0 + * @category HttpRouter + */ +export const TypeId: TypeId = "~effect/http/HttpRouter" + +/** + * @since 4.0.0 + * @category HttpRouter + */ +export type TypeId = "~effect/http/HttpRouter" + +/** + * @since 4.0.0 + * @category HttpRouter + */ +export interface HttpRouter { + readonly [TypeId]: TypeId + + readonly prefixed: (prefix: string) => HttpRouter + + readonly add: ( + method: "*" | "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS", + path: PathInput, + handler: + | Effect.Effect + | ((request: HttpServerRequest.HttpServerRequest) => Effect.Effect), + options?: { readonly uninterruptible?: boolean | undefined } | undefined + ) => Effect.Effect< + void, + never, + Request.From<"Requires", Exclude> | Request.From<"Error", E> + > + + readonly addAll: >>( + routes: Routes + ) => Effect.Effect< + void, + never, + | Request.From<"Requires", Exclude, Provided>> + | Request.From<"Error", Route.Error> + > + + readonly addGlobalMiddleware: ( + middleware: + & (( + effect: Effect.Effect + ) => Effect.Effect) + & (unhandled extends E ? unknown : "You cannot handle any errors") + ) => Effect.Effect< + void, + never, + | Request.From<"GlobalRequires", Exclude> + | Request.From<"GlobalError", Exclude> + > + + readonly asHttpEffect: () => Effect.Effect< + HttpServerResponse.HttpServerResponse, + unknown, + HttpServerRequest.HttpServerRequest | Scope.Scope + > +} + +/** + * @since 4.0.0 + * @category HttpRouter + */ +export const HttpRouter: ServiceMap.Key = ServiceMap.Key("effect/http/HttpRouter") + +/** + * @since 4.0.0 + * @category HttpRouter + */ +export const make = Effect.gen(function*() { + const router = FindMyWay.make>(yield* RouterConfig) + const middleware = new Set() + + const addAll = >>( + routes: Routes + ): Effect.Effect< + void, + never, + | Request.From<"Requires", Exclude, Provided>> + | Request.From<"Error", Route.Error> + > => + Effect.servicesWith((services: ServiceMap.ServiceMap) => { + const middleware = getMiddleware(services) + const applyMiddleware = (effect: Effect.Effect) => { + for (let i = 0; i < middleware.length; i++) { + effect = middleware[i](effect) + } + return effect + } + for (let i = 0; i < routes.length; i++) { + const route = middleware.length === 0 ? routes[i] : makeRoute({ + ...routes[i], + handler: applyMiddleware(routes[i].handler as Effect.Effect) + }) + if (route.method === "*") { + router.all(route.path, route as any) + } else { + router.on(route.method, route.path, route as any) + } + } + return Effect.void + }) + + return HttpRouter.of({ + [TypeId]: TypeId, + prefixed(this: HttpRouter, prefix: string) { + return HttpRouter.of({ + ...this, + prefixed: (newPrefix: string) => this.prefixed(prefixPath(prefix, newPrefix)), + addAll: (routes) => addAll(routes.map(prefixRoute(prefix))) as any, + add: (method, path, handler, options) => + addAll([ + makeRoute({ + method, + path: prefixPath(path, prefix) as PathInput, + handler: Effect.isEffect(handler) + ? handler + : Effect.flatMap(HttpServerRequest.HttpServerRequest.asEffect(), handler), + uninterruptible: options?.uninterruptible ?? false, + prefix: Option.some(prefix) + }) + ]) + }) + }, + addAll, + add: (method, path, handler, options) => addAll([route(method, path, handler, options)]), + addGlobalMiddleware: (middleware_) => + Effect.sync(() => { + middleware.add(middleware_ as any) + }), + asHttpEffect() { + let handler = Effect.withFiber((fiber) => { + const contextMap = new Map(fiber.services.unsafeMap) + const request = contextMap.get(HttpServerRequest.HttpServerRequest.key) as HttpServerRequest.HttpServerRequest + let result = router.find(request.method, request.url) + if (result === undefined && request.method === "HEAD") { + result = router.find("GET", request.url) + } + if (result === undefined) { + return Effect.fail(new HttpServerError.RequestError({ reason: "RouteNotFound", request })) + } + const route = result.handler + if (route.prefix._tag === "Some") { + contextMap.set(HttpServerRequest.HttpServerRequest.key, sliceRequestUrl(request, route.prefix.value)) + } + contextMap.set(HttpServerRequest.ParsedSearchParams.key, result.searchParams) + contextMap.set(RouteContext.key, { + route, + params: result.params + }) + + const span = contextMap.get(Tracer.ParentSpan.key) as Tracer.Span | undefined + if (span && span._tag === "Span") { + span.attribute("http.route", route.path) + } + return Effect.provideServices( + (route.uninterruptible ? + route.handler : + Effect.interruptible(route.handler)) as Effect.Effect< + HttpServerResponse.HttpServerResponse, + unknown + >, + ServiceMap.unsafeMake(contextMap) + ) + }) + if (middleware.size === 0) return handler + for (const fn of Arr.reverse(middleware)) { + handler = fn(handler as any) + } + return handler + } + }) +}) + +function sliceRequestUrl(request: HttpServerRequest.HttpServerRequest, prefix: string) { + const prefexLen = prefix.length + return request.modify({ url: request.url.length <= prefexLen ? "/" : request.url.slice(prefexLen) }) +} + +/** + * @since 4.0.0 + * @category Configuration + */ +export const RouterConfig = ServiceMap.Reference>( + "effect/http/HttpRouter/RouterConfig", + { defaultValue: () => ({}) } +) + +/** + * @since 4.0.0 + * @category RouteContext + */ +export class RouteContext extends ServiceMap.Key> + readonly route: Route +}>()("effect/http/HttpRouter/RouteContext") {} + +/** + * A helper function that is the equivalent of: + * + * ```ts + * import * as HttpRouter from "effect/unstable/http/HttpRouter" + * import * as Effect from "effect/Effect" + * import * as Layer from "effect/Layer" + * + * const MyRoute = Layer.effectDiscard(Effect.gen(function*() { + * const router = yield* HttpRouter.HttpRouter + * + * // then use `yield* router.add(...)` to add a route + * })) + * ``` + * + * @since 4.0.0 + * @category HttpRouter + */ +export const use = ( + f: (router: HttpRouter) => Effect.Effect +): Layer.Layer> => + Layer.effectDiscard(Effect.flatMap(HttpRouter.asEffect(), f)) + +/** + * Create a layer that adds a single route to the HTTP router. + * + * ```ts + * import * as Effect from "effect/Effect" + * import * as HttpRouter from "effect/unstable/http/HttpRouter" + * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" + * + * const Route = HttpRouter.add("GET", "/hello", Effect.succeed(HttpServerResponse.text("Hello, World!"))) + * ``` + * + * @since 4.0.0 + * @category HttpRouter + */ +export const add = ( + method: "*" | "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS", + path: PathInput, + handler: + | Effect.Effect + | ((request: HttpServerRequest.HttpServerRequest) => Effect.Effect), + options?: { + readonly uninterruptible?: boolean | undefined + } +): Layer.Layer> | Request.From<"Error", E>> => + use((router) => router.add(method, path, handler, options)) + +/** + * Create a layer that adds multiple routes to the HTTP router. + * + * ```ts + * import * as Effect from "effect/Effect" + * import * as HttpRouter from "effect/unstable/http/HttpRouter" + * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" + * + * const Routes = HttpRouter.addAll([ + * HttpRouter.route("GET", "/hello", Effect.succeed(HttpServerResponse.text("Hello, World!"))) + * ]) + * ``` + * + * @since 4.0.0 + * @category HttpRouter + */ +export const addAll = >, EX = never, RX = never>( + routes: Routes | Effect.Effect, + options?: { + readonly prefix?: string | undefined + } +): Layer.Layer< + never, + EX, + | HttpRouter + | Exclude + | Request.From<"Requires", Exclude, Provided>> + | Request.From<"Error", Route.Error> +> => + Layer.effectDiscard(Effect.gen(function*() { + const toAdd = Effect.isEffect(routes) ? yield* routes : routes + let router = yield* HttpRouter + if (options?.prefix) { + router = router.prefixed(options.prefix) + } + yield* router.addAll(toAdd) + })) + +/** + * @since 4.0.0 + * @category HttpRouter + */ +export const layer: Layer.Layer = Layer.effect(HttpRouter, make) + +/** + * @since 4.0.0 + * @category HttpRouter + */ +export const toHttpEffect = ( + appLayer: Layer.Layer +): Effect.Effect< + Effect.Effect< + HttpServerResponse.HttpServerResponse, + Request.Only<"Error", R> | Request.Only<"GlobalRequires", R> | HttpServerError.HttpServerError, + Scope.Scope | HttpServerRequest.HttpServerRequest | Request.Only<"Requires", R> | Request.Only<"GlobalRequires", R> + >, + Request.Without, + Exclude, HttpRouter> | Scope.Scope +> => + Effect.gen(function*() { + const scope = yield* Effect.scope + const memoMap = yield* Layer.CurrentMemoMap + const context = yield* Layer.buildWithMemoMap( + Layer.provideMerge(appLayer, layer), + memoMap, + scope + ) + const router = ServiceMap.get(context, HttpRouter) + return router.asHttpEffect() + }) as any + +/** + * @since 4.0.0 + * @category Route + */ +export const RouteTypeId: RouteTypeId = "~effect/http/HttpRouter/Route" + +/** + * @since 4.0.0 + * @category Route + */ +export type RouteTypeId = "~effect/http/HttpRouter/Route" + +/** + * @since 4.0.0 + * @category Route + */ +export interface Route { + readonly [RouteTypeId]: RouteTypeId + readonly method: HttpMethod.HttpMethod | "*" + readonly path: PathInput + readonly handler: Effect.Effect + readonly uninterruptible: boolean + readonly prefix: Option.Option +} + +/** + * @since 4.0.0 + * @category Route + */ +export declare namespace Route { + /** + * @since 4.0.0 + * @category Route + */ + export type Error> = R extends Route ? E : never + + /** + * @since 4.0.0 + * @category Route + */ + export type Context> = T extends Route ? R : never +} + +const makeRoute = (options: { + readonly method: HttpMethod.HttpMethod | "*" + readonly path: PathInput + readonly handler: Effect.Effect + readonly uninterruptible?: boolean | undefined + readonly prefix?: Option.Option | undefined +}): Route> => + ({ + ...options, + uninterruptible: options.uninterruptible ?? false, + prefix: options.prefix ?? Option.none(), + [RouteTypeId]: RouteTypeId + }) as Route> + +/** + * @since 4.0.0 + * @category Route + */ +export const route = ( + method: "*" | "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS", + path: PathInput, + handler: + | Effect.Effect + | ((request: HttpServerRequest.HttpServerRequest) => Effect.Effect), + options?: { + readonly uninterruptible?: boolean | undefined + } +): Route> => + makeRoute({ + ...options, + method, + path, + handler: Effect.isEffect(handler) + ? handler + : Effect.flatMap(HttpServerRequest.HttpServerRequest.asEffect(), handler), + uninterruptible: options?.uninterruptible ?? false + }) + +/** + * @since 4.0.0 + * @category PathInput + */ +export type PathInput = `/${string}` | "*" + +const removeTrailingSlash = ( + path: PathInput +): PathInput => (path.endsWith("/") ? path.slice(0, -1) : path) as any + +/** + * @since 4.0.0 + * @category PathInput + */ +export const prefixPath: { + (prefix: string): (self: string) => string + (self: string, prefix: string): string +} = dual(2, (self: string, prefix: string) => { + prefix = removeTrailingSlash(prefix as PathInput) + return self === "/" ? prefix : prefix + self +}) + +/** + * @since 4.0.0 + * @category Route + */ +export const prefixRoute: { + (prefix: string): (self: Route) => Route + (self: Route, prefix: string): Route +} = dual(2, (self: Route, prefix: string): Route => + makeRoute({ + ...self, + path: prefixPath(self.path, prefix) as PathInput, + prefix: Option.match(self.prefix, { + onNone: () => Option.some(prefix as string), + onSome: (existingPrefix) => Option.some(prefixPath(existingPrefix, prefix) as string) + }) + })) + +/** + * Represents a request-level dependency, that needs to be provided by + * middleware. + * + * @since 4.0.0 + * @category Request types + */ +export interface Request { + readonly _: unique symbol + readonly kind: Kind + readonly type: T +} + +/** + * @since 4.0.0 + * @category Request types + */ +export declare namespace Request { + /** + * @since 4.0.0 + * @category Request types + */ + export type From = R extends infer T ? Request : never + + /** + * @since 4.0.0 + * @category Request types + */ + export type Only = A extends Request ? T : never + + /** + * @since 4.0.0 + * @category Request types + */ + export type Without = A extends Request ? never : A +} + +/** + * Services provided by the HTTP router, which are available in the + * request context. + * + * @since 4.0.0 + * @category Request types + */ +export type Provided = + | HttpServerRequest.HttpServerRequest + | Scope.Scope + | HttpServerRequest.ParsedSearchParams + | RouteContext + +/** + * Services provided to global middleware. + * + * @since 4.0.0 + * @category Request types + */ +export type GlobalProvided = + | HttpServerRequest.HttpServerRequest + | Scope.Scope + +/** + * @since 4.0.0 + * @category Middleware + */ +export const MiddlewareTypeId: MiddlewareTypeId = "~effect/http/HttpRouter/Middleware" + +/** + * @since 4.0.0 + * @category Middleware + */ +export type MiddlewareTypeId = "~effect/http/HttpRouter/Middleware" + +/** + * A pseudo-error type that represents an error that should be not handled by + * the middleware. + * + * @since 4.0.0 + * @category Middleware + */ +export interface unhandled { + readonly _: unique symbol +} + +/** + * @since 4.0.0 + * @category Middleware + */ +export interface Middleware< + Config extends { + provides: any + handles: any + error: any + requires: any + layerError: any + layerRequires: any + } +> { + readonly [MiddlewareTypeId]: Config + + readonly layer: [Config["requires"]] extends [never] ? Layer.Layer< + Request.From<"Requires", Config["provides"]>, + Config["layerError"], + | Config["layerRequires"] + | Request.From<"Requires", Config["requires"]> + | Request.From<"Error", Config["error"]> + > + : "Need to .combine(middleware) that satisfy the missing request dependencies" + + readonly combine: < + Config2 extends { + provides: any + handles: any + error: any + requires: any + layerError: any + layerRequires: any + } + >(other: Middleware) => Middleware<{ + provides: Config2["provides"] | Config["provides"] + handles: Config2["handles"] | Config["handles"] + error: Config2["error"] | Exclude + requires: Exclude | Config2["requires"] + layerError: Config["layerError"] | Config2["layerError"] + layerRequires: Config["layerRequires"] | Config2["layerRequires"] + }> +} + +/** + * Create a middleware layer that can be used to modify requests and responses. + * + * By default, the middleware only affects the routes that it is provided to. + * + * If you want to create a middleware that applies globally to all routes, pass + * the `global` option as `true`. + * + * ```ts + * import * as HttpRouter from "effect/unstable/http/HttpRouter" + * import * as HttpMiddleware from "effect/unstable/http/HttpMiddleware" + * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" + * import * as ServiceMap from "effect/ServiceMap" + * import * as Effect from "effect/Effect" + * import * as Layer from "effect/Layer" + * + * // Here we are defining a CORS middleware + * const CorsMiddleware = HttpRouter.middleware(HttpMiddleware.cors()).layer + * // You can also use HttpRouter.cors() to create a CORS middleware + * + * class CurrentSession extends ServiceMap.Key()("CurrentSession") {} + * + * // You can create middleware that provides a service to the HTTP requests. + * const SessionMiddleware = HttpRouter.middleware<{ + * provides: CurrentSession + * }>()( + * Effect.gen(function*() { + * yield* Effect.log("SessionMiddleware initialized") + * + * return (httpEffect) => + * Effect.provideService(httpEffect, CurrentSession, { + * token: "dummy-token" + * }) + * }) + * ).layer + * + * Effect.gen(function*() { + * const router = yield* HttpRouter.HttpRouter + * yield* router.add( + * "GET", + * "/hello", + * Effect.gen(function*() { + * // Requests can now access the current session + * const session = yield* CurrentSession + * return HttpServerResponse.text(`Hello, World! Your token is ${session.token}`) + * }) + * ) + * }).pipe( + * Layer.effectDiscard, + * // Provide the SessionMiddleware & CorsMiddleware to some routes + * Layer.provide([SessionMiddleware, CorsMiddleware]) + * ) + * ``` + * + * @since 4.0.0 + * @category Middleware + */ +export const middleware: + & middleware.Make + & (< + Config extends { + provides?: any + handles?: any + } = {} + >() => middleware.Make< + Config extends { provides: infer R } ? R : never, + Config extends { handles: infer E } ? E : never + >) = function() { + if (arguments.length === 0) { + return makeMiddleware as any + } + return makeMiddleware(arguments[0], arguments[1]) as any + } + +const makeMiddleware = (middleware: any, options?: { + readonly global?: boolean | undefined +}) => + options?.global ? + Layer.effectDiscard(Effect.gen(function*() { + const router = yield* HttpRouter + const fn = Effect.isEffect(middleware) ? yield* middleware : middleware + yield* router.addGlobalMiddleware(fn) + })) + : new MiddlewareImpl( + Effect.isEffect(middleware) ? + Layer.effectServices(Effect.map(middleware, (fn) => ServiceMap.unsafeMake(new Map([[fnContextKey, fn]])))) : + Layer.succeedServices(ServiceMap.unsafeMake(new Map([[fnContextKey, middleware]]))) as any + ) + +let middlewareId = 0 +const fnContextKey = "effect/http/HttpRouter/MiddlewareFn" + +class MiddlewareImpl< + Config extends { + provides: any + handles: any + error: any + requires: any + layerError: any + layerRequires: any + } +> implements Middleware { + readonly [MiddlewareTypeId]: Config = {} as any + + constructor( + readonly layerFn: Layer.Layer, + readonly dependencies?: Layer.Layer + ) { + const contextKey = `effect/http/HttpRouter/Middleware-${++middlewareId}` as const + this.layer = Layer.effectDiscard(Effect.gen(this, function*() { + const context = yield* Effect.services() + const stack = [context.unsafeMap.get(fnContextKey)] + if (this.dependencies) { + const memoMap = yield* Layer.CurrentMemoMap + const scope = ServiceMap.get(context, Scope.Scope) + const depsContext = yield* Layer.buildWithMemoMap(this.dependencies, memoMap, scope) + // eslint-disable-next-line no-restricted-syntax + stack.push(...getMiddleware(depsContext)) + } + return ServiceMap.unsafeMake(new Map([[contextKey, stack]])) + })).pipe(Layer.provide(this.layerFn)) + } + + layer: any + + combine< + Config2 extends { + provides: any + handles: any + error: any + requires: any + layerError: any + layerRequires: any + } + >(other: Middleware): Middleware { + return new MiddlewareImpl( + this.layerFn, + this.dependencies ? Layer.provideMerge(this.dependencies, other.layer as any) : other.layer as any + ) as any + } +} + +const middlewareCache = new WeakMap, any>() +const getMiddleware = (context: ServiceMap.ServiceMap): Array => { + let arr = middlewareCache.get(context) + if (arr) return arr + const topLevel = Arr.empty>() + let maxLength = 0 + for (const [key, value] of context.unsafeMap) { + if (key.startsWith("effect/http/HttpRouter/Middleware-")) { + topLevel.push(value) + if (value.length > maxLength) { + maxLength = value.length + } + } + } + if (topLevel.length === 0) { + arr = [] + } else { + const middleware = new Set() + for (let i = maxLength - 1; i >= 0; i--) { + for (const arr of topLevel) { + if (i < arr.length) { + middleware.add(arr[i]) + } + } + } + arr = Arr.fromIterable(middleware).reverse() + } + middlewareCache.set(context, arr) + return arr +} + +/** + * @since 4.0.0 + * @category Middleware + */ +export declare namespace middleware { + /** + * @since 4.0.0 + * @category Middleware + */ + export type Make = { + ( + middleware: Effect.Effect< + ( + effect: Effect.Effect< + HttpServerResponse.HttpServerResponse, + Types.NoInfer, + Types.NoInfer + > + ) => + & Effect.Effect< + HttpServerResponse.HttpServerResponse, + E, + R + > + & (unhandled extends E ? unknown : "You must only handle the configured errors"), + EX, + RX + >, + options?: { + readonly global?: Global | undefined + } + ): Global extends true ? Layer.Layer< + | Request.From<"Requires", Provides> + | Request.From<"Error", Handles> + | Request.From<"GlobalRequires", Provides> + | Request.From<"GlobalError", Handles>, + EX, + | HttpRouter + | Exclude + | Request.From<"GlobalRequires", Exclude> + | Request.From<"GlobalError", Exclude> + > : + Middleware<{ + provides: Provides + handles: Handles + error: Exclude + requires: Exclude + layerError: EX + layerRequires: Exclude + }> + ( + middleware: + & (( + effect: Effect.Effect< + HttpServerResponse.HttpServerResponse, + Types.NoInfer, + Types.NoInfer + > + ) => Effect.Effect< + HttpServerResponse.HttpServerResponse, + E, + R + >) + & (unhandled extends E ? unknown : "You must only handle the configured errors"), + options?: { + readonly global?: Global | undefined + } + ): Global extends true ? Layer.Layer< + | Request.From<"Requires", Provides> + | Request.From<"Error", Handles> + | Request.From<"GlobalRequires", Provides> + | Request.From<"GlobalError", Handles>, + never, + | HttpRouter + | Request.From<"GlobalRequires", Exclude> + | Request.From<"GlobalError", Exclude> + > : + Middleware<{ + provides: Provides + handles: Handles + error: Exclude + requires: Exclude + layerError: never + layerRequires: never + }> + } + + /** + * @since 4.0.0 + * @category Middleware + */ + export type Fn = ( + effect: Effect.Effect + ) => Effect.Effect +} + +/** + * A middleware that applies CORS headers to the HTTP response. + * + * @since 4.0.0 + * @category Middleware + */ +export const cors = ( + options?: { + readonly allowedOrigins?: ReadonlyArray | undefined + readonly allowedMethods?: ReadonlyArray | undefined + readonly allowedHeaders?: ReadonlyArray | undefined + readonly exposedHeaders?: ReadonlyArray | undefined + readonly maxAge?: number | undefined + readonly credentials?: boolean | undefined + } | undefined +): Layer.Layer => middleware(HttpMiddleware.cors(options), { global: true }) + +/** + * A middleware that disables the logger for some routes. + * + * ```ts + * import * as Effect from "effect/Effect" + * import * as HttpRouter from "effect/unstable/http/HttpRouter" + * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" + * import * as Layer from "effect/Layer" + * + * const Route = HttpRouter.add("GET", "/hello", Effect.succeed(HttpServerResponse.text("Hello, World!"))).pipe( + * // disable the logger for this route + * Layer.provide(HttpRouter.disableLogger) + * ) + * ``` + * + * @since 4.0.0 + * @category Middleware + */ +export const disableLogger: Layer.Layer = middleware(HttpMiddleware.withLoggerDisabled).layer + +/** + * Serves the provided application layer as an HTTP server. + * + * @since 4.0.0 + * @category Server + */ +export const serve = | Request.Only<"GlobalRequires", R>>( + appLayer: Layer.Layer, + options?: { + readonly routerConfig?: Partial | undefined + readonly disableLogger?: boolean | undefined + readonly disableListenLog?: boolean + /** + * Middleware to apply to the HTTP server. + * + * NOTE: This middleware is applied to the entire HTTP server chain, + * including the sending of the response. This means that modifications + * to the response **WILL NOT** be reflected in the final response sent to the + * client. + * + * Use HttpRouter.middleware to create middleware that can modify the + * response. + */ + readonly middleware?: ( + effect: Effect.Effect< + HttpServerResponse.HttpServerResponse, + Request.Only<"Error", R> | Request.Only<"GlobalError", R> | HttpServerError.HttpServerError, + | Scope.Scope + | HttpServerRequest.HttpServerRequest + | Request.Only<"Requires", R> + | Request.Only<"GlobalRequires", R> + > + ) => Effect.Effect + } +): Layer.Layer< + never, + Request.Without, + HttpServer.HttpServer | Exclude | Exclude, HttpRouter> +> => { + let middleware: any = options?.middleware + if (options?.disableLogger !== true) { + middleware = middleware ? compose(middleware, HttpMiddleware.logger) : HttpMiddleware.logger + } + const RouterLayer = options?.routerConfig + ? Layer.provide(layer, Layer.succeed(RouterConfig, options.routerConfig)) + : layer + return Effect.gen(function*() { + const router = yield* HttpRouter + const handler = router.asHttpEffect() + return middleware ? HttpServer.serve(handler, middleware) : HttpServer.serve(handler) + }).pipe( + Layer.unwrap, + Layer.provide(appLayer), + Layer.provide(RouterLayer), + options?.disableListenLog ? identity : HttpServer.withLogAddress + ) as any +} + +/** + * @since 4.0.0 + * @category Server + */ +export const toWebHandler = < + A, + E, + R extends + | HttpRouter + | Request<"Requires", any> + | Request<"GlobalRequires", any> + | Request<"Error", any> + | Request<"GlobalError", any>, + HE, + HR = Request.Only<"Requires", R> | Request.Only<"GlobalRequires", R> +>( + appLayer: Layer.Layer, + options?: { + readonly memoMap?: Layer.MemoMap | undefined + readonly routerConfig?: Partial | undefined + readonly disableLogger?: boolean | undefined + /** + * Middleware to apply to the HTTP server. + * + * NOTE: This middleware is applied to the entire HTTP server chain, + * including the sending of the response. This means that modifications + * to the response **WILL NOT** be reflected in the final response sent to the + * client. + * + * Use HttpRouter.middleware to create middleware that can modify the + * response. + */ + readonly middleware?: ( + effect: Effect.Effect< + HttpServerResponse.HttpServerResponse, + Request.Only<"Error", R> | Request.Only<"GlobalError", R> | HttpServerError.HttpServerError, + | Scope.Scope + | HttpServerRequest.HttpServerRequest + | Request.Only<"Requires", R> + | Request.Only<"GlobalRequires", R> + > + ) => Effect.Effect + } +): { + readonly handler: [HR] extends [never] + ? ((request: globalThis.Request, context?: ServiceMap.ServiceMap | undefined) => Promise) + : ((request: globalThis.Request, context: ServiceMap.ServiceMap
) => Promise) + readonly dispose: () => Promise +} => { + let middleware: any = options?.middleware + if (options?.disableLogger !== true) { + middleware = middleware ? compose(middleware, HttpMiddleware.logger) : HttpMiddleware.logger + } + const RouterLayer = options?.routerConfig + ? Layer.provide(layer, Layer.succeed(RouterConfig, options.routerConfig)) + : layer + const runtime = ManagedRuntime.make( + Layer.provideMerge(appLayer, RouterLayer) as any, + options + ) + let handlerCached: + | ((request: globalThis.Request, context?: ServiceMap.ServiceMap | undefined) => Promise) + | undefined + const handlerPromise = Effect.gen(function*() { + const router = yield* HttpRouter + const effect = router.asHttpEffect() + const services = yield* runtime.servicesEffect + const handler = HttpEffect.toWebHandlerWith(services)(effect, middleware) + handlerCached = handler + return handler + }).pipe(runtime.runPromise) + function handler(request: globalThis.Request, context?: ServiceMap.ServiceMap | undefined): Promise { + if (handlerCached !== undefined) return handlerCached(request, context) + return handlerPromise.then((handler) => handler(request, context)) + } + return { handler, dispose: runtime.dispose } as const +} diff --git a/packages/effect/src/unstable/http/HttpServer.ts b/packages/effect/src/unstable/http/HttpServer.ts new file mode 100644 index 0000000000..87ede7c4e0 --- /dev/null +++ b/packages/effect/src/unstable/http/HttpServer.ts @@ -0,0 +1,254 @@ +/** + * @since 4.0.0 + */ +import * as Effect from "../../Effect.js" +import * as FileSystem from "../../FileSystem.js" +import { dual } from "../../Function.js" +import * as Layer from "../../Layer.js" +import * as Path from "../../Path.js" +import type * as Scope from "../../Scope.js" +import * as ServiceMap from "../../ServiceMap.js" +import * as Etag from "./Etag.js" +import * as HttpClient from "./HttpClient.js" +import * as ClientRequest from "./HttpClientRequest.js" +import type * as Middleware from "./HttpMiddleware.js" +import * as HttpPlatform from "./HttpPlatform.js" +import type { HttpServerRequest } from "./HttpServerRequest.js" +import type { HttpServerResponse } from "./HttpServerResponse.js" + +/** + * @since 4.0.0 + * @category models + */ +export class HttpServer extends ServiceMap.Key(effect: Effect.Effect): Effect.Effect< + void, + never, + Exclude | Scope.Scope + > + >( + effect: Effect.Effect, + middleware: Middleware.HttpMiddleware.Applied + ): Effect.Effect< + void, + never, + Exclude | Scope.Scope + > + } + readonly address: Address +}>()("effect/http/HttpServer") {} + +/** + * @since 4.0.0 + * @category address + */ +export type Address = UnixAddress | TcpAddress + +/** + * @since 4.0.0 + * @category address + */ +export interface TcpAddress { + readonly _tag: "TcpAddress" + readonly hostname: string + readonly port: number +} + +/** + * @since 4.0.0 + * @category address + */ +export interface UnixAddress { + readonly _tag: "UnixAddress" + readonly path: string +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const make = ( + options: { + readonly serve: ( + httpApp: Effect.Effect, + middleware?: Middleware.HttpMiddleware + ) => Effect.Effect + readonly address: Address + } +): HttpServer["Service"] => options + +/** + * @since 4.0.0 + * @category accessors + */ +export const serve: { + (): ( + effect: Effect.Effect + ) => Layer.Layer> + >( + middleware: Middleware.HttpMiddleware.Applied + ): ( + effect: Effect.Effect + ) => Layer.Layer< + never, + never, + HttpServer | Exclude, HttpServerRequest | Scope.Scope> + > + ( + effect: Effect.Effect + ): Layer.Layer> + >( + effect: Effect.Effect, + middleware: Middleware.HttpMiddleware.Applied + ): Layer.Layer< + never, + never, + HttpServer | Exclude, HttpServerRequest | Scope.Scope> + > +} = dual((args) => Effect.isEffect(args[0]), >( + effect: Effect.Effect, + middleware?: Middleware.HttpMiddleware.Applied +): Layer.Layer< + never, + never, + HttpServer | Exclude, HttpServerRequest | Scope.Scope> +> => + Layer.effectDiscard( + Effect.flatMap( + HttpServer.asEffect(), + (server) => server.serve(effect, middleware!) + ) + ) as any) + +/** + * @since 4.0.0 + * @category accessors + */ +export const serveEffect: { + (): ( + effect: Effect.Effect + ) => Effect.Effect> + >( + middleware: Middleware.HttpMiddleware.Applied + ): ( + effect: Effect.Effect + ) => Effect.Effect< + void, + never, + Scope.Scope | HttpServer | Exclude, HttpServerRequest> + > + ( + effect: Effect.Effect + ): Effect.Effect> + >( + effect: Effect.Effect, + middleware: Middleware.HttpMiddleware.Applied + ): Effect.Effect< + void, + never, + Scope.Scope | HttpServer | Exclude, HttpServerRequest> + > +} = dual((args) => Effect.isEffect(args[0]), >( + effect: Effect.Effect, + middleware?: Middleware.HttpMiddleware.Applied +): Effect.Effect< + void, + never, + Scope.Scope | HttpServer | Exclude, HttpServerRequest> +> => + Effect.flatMap( + HttpServer.asEffect(), + (server) => server.serve(effect, middleware!) + ) as any) + +/** + * @since 4.0.0 + * @category address + */ +export const formatAddress = (address: Address): string => { + switch (address._tag) { + case "UnixAddress": + return `unix://${address.path}` + case "TcpAddress": + return `http://${address.hostname}:${address.port}` + } +} + +/** + * @since 4.0.0 + * @category address + */ +export const addressFormattedWith = ( + f: (address: string) => Effect.Effect +): Effect.Effect => + Effect.flatMap( + HttpServer.asEffect(), + (server) => f(formatAddress(server.address)) + ) + +/** + * @since 4.0.0 + * @category address + */ +export const logAddress: Effect.Effect = addressFormattedWith((_) => + Effect.log(`Listening on ${_}`) +) + +/** + * @since 4.0.0 + * @category address + */ +export const withLogAddress = ( + layer: Layer.Layer +): Layer.Layer> => + Layer.effectDiscard(logAddress).pipe( + Layer.provideMerge(layer) + ) + +/** + * @since 4.0.0 + * @category Testing + */ +export const makeTestClient: Effect.Effect< + HttpClient.HttpClient, + never, + HttpServer | HttpClient.HttpClient +> = Effect.gen(function*() { + const server = yield* HttpServer + const client = yield* HttpClient.HttpClient + const address = server.address + if (address._tag === "UnixAddress") { + return yield* Effect.die(new Error("HttpServer.layerTestClient: UnixAddress not supported")) + } + const host = address.hostname === "0.0.0.0" ? "127.0.0.1" : address.hostname + const url = `http://${host}:${address.port}` + return HttpClient.mapRequest(client, ClientRequest.prependUrl(url)) +}) + +/** + * @since 4.0.0 + * @category Testing + */ +export const layerTestClient: Layer.Layer< + HttpClient.HttpClient, + never, + HttpServer | HttpClient.HttpClient +> = Layer.effect(HttpClient.HttpClient, makeTestClient) + +/** + * @since 4.0.0 + * @category Testing + */ +export const layerServices: Layer.Layer< + | Path.Path + | HttpPlatform.HttpPlatform + | FileSystem.FileSystem + | Etag.Generator +> = Layer.mergeAll( + HttpPlatform.layer, + Path.layer, + Etag.layerWeak +).pipe( + Layer.provideMerge(FileSystem.layerNoop({})) +) diff --git a/packages/effect/src/unstable/http/HttpServerError.ts b/packages/effect/src/unstable/http/HttpServerError.ts new file mode 100644 index 0000000000..f93a09e473 --- /dev/null +++ b/packages/effect/src/unstable/http/HttpServerError.ts @@ -0,0 +1,203 @@ +/** + * @since 4.0.0 + */ +import * as Arr from "../../Array.js" +import * as Cause from "../../Cause.js" +import * as Data from "../../Data.js" +import * as Effect from "../../Effect.js" +import type * as Exit from "../../Exit.js" +import * as Option from "../../Option.js" +import { hasProperty } from "../../Predicate.js" +import type * as Request from "./HttpServerRequest.js" +import * as Respondable from "./HttpServerRespondable.js" +import * as Response from "./HttpServerResponse.js" + +/** + * @since 4.0.0 + * @category type id + */ +export const TypeId: TypeId = "~effect/http/HttpServerError" + +/** + * @since 4.0.0 + * @category type id + */ +export type TypeId = "~effect/http/HttpServerError" + +/** + * @since 4.0.0 + * @category error + */ +export type HttpServerError = RequestError | ResponseError + +/** + * @since 4.0.0 + * @category error + */ +export class RequestError extends Data.TaggedError("HttpServerError")<{ + readonly reason: "RequestParseError" | "RouteNotFound" + readonly request: Request.HttpServerRequest + readonly description?: string + readonly cause?: unknown +}> implements Respondable.Respondable { + /** + * @since 4.0.0 + */ + readonly [TypeId]: TypeId = TypeId + + /** + * @since 4.0.0 + */ + stack = `${this.name}: ${this.message}`; + + /** + * @since 4.0.0 + */ + [Respondable.symbol]() { + return Effect.succeed(Response.empty({ status: this.reason === "RouteNotFound" ? 404 : 400 })) + } + + get methodAndUrl() { + return `${this.request.method} ${this.request.url}` + } + + get message() { + const prefix = `${this.reason} (${this.methodAndUrl})` + return this.description ? `${prefix}: ${this.description}` : prefix + } +} + +/** + * @since 4.0.0 + * @category predicates + */ +export const isHttpServerError = (u: unknown): u is HttpServerError => hasProperty(u, TypeId) + +/** + * @since 4.0.0 + * @category error + */ +export class ResponseError extends Data.TaggedError("HttpServerError")<{ + readonly request: Request.HttpServerRequest + readonly response: Response.HttpServerResponse + readonly description?: string + readonly cause?: unknown +}> implements Respondable.Respondable { + /** + * @since 4.0.0 + */ + readonly [TypeId]: TypeId = TypeId + /** + * @since 4.0.0 + */ + readonly reason = "ResponseError" as const + + /** + * @since 4.0.0 + */ + stack = `${this.name}: ${this.message}`; + + /** + * @since 4.0.0 + */ + [Respondable.symbol]() { + return Effect.succeed(Response.empty({ status: 500 })) + } + + get methodAndUrl() { + return `${this.request.method} ${this.request.url}` + } + + get message() { + const info = `${this.reason} (${this.response.status} ${this.methodAndUrl})` + return this.description ? `${info}: ${this.description}` : info + } +} + +/** + * @since 4.0.0 + * @category error + */ +export class ServeError extends Data.TaggedError("ServeError")<{ + readonly cause: unknown +}> { + /** + * @since 4.0.0 + */ + readonly [TypeId]: TypeId = TypeId +} + +/** + * @since 4.0.0 + */ +export const clientAbortFiberId = -499 + +/** + * @since 4.0.0 + */ +export const causeResponse = ( + cause: Cause.Cause +): Effect.Effect]> => { + const [effect, failures] = Arr.reduce( + cause.failures, + [Effect.succeed(internalServerError), Arr.empty>()] as const, + (acc, f) => { + switch (f._tag) { + case "Fail": { + return [Respondable.toResponseOrElse(f.error, internalServerError), [f]] + } + case "Die": { + return [Respondable.toResponseOrElseDefect(f.defect, internalServerError), [f]] + } + case "Interrupt": { + if (acc[1].length > 0) return acc + const response = f.fiberId._tag === "Some" && f.fiberId.value === clientAbortFiberId + ? clientAbortError + : serverAbortError + return [Effect.succeed(response), [f]] + } + default: { + return acc + } + } + } + ) + return Effect.map(effect, (response) => { + failures.push(Cause.failureDie(response)) + return [response, Cause.fromFailures(failures)] as const + }) +} + +/** + * @since 4.0.0 + */ +export const causeResponseStripped = ( + cause: Cause.Cause +): readonly [response: Response.HttpServerResponse, cause: Option.Option>] => { + let response: Response.HttpServerResponse | undefined + const failures = cause.failures.filter((f) => { + if (f._tag === "Die" && Response.isHttpServerResponse(f.defect)) { + response = f.defect + return false + } + return true + }) + return [ + response ?? internalServerError, + failures.length > 0 ? Option.some(Cause.fromFailures(failures)) : Option.none() + ] +} + +const internalServerError = Response.empty({ status: 500 }) +const clientAbortError = Response.empty({ status: 499 }) +const serverAbortError = Response.empty({ status: 503 }) + +/** + * @since 4.0.0 + */ +export const exitResponse = (exit: Exit.Exit): Response.HttpServerResponse => { + if (exit._tag === "Success") { + return exit.value + } + return causeResponseStripped(exit.cause)[0] +} diff --git a/packages/effect/src/unstable/http/HttpServerRequest.ts b/packages/effect/src/unstable/http/HttpServerRequest.ts new file mode 100644 index 0000000000..4fb0d33aa4 --- /dev/null +++ b/packages/effect/src/unstable/http/HttpServerRequest.ts @@ -0,0 +1,492 @@ +/** + * @since 4.0.0 + */ +import type * as Arr from "../../Array.js" +import * as Channel from "../../Channel.js" +import * as Effect from "../../Effect.js" +import type * as FileSystem from "../../FileSystem.js" +import * as Inspectable from "../../Inspectable.js" +import * as Option from "../../Option.js" +import type * as Path from "../../Path.js" +import type { ReadonlyRecord } from "../../Record.js" +import type { ParseOptions } from "../../schema/AST.js" +import * as Schema from "../../schema/Schema.js" +import type * as Scope from "../../Scope.js" +import * as ServiceMap from "../../ServiceMap.js" +import * as Stream from "../../Stream.js" +import * as Socket from "../socket/Socket.js" +import * as Cookies from "./Cookies.js" +import * as Headers from "./Headers.js" +import * as HttpIncomingMessage from "./HttpIncomingMessage.js" +import type { HttpMethod } from "./HttpMethod.js" +import { type HttpServerError, RequestError } from "./HttpServerError.js" +import * as Multipart from "./Multipart.js" +import * as UrlParams from "./UrlParams.js" + +export { + /** + * @since 4.0.0 + * @category fiber refs + */ + MaxBodySize +} from "./HttpIncomingMessage.js" + +/** + * @since 4.0.0 + * @category type ids + */ +export const TypeId: TypeId = "~effect/http/HttpServerRequest" + +/** + * @since 4.0.0 + * @category type ids + */ +export type TypeId = "~effect/http/HttpServerRequest" + +/** + * @since 4.0.0 + * @category models + */ +export interface HttpServerRequest extends HttpIncomingMessage.HttpIncomingMessage { + readonly [TypeId]: TypeId + readonly source: unknown + readonly url: string + readonly originalUrl: string + readonly method: HttpMethod + readonly cookies: ReadonlyRecord + + readonly multipart: Effect.Effect< + Multipart.Persisted, + Multipart.MultipartError, + Scope.Scope | FileSystem.FileSystem | Path.Path + > + readonly multipartStream: Stream.Stream + + readonly upgrade: Effect.Effect + + readonly modify: ( + options: { + readonly url?: string + readonly headers?: Headers.Headers + readonly remoteAddress?: string + } + ) => HttpServerRequest +} + +/** + * @since 4.0.0 + * @category context + */ +export const HttpServerRequest: ServiceMap.Key = ServiceMap.Key( + "effect/http/HttpServerRequest" +) + +/** + * @since 4.0.0 + * @category search params + */ +export class ParsedSearchParams extends ServiceMap.Key< + ParsedSearchParams, + ReadonlyRecord> +>()("effect/http/ParsedSearchParams") {} + +/** + * @since 4.0.0 + * @category search params + */ +export const searchParamsFromURL = (url: URL): ReadonlyRecord> => { + const out: Record> = {} + for (const [key, value] of url.searchParams.entries()) { + const entry = out[key] + if (entry !== undefined) { + if (Array.isArray(entry)) { + entry.push(value) + } else { + out[key] = [entry, value] + } + } else { + out[key] = value + } + } + return out +} + +/** + * @since 4.0.0 + * @category accessors + */ +export const upgradeChannel = (): Channel.Channel< + Arr.NonEmptyReadonlyArray, + HttpServerError | IE | Socket.SocketError, + void, + Arr.NonEmptyReadonlyArray, + IE, + unknown, + HttpServerRequest +> => + HttpServerRequest.asEffect().pipe( + Effect.flatMap((_) => _.upgrade), + Effect.map(Socket.toChannelWith()), + Channel.unwrap + ) + +/** + * @since 4.0.0 + * @category schema + */ +export const schemaCookies = >, RD, RE>( + schema: Schema.Codec, + options?: ParseOptions | undefined +): Effect.Effect => { + const parse = Schema.decodeUnknownEffect(schema) + return Effect.flatMap(HttpServerRequest.asEffect(), (req) => parse(req.cookies, options)) +} + +/** + * @since 4.0.0 + * @category schema + */ +export const schemaHeaders = >, RD, RE>( + schema: Schema.Codec, + options?: ParseOptions | undefined +): Effect.Effect => { + const parse = Schema.decodeUnknownEffect(schema) + return Effect.flatMap(HttpServerRequest.asEffect(), (req) => parse(req.headers, options)) +} + +/** + * @since 4.0.0 + * @category schema + */ +export const schemaSearchParams = < + A, + I extends Readonly | undefined>>, + RD, + RE +>( + schema: Schema.Codec, + options?: ParseOptions | undefined +): Effect.Effect => { + const parse = Schema.decodeUnknownEffect(schema) + return Effect.flatMap(ParsedSearchParams.asEffect(), (params) => parse(params, options)) +} +/** + * @since 4.0.0 + * @category schema + */ +export const schemaBodyJson = ( + schema: Schema.Codec, + options?: ParseOptions | undefined +): Effect.Effect => { + const parse = HttpIncomingMessage.schemaBodyJson(schema, options) + return Effect.flatMap(HttpServerRequest.asEffect(), parse) +} + +const isMultipart = (request: HttpServerRequest) => + request.headers["content-type"]?.toLowerCase().includes("multipart/form-data") + +/** + * @since 4.0.0 + * @category schema + */ + +/** @internal */ +export const schemaBodyForm = , RD, RE>( + schema: Schema.Codec, + options?: ParseOptions | undefined +) => { + const parseMultipart = Multipart.schemaPersisted(schema) + const parseUrlParams = HttpIncomingMessage.schemaBodyUrlParams(schema as Schema.Codec, options) + return Effect.flatMap(HttpServerRequest.asEffect(), (request): Effect.Effect< + A, + Multipart.MultipartError | Schema.SchemaError | HttpServerError, + RD | HttpServerRequest | Scope.Scope | FileSystem.FileSystem | Path.Path + > => { + if (isMultipart(request)) { + return Effect.flatMap(request.multipart, (_) => parseMultipart(_, options)) + } + return parseUrlParams(request) + }) +} + +/** + * @since 4.0.0 + * @category schema + */ +export const schemaBodyUrlParams = < + A, + I extends Readonly | undefined>>, + RD, + RE +>( + schema: Schema.Codec, + options?: ParseOptions | undefined +): Effect.Effect => { + const parse = HttpIncomingMessage.schemaBodyJson(schema, options) + return Effect.flatMap(HttpServerRequest.asEffect(), parse) +} + +/** + * @since 4.0.0 + * @category schema + */ +export const schemaBodyMultipart = , RD, RE>( + schema: Schema.Codec, + options?: ParseOptions | undefined +): Effect.Effect< + A, + Multipart.MultipartError | Schema.SchemaError, + HttpServerRequest | Scope.Scope | FileSystem.FileSystem | Path.Path | RD +> => { + const parse = Multipart.schemaPersisted(schema) + return HttpServerRequest.asEffect().pipe( + Effect.flatMap((_) => _.multipart), + Effect.flatMap((_) => parse(_, options)) + ) +} + +/** + * @since 4.0.0 + * @category schema + */ +export const schemaBodyFormJson = ( + schema: Schema.Codec, + options?: ParseOptions | undefined +) => { + const parseMultipart = Multipart.schemaJson(schema, options) + return (field: string) => { + const parseUrlParams = UrlParams.schemaJsonField(field).pipe( + Schema.decodeTo(schema), + Schema.decodeEffect + ) + return Effect.flatMap( + HttpServerRequest.asEffect(), + (request): Effect.Effect< + A, + Schema.SchemaError | HttpServerError, + RD | FileSystem.FileSystem | Path.Path | Scope.Scope | HttpServerRequest + > => { + if (isMultipart(request)) { + return Effect.flatMap( + Effect.mapError(request.multipart, (cause) => + new RequestError({ + request, + reason: "RequestParseError", + cause + })), + parseMultipart(field) + ) + } + return Effect.flatMap(request.urlParamsBody, (_) => parseUrlParams(_, options)) + } + ) + } +} + +/** + * @since 4.0.0 + * @category conversions + */ +export const fromWeb = (request: globalThis.Request): HttpServerRequest => + new ServerRequestImpl(request, removeHost(request.url)) + +const removeHost = (url: string) => { + if (url[0] === "/") { + return url + } + const index = url.indexOf("/", url.indexOf("//") + 2) + return index === -1 ? "/" : url.slice(index) +} + +class ServerRequestImpl extends Inspectable.Class implements HttpServerRequest { + readonly [TypeId]: TypeId + readonly [HttpIncomingMessage.TypeId]: HttpIncomingMessage.TypeId + constructor( + readonly source: Request, + readonly url: string, + public headersOverride?: Headers.Headers, + private remoteAddressOverride?: string + ) { + super() + this[TypeId] = TypeId + this[HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId + } + toJSON(): unknown { + return HttpIncomingMessage.inspect(this, { + _id: "effect/http/HttpServerRequest", + method: this.method, + url: this.originalUrl + }) + } + modify( + options: { + readonly url?: string | undefined + readonly headers?: Headers.Headers | undefined + readonly remoteAddress?: string | undefined + } + ) { + return new ServerRequestImpl( + this.source, + options.url ?? this.url, + options.headers ?? this.headersOverride, + options.remoteAddress ?? this.remoteAddressOverride + ) + } + get method(): HttpMethod { + return this.source.method.toUpperCase() as HttpMethod + } + get originalUrl() { + return this.source.url + } + get remoteAddress(): Option.Option { + return this.remoteAddressOverride ? Option.some(this.remoteAddressOverride) : Option.none() + } + get headers(): Headers.Headers { + this.headersOverride ??= Headers.fromInput(this.source.headers as any) + return this.headersOverride + } + + private cachedCookies: ReadonlyRecord | undefined + get cookies() { + if (this.cachedCookies) { + return this.cachedCookies + } + return this.cachedCookies = Cookies.parseHeader(this.headers.cookie ?? "") + } + + get stream(): Stream.Stream { + return this.source.body + ? Stream.fromReadableStream({ + evaluate: () => this.source.body as any, + onError: (cause) => + new RequestError({ + request: this, + reason: "RequestParseError", + cause + }) + }) + : Stream.fail( + new RequestError({ + request: this, + reason: "RequestParseError", + description: "can not create stream from empty body" + }) + ) + } + + private textEffect: Effect.Effect | undefined + get text(): Effect.Effect { + if (this.textEffect) { + return this.textEffect + } + this.textEffect = Effect.runSync(Effect.cached( + Effect.tryPromise({ + try: () => this.source.text(), + catch: (cause) => + new RequestError({ + request: this, + reason: "RequestParseError", + cause + }) + }) + )) + return this.textEffect + } + + get json(): Effect.Effect { + return Effect.flatMap(this.text, (text) => + Effect.try({ + try: () => JSON.parse(text) as unknown, + catch: (cause) => + new RequestError({ + request: this, + reason: "RequestParseError", + cause + }) + })) + } + + get urlParamsBody(): Effect.Effect { + return Effect.flatMap(this.text, (_) => + Effect.try({ + try: () => UrlParams.fromInput(new URLSearchParams(_)), + catch: (cause) => + new RequestError({ + request: this, + reason: "RequestParseError", + cause + }) + })) + } + + private multipartEffect: + | Effect.Effect< + Multipart.Persisted, + Multipart.MultipartError, + Scope.Scope | FileSystem.FileSystem | Path.Path + > + | undefined + get multipart(): Effect.Effect< + Multipart.Persisted, + Multipart.MultipartError, + Scope.Scope | FileSystem.FileSystem | Path.Path + > { + if (this.multipartEffect) { + return this.multipartEffect + } + this.multipartEffect = Effect.runSync(Effect.cached( + Multipart.toPersisted(this.multipartStream) + )) + return this.multipartEffect + } + + get multipartStream(): Stream.Stream { + return Stream.pipeThroughChannel( + Stream.mapError(this.stream, (cause) => new Multipart.MultipartError({ reason: "InternalError", cause })), + Multipart.makeChannel(this.headers) + ) + } + + private arrayBufferEffect: Effect.Effect | undefined + get arrayBuffer(): Effect.Effect { + if (this.arrayBufferEffect) { + return this.arrayBufferEffect + } + this.arrayBufferEffect = Effect.runSync(Effect.cached( + Effect.tryPromise({ + try: () => this.source.arrayBuffer(), + catch: (cause) => + new RequestError({ + request: this, + reason: "RequestParseError", + cause + }) + }) + )) + return this.arrayBufferEffect + } + + get upgrade(): Effect.Effect { + return Effect.fail( + new RequestError({ + request: this, + reason: "RequestParseError", + description: "Not an upgradeable ServerRequest" + }) + ) + } +} + +/** + * @since 4.0.0 + * @category conversions + */ +export const toURL = (self: HttpServerRequest): Option.Option => { + const host = self.headers.host ?? "localhost" + const protocol = self.headers["x-forwarded-proto"] === "https" ? "https" : "http" + try { + return Option.some(new URL(self.url, `${protocol}://${host}`)) + } catch { + return Option.none() + } +} diff --git a/packages/effect/src/unstable/http/HttpServerRespondable.ts b/packages/effect/src/unstable/http/HttpServerRespondable.ts new file mode 100644 index 0000000000..88cf47e89a --- /dev/null +++ b/packages/effect/src/unstable/http/HttpServerRespondable.ts @@ -0,0 +1,74 @@ +/** + * @since 4.0.0 + */ +import * as Cause from "../../Cause.js" +import * as Effect from "../../Effect.js" +import { hasProperty } from "../../Predicate.js" +import * as Schema from "../../schema/Schema.js" +import type { HttpServerResponse } from "./HttpServerResponse.js" +import * as Response from "./HttpServerResponse.js" + +/** + * @since 4.0.0 + * @category symbols + */ +export const symbol: "~effect/http/HttpServerRespondable" = "~effect/http/HttpServerRespondable" as const + +/** + * @since 4.0.0 + * @category models + */ +export interface Respondable { + readonly [symbol]: () => Effect.Effect +} + +/** + * @since 4.0.0 + * @category guards + */ +export const isRespondable = (u: unknown): u is Respondable => hasProperty(u, symbol) + +const badRequest = Response.empty({ status: 400 }) +const notFound = Response.empty({ status: 404 }) + +/** + * @since 4.0.0 + * @category accessors + */ +export const toResponse = (self: Respondable): Effect.Effect => { + if (Response.isHttpServerResponse(self)) { + return Effect.succeed(self) + } + return Effect.orDie(self[symbol]()) +} + +/** + * @since 4.0.0 + * @category accessors + */ +export const toResponseOrElse = (u: unknown, orElse: HttpServerResponse): Effect.Effect => { + if (Response.isHttpServerResponse(u)) { + return Effect.succeed(u) + } else if (isRespondable(u)) { + return Effect.catchCause(u[symbol](), () => Effect.succeed(orElse)) + // add support for some commmon types + } else if (u instanceof Schema.SchemaError) { + return Effect.succeed(badRequest) + } else if (Cause.isNoSuchElementError(u)) { + return Effect.succeed(notFound) + } + return Effect.succeed(orElse) +} + +/** + * @since 4.0.0 + * @category accessors + */ +export const toResponseOrElseDefect = (u: unknown, orElse: HttpServerResponse): Effect.Effect => { + if (Response.isHttpServerResponse(u)) { + return Effect.succeed(u) + } else if (isRespondable(u)) { + return Effect.catchCause(u[symbol](), () => Effect.succeed(orElse)) + } + return Effect.succeed(orElse) +} diff --git a/packages/effect/src/unstable/http/HttpServerResponse.ts b/packages/effect/src/unstable/http/HttpServerResponse.ts new file mode 100644 index 0000000000..1ea1c00364 --- /dev/null +++ b/packages/effect/src/unstable/http/HttpServerResponse.ts @@ -0,0 +1,706 @@ +/** + * @since 4.0.0 + */ +import * as Effect from "../../Effect.js" +import type * as FileSystem from "../../FileSystem.js" +import { dual } from "../../Function.js" +import { ServiceMap } from "../../index.js" +import * as Inspectable from "../../Inspectable.js" +import { PipeInspectableProto } from "../../internal/core.js" +import type { Pipeable } from "../../Pipeable.js" +import type { PlatformError } from "../../PlatformError.js" +import { hasProperty } from "../../Predicate.js" +import type { ParseOptions } from "../../schema/AST.js" +import type * as Schema from "../../schema/Schema.js" +import * as Stream from "../../Stream.js" +import type { Mutable } from "../../Types.js" +import * as Cookies from "./Cookies.js" +import * as Headers from "./Headers.js" +import * as Body from "./HttpBody.js" +import { HttpPlatform } from "./HttpPlatform.js" +import * as Template from "./Template.js" +import * as UrlParams from "./UrlParams.js" + +/** + * @since 4.0.0 + * @category type ids + */ +export const TypeId: TypeId = "~effect/http/HttpServerResponse" + +/** + * @since 4.0.0 + * @category type ids + */ +export type TypeId = "~effect/http/HttpServerResponse" + +/** + * @since 4.0.0 + * @category models + */ +export interface HttpServerResponse extends Inspectable.Inspectable, Pipeable { + readonly [TypeId]: TypeId + readonly status: number + readonly statusText?: string | undefined + readonly headers: Headers.Headers + readonly cookies: Cookies.Cookies + readonly body: Body.HttpBody +} + +/** + * @since 4.0.0 + * @category models + */ +export interface Options { + readonly status?: number | undefined + readonly statusText?: string | undefined + readonly headers?: Headers.Input | undefined + readonly cookies?: Cookies.Cookies | undefined + readonly contentType?: string | undefined + readonly contentLength?: number | undefined +} + +/** + * @since 4.0.0 + */ +export declare namespace Options { + /** + * @since 4.0.0 + * @category models + */ + export interface WithContent extends Omit {} + + /** + * @since 4.0.0 + * @category models + */ + export interface WithContentType extends Omit {} +} + +/** + * @since 4.0.0 + */ +export const isHttpServerResponse = (u: unknown): u is HttpServerResponse => hasProperty(u, TypeId) + +/** + * @since 4.0.0 + * @category constructors + */ +export const empty = (options?: Options.WithContent | undefined): HttpServerResponse => + makeResponse({ + status: options?.status ?? 204, + statusText: options?.statusText + }) + +/** + * @since 4.0.0 + * @category constructors + */ +export const redirect = (location: string | URL, options?: Options.WithContentType | undefined): HttpServerResponse => { + const headers = Headers.unsafeFromRecord({ location: location.toString() }) + return makeResponse({ + status: options?.status ?? 302, + statusText: options?.statusText, + headers: options?.headers ? + Headers.merge(headers, Headers.fromInput(options.headers)) : + headers, + cookies: options?.cookies ?? Cookies.empty + }) +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const uint8Array = ( + body: Uint8Array, + options?: Options.WithContentType +): HttpServerResponse => { + const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty + return makeResponse({ + status: options?.status ?? 200, + statusText: options?.statusText, + headers, + cookies: options?.cookies ?? Cookies.empty, + body: Body.uint8Array(body, getContentType(options, headers)) + }) +} + +const getContentType = ( + options: Options | undefined, + headers: Headers.Headers +): string | undefined => { + if (options?.contentType) { + return options.contentType + } else if (options?.headers) { + return headers["content-type"] + } +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const text = ( + body: string, + options?: Options.WithContentType +): HttpServerResponse => { + const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty + return makeResponse({ + status: options?.status ?? 200, + statusText: options?.statusText, + headers, + cookies: options?.cookies ?? Cookies.empty, + body: Body.text(body, getContentType(options, headers)) + }) +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const html: { +
>( + strings: TemplateStringsArray, + ...args: A + ): Effect.Effect< + HttpServerResponse, + Template.Interpolated.Error, + Template.Interpolated.Context + > + (html: string): HttpServerResponse +} = ( + strings: TemplateStringsArray | string, + ...args: ReadonlyArray +) => { + if (typeof strings === "string") { + return text(strings, { contentType: "text/html" }) + } + + return Effect.map( + Template.make(strings, ...args), + (_) => text(_, { contentType: "text/html" }) + ) as any +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const htmlStream = >( + strings: TemplateStringsArray, + ...args: A +): Effect.Effect< + HttpServerResponse, + never, + Template.Interpolated.Context +> => + Effect.map( + Effect.services>(), + (context) => + stream( + Stream.provideServices( + Stream.encodeText(Template.stream(strings, ...args)), + context + ), + { contentType: "text/html" } + ) + ) + +/** + * @since 4.0.0 + * @category constructors + */ +export const json = ( + body: unknown, + options?: Options.WithContent | undefined +): Effect.Effect => + Effect.map(Body.json(body), (body) => + makeResponse({ + status: options?.status ?? 200, + statusText: options?.statusText, + headers: options?.headers && Headers.fromInput(options.headers), + cookies: options?.cookies, + body + })) + +/** + * @since 4.0.0 + * @category constructors + */ +export const schemaJson = ( + schema: Schema.Codec, + options?: ParseOptions | undefined +) => { + const encode = Body.jsonSchema(schema, options) + return ( + body: A, + options?: Options.WithContent | undefined + ): Effect.Effect => + Effect.map(encode(body), (body) => + makeResponse({ + status: options?.status ?? 200, + statusText: options?.statusText, + headers: options?.headers && Headers.fromInput(options.headers), + cookies: options?.cookies, + body + })) +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const unsafeJson = ( + body: unknown, + options?: Options.WithContent | undefined +): HttpServerResponse => + makeResponse({ + status: options?.status ?? 200, + statusText: options?.statusText, + headers: options?.headers && Headers.fromInput(options.headers), + cookies: options?.cookies, + body: Body.unsafeJson(body) + }) + +/** + * @since 4.0.0 + * @category constructors + */ +export const urlParams = ( + body: UrlParams.Input, + options?: Options.WithContent | undefined +): HttpServerResponse => + makeResponse({ + status: options?.status ?? 200, + statusText: options?.statusText, + headers: options?.headers && Headers.fromInput(options.headers), + cookies: options?.cookies, + body: Body.text(UrlParams.toString(UrlParams.fromInput(body)), "application/x-www-form-urlencoded") + }) + +/** + * @since 4.0.0 + * @category constructors + */ +export const raw = (body: unknown, options?: Options | undefined): HttpServerResponse => + makeResponse({ + status: options?.status ?? 200, + statusText: options?.statusText, + headers: options?.headers && Headers.fromInput(options.headers), + cookies: options?.cookies, + body: Body.raw(body, { + contentType: options?.contentType, + contentLength: options?.contentLength + }) + }) + +/** + * @since 4.0.0 + * @category constructors + */ +export const formData = ( + body: FormData, + options?: Options.WithContent | undefined +): HttpServerResponse => + makeResponse({ + status: options?.status ?? 200, + statusText: options?.statusText, + headers: options?.headers && Headers.fromInput(options.headers), + cookies: options?.cookies, + body: Body.formData(body) + }) + +/** + * @since 4.0.0 + * @category constructors + */ +export const stream = ( + body: Stream.Stream, + options?: Options | undefined +): HttpServerResponse => { + const headers = options?.headers ? Headers.fromInput(options.headers) : Headers.empty + return makeResponse({ + status: options?.status ?? 200, + statusText: options?.statusText, + headers, + cookies: options?.cookies, + body: Body.stream(body, getContentType(options, headers), options?.contentLength) + }) +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const file = ( + path: string, + options?: (Options & FileSystem.StreamOptions) | undefined +): Effect.Effect => + Effect.flatMap( + HttpPlatform.asEffect(), + (platform) => platform.fileResponse(path, options) + ) + +/** + * @since 4.0.0 + * @category constructors + */ +export const fileWeb = ( + file: Body.HttpBody.FileLike, + options?: (Options.WithContent & FileSystem.StreamOptions) | undefined +): Effect.Effect => + Effect.flatMap( + HttpPlatform.asEffect(), + (platform) => platform.fileWebResponse(file, options) + ) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setHeader: { + (key: string, value: string): (self: HttpServerResponse) => HttpServerResponse + (self: HttpServerResponse, key: string, value: string): HttpServerResponse +} = dual(3, (self: HttpServerResponse, key: string, value: string): HttpServerResponse => + makeResponse({ + ...self, + headers: Headers.set(self.headers, key, value) + })) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setHeaders: { + (input: Headers.Input): (self: HttpServerResponse) => HttpServerResponse + (self: HttpServerResponse, input: Headers.Input): HttpServerResponse +} = dual(2, (self: HttpServerResponse, input: Headers.Input): HttpServerResponse => + makeResponse({ + ...self, + headers: Headers.setAll(self.headers, input) + })) + +/** + * @since 4.0.0 + * @category combinators + */ +export const removeCookie: { + (name: string): (self: HttpServerResponse) => HttpServerResponse + (self: HttpServerResponse, name: string): HttpServerResponse +} = dual(2, (self: HttpServerResponse, name: string): HttpServerResponse => + makeResponse({ + ...self, + cookies: Cookies.remove(self.cookies, name) + })) + +/** + * @since 4.0.0 + * @category combinators + */ +export const replaceCookies: { + (cookies: Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse + (self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse +} = dual( + 2, + (self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse => makeResponse({ ...self, cookies }) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setCookie: { + ( + name: string, + value: string, + options?: Cookies.Cookie["options"] + ): ( + self: HttpServerResponse + ) => Effect.Effect< + HttpServerResponse, + Cookies.CookiesError + > + ( + self: HttpServerResponse, + name: string, + value: string, + options?: Cookies.Cookie["options"] + ): Effect.Effect< + HttpServerResponse, + Cookies.CookiesError + > +} = dual( + (args) => isHttpServerResponse(args[0]), + (self: HttpServerResponse, name: string, value: string, options?: Cookies.Cookie["options"]): Effect.Effect< + HttpServerResponse, + Cookies.CookiesError + > => + Effect.map(Cookies.set(self.cookies, name, value, options).asEffect(), (cookies) => + makeResponse({ + ...self, + cookies + })) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const unsafeSetCookie: { + ( + name: string, + value: string, + options?: Cookies.Cookie["options"] + ): (self: HttpServerResponse) => HttpServerResponse + ( + self: HttpServerResponse, + name: string, + value: string, + options?: Cookies.Cookie["options"] + ): HttpServerResponse +} = dual( + (args) => isHttpServerResponse(args[0]), + (self: HttpServerResponse, name: string, value: string, options?: Cookies.Cookie["options"]): HttpServerResponse => + makeResponse({ + ...self, + cookies: Cookies.unsafeSet(self.cookies, name, value, options) + }) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const updateCookies: { + (f: (cookies: Cookies.Cookies) => Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse + (self: HttpServerResponse, f: (cookies: Cookies.Cookies) => Cookies.Cookies): HttpServerResponse +} = dual( + 2, + (self: HttpServerResponse, f: (cookies: Cookies.Cookies) => Cookies.Cookies): HttpServerResponse => + makeResponse({ + ...self, + cookies: f(self.cookies) + }) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const mergeCookies: { + (cookies: Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse + (self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse +} = dual( + 2, + (self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse => + makeResponse({ ...self, cookies: Cookies.merge(self.cookies, cookies) }) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setCookies: { + ( + cookies: Iterable< + readonly [ + name: string, + value: string, + options?: Cookies.Cookie["options"] + ] + > + ): (self: HttpServerResponse) => Effect.Effect + ( + self: HttpServerResponse, + cookies: Iterable< + readonly [ + name: string, + value: string, + options?: Cookies.Cookie["options"] + ] + > + ): Effect.Effect +} = dual(2, ( + self: HttpServerResponse, + cookies: Iterable< + readonly [ + name: string, + value: string, + options?: Cookies.Cookie["options"] + ] + > +): Effect.Effect => + Effect.map(Cookies.setAll(self.cookies, cookies).asEffect(), (cookies) => + makeResponse({ + ...self, + cookies + }))) + +/** + * @since 4.0.0 + * @category combinators + */ +export const unsafeSetCookies: { + ( + cookies: Iterable< + readonly [ + name: string, + value: string, + options?: Cookies.Cookie["options"] + ] + > + ): (self: HttpServerResponse) => HttpServerResponse + ( + self: HttpServerResponse, + cookies: Iterable< + readonly [ + name: string, + value: string, + options?: Cookies.Cookie["options"] + ] + > + ): HttpServerResponse +} = dual(2, ( + self: HttpServerResponse, + cookies: Iterable< + readonly [ + name: string, + value: string, + options?: Cookies.Cookie["options"] + ] + > +): HttpServerResponse => + makeResponse({ + ...self, + cookies: Cookies.unsafeSetAll(self.cookies, cookies) + })) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setBody: { + (body: Body.HttpBody): (self: HttpServerResponse) => HttpServerResponse + (self: HttpServerResponse, body: Body.HttpBody): HttpServerResponse +} = dual(2, (self: HttpServerResponse, body: Body.HttpBody): HttpServerResponse => makeResponse({ ...self, body })) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setStatus: { + (status: number, statusText?: string | undefined): (self: HttpServerResponse) => HttpServerResponse + (self: HttpServerResponse, status: number, statusText?: string | undefined): HttpServerResponse +} = dual( + (args) => isHttpServerResponse(args[0]), + (self: HttpServerResponse, status: number, statusText?: string | undefined): HttpServerResponse => + makeResponse({ + ...self, + status, + statusText: statusText ?? self.statusText + }) +) + +/** + * @since 4.0.0 + * @category conversions + */ +export const toWeb = (response: HttpServerResponse, options?: { + readonly withoutBody?: boolean | undefined + readonly services?: ServiceMap.ServiceMap | undefined +}): Response => { + const headers = new globalThis.Headers(response.headers) + if (!Cookies.isEmpty(response.cookies)) { + const toAdd = Cookies.toSetCookieHeaders(response.cookies) + for (const header of toAdd) { + headers.append("set-cookie", header) + } + } + if (options?.withoutBody) { + return new Response(undefined, { + status: response.status, + statusText: response.statusText as string, + headers + }) + } + const body = response.body + switch (body._tag) { + case "Empty": { + return new Response(undefined, { + status: response.status, + statusText: response.statusText as string, + headers + }) + } + case "Uint8Array": + case "Raw": { + if (body.body instanceof Response) { + for (const [key, value] of headers as any) { + body.body.headers.set(key, value) + } + return body.body + } + return new Response(body.body as any, { + status: response.status, + statusText: response.statusText!, + headers + }) + } + case "FormData": { + return new Response(body.formData as any, { + status: response.status, + statusText: response.statusText!, + headers + }) + } + case "Stream": { + return new Response(Stream.toReadableStreamWith(body.stream, options?.services ?? ServiceMap.empty()), { + status: response.status, + statusText: response.statusText!, + headers + }) + } + } +} + +const Proto: Omit = { + ...PipeInspectableProto, + [TypeId]: TypeId, + toJSON(this: HttpServerResponse) { + return { + _id: "HttpServerResponse", + status: this.status, + statusText: this.statusText, + headers: Inspectable.redact(this.headers), + cookies: this.cookies.toJSON(), + body: this.body.toJSON() + } + } +} + +const makeResponse = (options: { + readonly status: number + readonly statusText?: string | undefined + readonly headers?: Headers.Headers | undefined + readonly cookies?: Cookies.Cookies | undefined + readonly body?: Body.HttpBody | undefined +}) => { + const self = Object.create(Proto) as Mutable + self.status = options.status + self.statusText = options.statusText + self.cookies = options.cookies ?? Cookies.empty + self.body = options.body ?? Body.empty + if (self.body._tag !== "Empty" && (self.body.contentType || self.body.contentLength)) { + const newHeaders = Headers.unsafeFromRecord({ ...options.headers }) as any + if (self.body.contentType) { + newHeaders["content-type"] = self.body.contentType + } + if (self.body.contentLength) { + newHeaders["content-length"] = self.body.contentLength.toString() + } + self.headers = newHeaders + } else { + self.headers = options.headers ?? Headers.empty + } + return self +} diff --git a/packages/effect/src/unstable/http/Multipart.ts b/packages/effect/src/unstable/http/Multipart.ts new file mode 100644 index 0000000000..804d672b54 --- /dev/null +++ b/packages/effect/src/unstable/http/Multipart.ts @@ -0,0 +1,617 @@ +/** + * @since 4.0.0 + */ +import * as Arr from "../../Array.js" +import * as Channel from "../../Channel.js" +import * as Effect from "../../Effect.js" +import * as Exit from "../../Exit.js" +import * as FileSystem from "../../FileSystem.js" +import { constant, dual } from "../../Function.js" +import * as Inspectable from "../../Inspectable.js" +import * as Option from "../../Option.js" +import * as Path from "../../Path.js" +import * as Predicate from "../../Predicate.js" +import * as Pull from "../../Pull.js" +import type { ParseOptions } from "../../schema/AST.js" +import * as Check from "../../schema/Check.js" +import * as Schema from "../../schema/Schema.js" +import * as Transformation from "../../schema/Transformation.js" +import type * as Scope from "../../Scope.js" +import * as ServiceMap from "../../ServiceMap.js" +import * as Stream from "../../Stream.js" +import * as IncomingMessage from "./HttpIncomingMessage.js" +import * as MP from "./Multipasta.js" + +/** + * @since 4.0.0 + * @category type ids + */ +export const TypeId: TypeId = "~effect/http/Multipart" + +/** + * @since 4.0.0 + * @category type ids + */ +export type TypeId = "~effect/http/Multipart" + +/** + * @since 4.0.0 + * @category models + */ +export type Part = Field | File + +/** + * @since 4.0.0 + */ +export declare namespace Part { + /** + * @since 4.0.0 + * @category models + */ + export interface Proto extends Inspectable.Inspectable { + readonly [TypeId]: TypeId + readonly _tag: string + } +} + +/** + * @since 4.0.0 + * @category models + */ +export interface Field extends Part.Proto { + readonly _tag: "Field" + readonly key: string + readonly contentType: string + readonly value: string +} + +/** + * @since 4.0.0 + * @category Guards + */ +export const isPart = (u: unknown): u is Part => Predicate.hasProperty(u, TypeId) + +/** + * @since 4.0.0 + * @category Guards + */ +export const isField = (u: unknown): u is Field => isPart(u) && u._tag === "Field" + +/** + * @since 4.0.0 + * @category models + */ +export interface File extends Part.Proto { + readonly _tag: "File" + readonly key: string + readonly name: string + readonly contentType: string + readonly content: Stream.Stream + readonly contentEffect: Effect.Effect +} + +/** + * @since 4.0.0 + * @category Guards + */ +export const isFile = (u: unknown): u is File => isPart(u) && u._tag === "File" + +/** + * @since 4.0.0 + * @category models + */ +export interface PersistedFile extends Part.Proto { + readonly _tag: "PersistedFile" + readonly key: string + readonly name: string + readonly contentType: string + readonly path: string +} + +/** + * @since 4.0.0 + * @category Guards + */ +export const isPersistedFile = (u: unknown): u is PersistedFile => + Predicate.hasProperty(u, TypeId) && Predicate.isTagged(u, "PersistedFile") + +/** + * @since 4.0.0 + * @category models + */ +export interface Persisted { + readonly [key: string]: ReadonlyArray | ReadonlyArray | string +} + +/** + * @since 4.0.0 + * @category Errors + */ +export const ErrorTypeId: ErrorTypeId = "~effect/http/Multipart/MultipartError" + +/** + * @since 4.0.0 + * @category Errors + */ +export type ErrorTypeId = "~effect/http/Multipart/MultipartError" + +/** + * @since 4.0.0 + * @category Errors + */ +export class MultipartError extends Schema.ErrorClass(ErrorTypeId)({ + _tag: Schema.tag("MultipartError"), + reason: Schema.Literals(["FileTooLarge", "FieldTooLarge", "BodyTooLarge", "TooManyParts", "InternalError", "Parse"]), + cause: Schema.Unknown +}) { + /** + * @since 4.0.0 + */ + readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId + + /** + * @since 4.0.0 + */ + get message(): string { + return this.reason + } +} + +/** + * @since 4.0.0 + * @category Schemas + */ +export interface FileSchema extends Schema.declareRefinement {} + +/** + * @since 4.0.0 + * @category Schemas + */ +export const FileSchema: FileSchema = Schema.declareRefinement({ + is: isPersistedFile, + annotations: { + identifier: "PersistedFile", + jsonSchema: { + _tag: "override", + override: () => ({ + type: "string", + format: "binary" + }) + } + } +}) + +/** + * @since 4.0.0 + * @category Schemas + */ +export const FilesSchema: Schema.Array$ = Schema.Array(FileSchema) + +/** + * @since 4.0.0 + * @category Schemas + */ +export const SingleFileSchema: Schema.decodeTo< + FileSchema, + Schema.Array$, + never, + never +> = FilesSchema.check(Check.length(1)).pipe( + Schema.decodeTo( + FileSchema, + Transformation.transform({ + decode: ([file]) => file, + encode: (file) => [file] + }) + ) +) + +/** + * @since 4.0.0 + * @category Schemas + */ +export const schemaPersisted = , RD, RE>( + schema: Schema.Codec +): (input: unknown, options?: ParseOptions) => Effect.Effect => + Schema.decodeUnknownEffect(schema) + +/** + * @since 4.0.0 + * @category Schemas + */ +export const schemaJson = (schema: Schema.Codec, options?: ParseOptions | undefined): { + ( + field: string + ): (persisted: Persisted) => Effect.Effect + ( + persisted: Persisted, + field: string + ): Effect.Effect +} => { + const fromJson = Schema.fromJsonString(schema) + return dual(2, (persisted: Persisted, field: string): Effect.Effect => + Effect.map( + Schema.decodeUnknownEffect(Schema.Struct({ [field]: fromJson }))(persisted, options), + (_) => _[field] + )) +} + +/** + * @since 4.0.0 + * @category Config + */ +export const makeConfig = ( + headers: Record +): Effect.Effect => + Effect.withFiber((fiber) => { + const mimeTypes = ServiceMap.get(fiber.services, FieldMimeTypes) + return Effect.succeed({ + headers, + maxParts: Option.getOrUndefined(fiber.getRef(MaxParts)), + maxFieldSize: Number(fiber.getRef(MaxFieldSize)), + maxPartSize: fiber.getRef(MaxFileSize).pipe(Option.map(Number), Option.getOrUndefined), + maxTotalSize: fiber.getRef(IncomingMessage.MaxBodySize).pipe( + Option.map(Number), + Option.getOrUndefined + ), + isFile: mimeTypes.length === 0 ? undefined : (info: MP.PartInfo): boolean => + !mimeTypes.some( + (_) => info.contentType.includes(_) + ) && MP.defaultIsFile(info) + }) + }) + +/** + * @since 4.0.0 + * @category Parsers + */ +export const makeChannel = (headers: Record): Channel.Channel< + Arr.NonEmptyReadonlyArray, + MultipartError | IE, + void, + Arr.NonEmptyReadonlyArray, + IE, + unknown +> => + Channel.fromTransform((upstream) => + Effect.map(makeConfig(headers), (config) => { + let partsBuffer: Array = [] + let exit = Option.none>>() + + const parser = MP.make({ + ...config, + onField(info, value) { + partsBuffer.push(new FieldImpl(info.name, info.contentType, MP.decodeField(info, value))) + }, + onFile(info) { + let chunks: Array = [] + let finished = false + const pullChunks = Channel.fromPull( + Effect.succeed(Effect.suspend(function loop(): Pull.Pull> { + if (!Arr.isNonEmptyReadonlyArray(chunks)) { + return finished ? Pull.haltVoid : Effect.flatMap(pump, loop) + } + const chunk = chunks + chunks = [] + return Effect.succeed(chunk) + })) + ) + partsBuffer.push(new FileImpl(info, pullChunks)) + return function(chunk) { + if (chunk === null) { + finished = true + } else { + chunks.push(chunk) + } + } + }, + onError(error_) { + exit = Option.some(Exit.fail(convertError(error_))) + }, + onDone() { + exit = Option.some(Exit.fail(new Pull.Halt(void 0))) + } + }) + + const pump = upstream.pipe( + Effect.flatMap((chunk) => { + for (let i = 0; i < chunk.length; i++) { + parser.write(chunk[i]) + } + return Effect.void + }), + Effect.catchCause((cause) => { + if (Pull.isHaltCause(cause)) { + parser.end() + } else { + exit = Option.some(Exit.failCause(cause)) as any + } + return Effect.void + }) + ) + + return pump.pipe( + Effect.flatMap(function loop(): Pull.Pull, IE | MultipartError> { + if (!Arr.isNonEmptyReadonlyArray(partsBuffer)) { + if (Option.isSome(exit)) { + return exit.value + } + return Effect.flatMap(pump, loop) + } + const parts = partsBuffer + partsBuffer = [] + return Effect.succeed(parts) + }) + ) + }) + ) + +function convertError(cause: MP.MultipartError): MultipartError { + switch (cause._tag) { + case "ReachedLimit": { + switch (cause.limit) { + case "MaxParts": { + return new MultipartError({ reason: "TooManyParts", cause }) + } + case "MaxFieldSize": { + return new MultipartError({ reason: "FieldTooLarge", cause }) + } + case "MaxPartSize": { + return new MultipartError({ reason: "FileTooLarge", cause }) + } + case "MaxTotalSize": { + return new MultipartError({ reason: "BodyTooLarge", cause }) + } + } + } + default: { + return new MultipartError({ reason: "Parse", cause }) + } + } +} + +abstract class PartBase extends Inspectable.Class { + readonly [TypeId]: TypeId + constructor() { + super() + this[TypeId] = TypeId + } +} + +class FieldImpl extends PartBase implements Field { + readonly _tag = "Field" + + constructor( + readonly key: string, + readonly contentType: string, + readonly value: string + ) { + super() + } + + toJSON(): unknown { + return { + _id: "@effect/platform/Multipart/Part", + _tag: "Field", + key: this.key, + contentType: this.contentType, + value: this.value + } + } +} + +class FileImpl extends PartBase implements File { + readonly _tag = "File" + readonly key: string + readonly name: string + readonly contentType: string + readonly content: Stream.Stream + readonly contentEffect: Effect.Effect + + constructor( + info: MP.PartInfo, + channel: Channel.Channel> + ) { + super() + this.key = info.name + this.name = info.filename ?? info.name + this.contentType = info.contentType + this.content = Stream.fromChannel(channel) + this.contentEffect = channel.pipe( + collectUint8Array, + Effect.mapError((cause) => new MultipartError({ reason: "InternalError", cause })) + ) + } + + toJSON(): unknown { + return { + _id: "@effect/platform/Multipart/Part", + _tag: "File", + key: this.key, + name: this.name, + contentType: this.contentType + } + } +} + +const defaultWriteFile = (path: string, file: File) => + Effect.flatMap( + FileSystem.FileSystem.asEffect(), + (fs) => + Effect.mapError( + Stream.run(file.content, fs.sink(path)), + (cause) => new MultipartError({ reason: "InternalError", cause }) + ) + ) + +/** + * @since 4.0.0 + */ +export const collectUint8Array = ( + self: Channel.Channel, OE, OD, unknown, unknown, unknown, R> +): Effect.Effect, OE, R> => + Channel.runFold(self, constant(new Uint8Array(0)), (accumulator, chunk) => { + const totalLength = chunk.reduce((sum, element) => sum + element.length, accumulator.length) + const newAccumulator = new Uint8Array(totalLength) + newAccumulator.set(accumulator, 0) + let offset = accumulator.length + for (const element of chunk) { + newAccumulator.set(element, offset) + offset += element.length + } + return newAccumulator + }) + +/** + * @since 4.0.0 + * @category Conversions + */ +export const toPersisted = ( + stream: Stream.Stream, + writeFile = defaultWriteFile +): Effect.Effect => + Effect.gen(function*() { + const fs = yield* FileSystem.FileSystem + const path_ = yield* Path.Path + const dir = yield* fs.makeTempDirectoryScoped() + const persisted: Record | Array | string> = Object.create(null) + yield* Stream.runForEach(stream, (part) => { + if (part._tag === "Field") { + if (!(part.key in persisted)) { + persisted[part.key] = part.value + } else if (typeof persisted[part.key] === "string") { + persisted[part.key] = [persisted[part.key] as string, part.value] + } else { + ;(persisted[part.key] as Array).push(part.value) + } + return Effect.void + } else if (part.name === "") { + return Effect.void + } + const file = part + const path = path_.join(dir, path_.basename(file.name).slice(-128)) + const filePart = new PersistedFileImpl( + file.key, + file.name, + file.contentType, + path + ) + if (Array.isArray(persisted[part.key])) { + ;(persisted[part.key] as Array).push(filePart) + } else { + persisted[part.key] = [filePart] + } + return writeFile(path, file) + }) + return persisted + }).pipe( + Effect.catchTags({ + SystemError: (cause) => Effect.fail(new MultipartError({ reason: "InternalError", cause })), + BadArgument: (cause) => Effect.fail(new MultipartError({ reason: "InternalError", cause })) + }) + ) + +class PersistedFileImpl extends PartBase implements PersistedFile { + readonly _tag = "PersistedFile" + + constructor( + readonly key: string, + readonly name: string, + readonly contentType: string, + readonly path: string + ) { + super() + } + + toJSON(): unknown { + return { + _id: "@effect/platform/Multipart/Part", + _tag: "PersistedFile", + key: this.key, + name: this.name, + contentType: this.contentType, + path: this.path + } + } +} + +/** + * @since 4.0.0 + * @category References + */ +export const limitsServices = (options: { + readonly maxParts?: Option.Option | undefined + readonly maxFieldSize?: FileSystem.SizeInput | undefined + readonly maxFileSize?: Option.Option | undefined + readonly maxTotalSize?: Option.Option | undefined + readonly fieldMimeTypes?: ReadonlyArray | undefined +}): ServiceMap.ServiceMap => { + const map = new Map() + if (options.maxParts !== undefined) { + map.set(MaxParts.key, options.maxParts) + } + if (options.maxFieldSize !== undefined) { + map.set(MaxFieldSize.key, FileSystem.Size(options.maxFieldSize)) + } + if (options.maxFileSize !== undefined) { + map.set(MaxFileSize.key, Option.map(options.maxFileSize, FileSystem.Size)) + } + if (options.maxTotalSize !== undefined) { + map.set(IncomingMessage.MaxBodySize.key, Option.map(options.maxTotalSize, FileSystem.Size)) + } + if (options.fieldMimeTypes !== undefined) { + map.set(FieldMimeTypes.key, options.fieldMimeTypes) + } + return ServiceMap.unsafeMake(map) +} + +/** + * @since 4.0.0 + * @category fiber refs + */ +export declare namespace withLimits { + /** + * @since 4.0.0 + * @category fiber refs + */ + export type Options = { + readonly maxParts?: Option.Option | undefined + readonly maxFieldSize?: FileSystem.SizeInput | undefined + readonly maxFileSize?: Option.Option | undefined + readonly maxTotalSize?: Option.Option | undefined + readonly fieldMimeTypes?: ReadonlyArray | undefined + } +} + +/** + * @since 4.0.0 + * @category References + */ +export const MaxParts = ServiceMap.Reference>("effect/http/Multipart/MaxParts", { + defaultValue: Option.none +}) + +/** + * @since 4.0.0 + * @category References + */ +export const MaxFieldSize = ServiceMap.Reference("effect/http/Multipart/MaxFieldSize", { + defaultValue: constant(FileSystem.Size(10 * 1024 * 1024)) +}) + +/** + * @since 4.0.0 + * @category References + */ +export const MaxFileSize = ServiceMap.Reference>( + "effect/http/Multipart/MaxFileSize", + { defaultValue: Option.none } +) + +/** + * @since 4.0.0 + * @category References + */ +export const FieldMimeTypes = ServiceMap.Reference>("effect/http/Multipart/FieldMimeTypes", { + defaultValue: constant(["application/json"]) +}) diff --git a/packages/effect/src/unstable/http/Multipasta.ts b/packages/effect/src/unstable/http/Multipasta.ts new file mode 100644 index 0000000000..312773ad11 --- /dev/null +++ b/packages/effect/src/unstable/http/Multipasta.ts @@ -0,0 +1,9 @@ +/** + * @since 4.0.0 + */ + +/** + * @since 4.0.0 + * @category re-exports + */ +export * from "multipasta" diff --git a/packages/effect/src/unstable/http/Template.ts b/packages/effect/src/unstable/http/Template.ts new file mode 100644 index 0000000000..d0e267a231 --- /dev/null +++ b/packages/effect/src/unstable/http/Template.ts @@ -0,0 +1,203 @@ +/** + * @since 4.0.0 + */ +import * as Effect from "../../Effect.js" +import * as Exit from "../../Exit.js" +import * as Option from "../../Option.js" +import * as Stream from "../../Stream.js" + +/** + * @category models + * @since 4.0.0 + */ +export type PrimitiveValue = string | number | bigint | boolean | null | undefined + +/** + * @category models + * @since 4.0.0 + */ +export type Primitive = PrimitiveValue | ReadonlyArray + +/** + * @category models + * @since 4.0.0 + */ +export type Interpolated = + | Primitive + | Option.Option + | Effect.Effect + +/** + * @category models + * @since 4.0.0 + */ +export type InterpolatedWithStream = Interpolated | Stream.Stream + +/** + * @category models + * @since 4.0.0 + */ +export declare namespace Interpolated { + /** + * @category models + * @since 4.0.0 + */ + export type Context = A extends infer T ? T extends Option.Option ? never + : T extends Effect.Effect ? R + : T extends Stream.Stream ? R + : never + : never + + /** + * @category models + * @since 4.0.0 + */ + export type Error = A extends infer T ? T extends Option.Option ? never + : T extends Stream.Stream ? E + : T extends Effect.Effect ? E + : never + : never +} + +/** + * @category constructors + * @since 4.0.0 + */ +export function make>( + strings: TemplateStringsArray, + ...args: A +): Effect.Effect< + string, + Interpolated.Error, + Interpolated.Context +> { + const argsLength = args.length + const values = new Array(argsLength) + const effects: Array< + [index: number, effect: Effect.Effect] + > = [] + + for (let i = 0; i < argsLength; i++) { + const arg = args[i] + + if (Option.isOption(arg)) { + values[i] = arg._tag === "Some" ? primitiveToString(arg.value) : "" + } else if (isSuccess(arg)) { + values[i] = primitiveToString(arg.value) + } else if (Effect.isEffect(arg)) { + effects.push([i, arg]) + } else { + values[i] = primitiveToString(arg) + } + } + + if (effects.length === 0) { + return Effect.succeed(consolidate(strings, values)) + } + + return Effect.map( + Effect.forEach( + effects, + ([index, effect]) => + Effect.tap(effect, (value) => { + values[index] = primitiveToString(value) + }), + { + concurrency: "inherit", + discard: true + } + ), + (_) => consolidate(strings, values) + ) +} + +/** + * @category constructors + * @since 4.0.0 + */ +export function stream>( + strings: TemplateStringsArray, + ...args: A +): Stream.Stream< + string, + Interpolated.Error, + Interpolated.Context +> { + const chunks: Array | Effect.Effect> = [] + let buffer = "" + + for (let i = 0, len = args.length; i < len; i++) { + buffer += strings[i] + const arg = args[i] + if (Option.isOption(arg)) { + buffer += arg._tag === "Some" ? primitiveToString(arg.value) : "" + } else if (isSuccess(arg)) { + buffer += primitiveToString(arg.value) + } else if (Effect.isEffect(arg)) { + if (buffer.length > 0) { + chunks.push(buffer) + buffer = "" + } + chunks.push(Effect.map(arg, primitiveToString)) + } else if (Stream.isStream(arg)) { + if (buffer.length > 0) { + chunks.push(buffer) + buffer = "" + } + chunks.push(Stream.map(arg, primitiveToString)) + } else { + buffer += primitiveToString(arg) + } + } + + buffer += strings[strings.length - 1] + if (buffer.length > 0) { + chunks.push(buffer) + buffer = "" + } + + return Stream.flatMap( + Stream.fromIterable(chunks), + (chunk) => + typeof chunk === "string" ? Stream.succeed(chunk) : Effect.isEffect(chunk) ? Stream.fromEffect(chunk) : chunk, + { concurrency: "unbounded" } + ) +} + +function primitiveToString(value: Primitive): string { + if (Array.isArray(value)) { + return value.map(primitiveToString).join("") + } + + switch (typeof value) { + case "string": { + return value + } + case "number": + case "bigint": { + return value.toString() + } + case "boolean": { + return value ? "true" : "false" + } + default: { + return "" + } + } +} + +function consolidate( + strings: ReadonlyArray, + values: ReadonlyArray +): string { + let out = "" + for (let i = 0, len = values.length; i < len; i++) { + out += strings[i] + out += values[i] + } + return out + strings[strings.length - 1] +} + +function isSuccess(u: unknown): u is Exit.Success { + return Exit.isExit(u) && u._tag === "Success" +} diff --git a/packages/effect/src/unstable/http/index.ts b/packages/effect/src/unstable/http/index.ts index 7581ee7c9d..756ce90e10 100644 --- a/packages/effect/src/unstable/http/index.ts +++ b/packages/effect/src/unstable/http/index.ts @@ -7,11 +7,21 @@ */ export * as Cookies from "./Cookies.js" +/** + * @since 4.0.0 + */ +export * as Etag from "./Etag.js" + /** * @since 1.0.0 */ export * as FetchHttpClient from "./FetchHttpClient.js" +/** + * @since 4.0.0 + */ +export * as FindMyWay from "./FindMyWay.js" + /** * @since 4.0.0 */ @@ -42,6 +52,11 @@ export * as HttpClientRequest from "./HttpClientRequest.js" */ export * as HttpClientResponse from "./HttpClientResponse.js" +/** + * @since 4.0.0 + */ +export * as HttpEffect from "./HttpEffect.js" + /** * @since 4.0.0 */ @@ -52,11 +67,66 @@ export * as HttpIncomingMessage from "./HttpIncomingMessage.js" */ export * as HttpMethod from "./HttpMethod.js" +/** + * @since 4.0.0 + */ +export * as HttpMiddleware from "./HttpMiddleware.js" + +/** + * @since 4.0.0 + */ +export * as HttpPlatform from "./HttpPlatform.js" + +/** + * @since 4.0.0 + */ +export * as HttpRouter from "./HttpRouter.js" + +/** + * @since 4.0.0 + */ +export * as HttpServer from "./HttpServer.js" + +/** + * @since 4.0.0 + */ +export * as HttpServerError from "./HttpServerError.js" + +/** + * @since 4.0.0 + */ +export * as HttpServerRequest from "./HttpServerRequest.js" + +/** + * @since 4.0.0 + */ +export * as HttpServerRespondable from "./HttpServerRespondable.js" + +/** + * @since 4.0.0 + */ +export * as HttpServerResponse from "./HttpServerResponse.js" + /** * @since 4.0.0 */ export * as HttpTraceContext from "./HttpTraceContext.js" +/** + * @since 4.0.0 + */ +export * as Multipart from "./Multipart.js" + +/** + * @since 4.0.0 + */ +export * as Multipasta from "./Multipasta.js" + +/** + * @since 4.0.0 + */ +export * as Template from "./Template.js" + /** * @since 4.0.0 */ diff --git a/packages/effect/test/ManagedRuntime.test.ts b/packages/effect/test/ManagedRuntime.test.ts new file mode 100644 index 0000000000..dbea6a6726 --- /dev/null +++ b/packages/effect/test/ManagedRuntime.test.ts @@ -0,0 +1,49 @@ +import { describe, it, test } from "@effect/vitest" +import { strictEqual } from "@effect/vitest/utils" +import { Effect, Layer, ManagedRuntime, ServiceMap } from "effect" + +describe("ManagedRuntime", () => { + test("memoizes the layer build", async () => { + let count = 0 + const layer = Layer.effectDiscard(Effect.sync(() => { + count++ + })) + const runtime = ManagedRuntime.make(layer) + await runtime.runPromise(Effect.void) + await runtime.runPromise(Effect.void) + await runtime.dispose() + strictEqual(count, 1) + }) + + test("provides context", async () => { + const tag = ServiceMap.Key("string") + const layer = Layer.succeed(tag, "test") + const runtime = ManagedRuntime.make(layer) + const result = await runtime.runPromise(tag.asEffect()) + await runtime.dispose() + strictEqual(result, "test") + }) + + test("allows sharing a MemoMap", async () => { + let count = 0 + const layer = Layer.effectDiscard(Effect.sync(() => { + count++ + })) + const runtimeA = ManagedRuntime.make(layer) + const runtimeB = ManagedRuntime.make(layer, { memoMap: runtimeA.memoMap }) + await runtimeA.runPromise(Effect.void) + await runtimeB.runPromise(Effect.void) + await runtimeA.dispose() + await runtimeB.dispose() + strictEqual(count, 1) + }) + + it("can be built synchronously", () => { + const tag = ServiceMap.Key("string") + const layer = Layer.succeed(tag, "test") + const managedRuntime = ManagedRuntime.make(layer) + const services = Effect.runSync(managedRuntime.servicesEffect) + const result = ServiceMap.get(services, tag) + strictEqual(result, "test") + }) +}) diff --git a/packages/effect/test/config/Config.test.ts b/packages/effect/test/config/Config.test.ts index 1c53d94c6c..743795e346 100644 --- a/packages/effect/test/config/Config.test.ts +++ b/packages/effect/test/config/Config.test.ts @@ -27,7 +27,7 @@ const assertConfigErrors = ( ) => { const configProvider = ConfigProvider.fromEnv({ environment: env }) const result = Effect.runSyncExit(config.parse(configProvider.context())) - assertFailure(result, Cause.fromFailures(errors.flatMap((e) => Cause.fail(e).failures))) + assertFailure(result, Cause.fromFailures(errors.map(Cause.failureFail))) } const assertConfig = ( diff --git a/packages/effect/test/http/Multipart.test.ts b/packages/effect/test/http/Multipart.test.ts new file mode 100644 index 0000000000..f8c2d8bc7f --- /dev/null +++ b/packages/effect/test/http/Multipart.test.ts @@ -0,0 +1,39 @@ +import { describe, it } from "@effect/vitest" +import { deepStrictEqual } from "@effect/vitest/utils" +import { Effect, identity, Stream, Unify } from "effect" +import * as Multipart from "effect/unstable/http/Multipart" + +describe("Multipart", () => { + it.effect("it parses", () => + Effect.gen(function*() { + const data = new globalThis.FormData() + data.append("foo", "bar") + data.append("test", "ing") + data.append("file", new globalThis.File(["A".repeat(1024 * 1024)], "foo.txt", { type: "text/plain" })) + const response = new Response(data) + + const parts = yield* Stream.fromReadableStream({ + evaluate: () => response.body!, + onError: identity + }).pipe( + Stream.pipeThroughChannel(Multipart.makeChannel(Object.fromEntries(response.headers))), + Stream.mapEffect((part) => { + return Unify.unify( + part._tag === "File" ? + Effect.zip( + Effect.succeed(part.name), + Stream.mkString(Stream.decodeText(part.content)) + ) : + Effect.succeed([part.key, part.value] as const) + ) + }), + Stream.runCollect + ) + + deepStrictEqual(parts, [ + ["foo", "bar"], + ["test", "ing"], + ["foo.txt", "A".repeat(1024 * 1024)] + ]) + })) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a04f62c83f..aa3dc8abb7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -184,6 +184,12 @@ importers: fast-check: specifier: ^4.2.0 version: 4.2.0 + find-my-way-ts: + specifier: ^0.1.6 + version: 0.1.6 + multipasta: + specifier: ^0.2.5 + version: 0.2.5 devDependencies: '@types/node': specifier: ^24.0.12 @@ -2274,6 +2280,9 @@ packages: resolution: {integrity: sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==} engines: {node: '>=8'} + find-my-way-ts@0.1.6: + resolution: {integrity: sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA==} + find-up@3.0.0: resolution: {integrity: sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==} engines: {node: '>=6'} @@ -2977,6 +2986,9 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + multipasta@0.2.5: + resolution: {integrity: sha512-c8eMDb1WwZcE02WVjHoOmUVk7fnKU/RmUcosHACglrWAuPQsEJv+E8430sXj6jNc1jHw0zrS16aCjQh4BcEb4A==} + nanoid@3.3.11: resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -6318,6 +6330,8 @@ snapshots: make-dir: 3.1.0 pkg-dir: 4.2.0 + find-my-way-ts@0.1.6: {} + find-up@3.0.0: dependencies: locate-path: 3.0.0 @@ -7052,6 +7066,8 @@ snapshots: ms@2.1.3: {} + multipasta@0.2.5: {} + nanoid@3.3.11: {} napi-postinstall@0.2.4: {}