From adfa56d73bec76a66dcd63a6a64dbffb136dbd1a Mon Sep 17 00:00:00 2001 From: Tim Date: Fri, 21 Mar 2025 14:20:00 +0100 Subject: [PATCH] add RcMap & LayerMap (#68) --- src/Cause.ts | 33 ++++ src/Context.ts | 23 +-- src/Effect.ts | 98 ++++++++++ src/Layer.ts | 15 +- src/LayerMap.ts | 396 ++++++++++++++++++++++++++++++++++++++++ src/RcMap.ts | 352 +++++++++++++++++++++++++++++++++++ src/index.ts | 26 +++ src/internal/context.ts | 30 ++- src/internal/effect.ts | 33 ++++ test/RcMap.test.ts | 177 ++++++++++++++++++ 10 files changed, 1150 insertions(+), 33 deletions(-) create mode 100644 src/LayerMap.ts create mode 100644 src/RcMap.ts create mode 100644 test/RcMap.test.ts diff --git a/src/Cause.ts b/src/Cause.ts index f02bebff9a..a46c98d814 100644 --- a/src/Cause.ts +++ b/src/Cause.ts @@ -266,3 +266,36 @@ export interface IllegalArgumentError extends YieldableError { * @category errors */ export const IllegalArgumentError: new(message?: string) => IllegalArgumentError = effect.IllegalArgumentError + +/** + * @since 4.0.0 + * @category errors + */ +export const ExceededCapacityErrorTypeId: unique symbol = effect.ExceededCapacityErrorTypeId + +/** + * @since 4.0.0 + * @category errors + */ +export type ExceededCapacityErrorTypeId = typeof ExceededCapacityErrorTypeId + +/** + * @since 4.0.0 + * @category errors + */ +export const isExceededCapacityError: (u: unknown) => u is ExceededCapacityError = effect.isExceededCapacityError + +/** + * @since 4.0.0 + * @category errors + */ +export interface ExceededCapacityError extends YieldableError { + readonly [ExceededCapacityErrorTypeId]: ExceededCapacityErrorTypeId + readonly _tag: "ExceededCapacityError" +} + +/** + * @since 4.0.0 + * @category errors + */ +export const ExceededCapacityError: new(message?: string) => ExceededCapacityError = effect.ExceededCapacityError diff --git a/src/Context.ts b/src/Context.ts index 76b8dd85ae..f31b97dc88 100644 --- a/src/Context.ts +++ b/src/Context.ts @@ -153,12 +153,6 @@ const TypeId: unique symbol = internal.TypeId as TypeId */ export type TypeId = typeof TypeId -/** - * @since 2.0.0 - * @category models - */ -export type ValidTagsById = R extends infer S ? Tag : never - /** * @since 2.0.0 * @category models @@ -317,8 +311,8 @@ export const add: { * @category getters */ export const get: { - | Tag>(tag: T): (self: Context) => Tag.Service - | Tag>(self: Context, tag: T): Tag.Service + (tag: Tag): (self: Context) => S + (self: Context, tag: Tag): S } = internal.get /** @@ -446,17 +440,16 @@ export const merge: { * * @since 2.0.0 */ -export const pick: >>( - ...tags: S -) => (self: Context) => Context<{ [k in keyof S]: Tag.Identifier }[number]> = internal.pick +export const pick: >>( + ...tags: Tags +) => (self: Context) => Context> = internal.pick /** * @since 2.0.0 */ -export const omit: >>( - ...tags: S -) => (self: Context) => Context }[keyof S]>> = - internal.omit +export const omit: >>( + ...tags: Tags +) => (self: Context) => Context>> = internal.omit /** * @example diff --git a/src/Effect.ts b/src/Effect.ts index 6df538b4ff..a3e9e49da1 100644 --- a/src/Effect.ts +++ b/src/Effect.ts @@ -3,6 +3,7 @@ */ import type * as Arr from "./Array.js" import type * as Cause from "./Cause.js" +import type { Clock } from "./Clock.js" import * as Context from "./Context.js" import type { DurationInput } from "./Duration.js" import type * as Either from "./Either.js" @@ -3525,6 +3526,61 @@ export const service: (tag: Context.Tag) => Effect = in */ export const serviceOption: (tag: Context.Tag) => Effect> = internal.serviceOption +/** + * Provides part of the required context while leaving the rest unchanged. + * + * **Details** + * + * This function allows you to transform the context required by an effect, + * providing part of the context and leaving the rest to be fulfilled later. + * + * **Example** + * + * ```ts + * import { Context, Effect } from "effect" + * + * class Service1 extends Context.Tag("Service1")() {} + * class Service2 extends Context.Tag("Service2")() {} + * + * const program = Effect.gen(function*() { + * const service1 = yield* Service1 + * console.log(service1.port) + * const service2 = yield* Service2 + * console.log(service2.connection) + * return "some result" + * }) + * + * // ┌─── Effect + * // ▼ + * const programWithService1 = Effect.updateContext( + * program, + * (ctx: Context.Context) => Context.add(ctx, Service1, { port: 3000 }) + * ) + * + * const runnable = programWithService1.pipe( + * Effect.provideService(Service2, { connection: "localhost" }), + * Effect.provideService(Service1, { port: 3001 }) + * ) + * + * Effect.runPromise(runnable) + * // Output: + * // 3000 + * // localhost + * ``` + * + * @since 4.0.0 + * @category Context + */ +export const updateContext: { + ( + f: (context: Context.Context) => Context.Context> + ): (self: Effect) => Effect + ( + self: Effect, + f: (context: Context.Context) => Context.Context> + ): Effect +} = internal.updateContext + /** * Updates the service with the required service entry. * @@ -4026,6 +4082,18 @@ export const uninterruptibleMask: ( f: (restore: (effect: Effect) => Effect) => Effect ) => Effect = internal.uninterruptibleMask +/** + * This function behaves like {@link interruptible}, but it also provides a + * `restore` function. This function can be used to restore the interruptibility + * of any specific region of code. + * + * @since 2.0.0 + * @category Interruption + */ +export const interruptibleMask: ( + f: (restore: (effect: Effect) => Effect) => Effect +) => Effect = internal.interruptibleMask + // ----------------------------------------------------------------------------- // Semaphore // ----------------------------------------------------------------------------- @@ -5411,6 +5479,36 @@ export namespace fn { */ export const fnUntraced: fn.Gen = internal.fnUntraced +// ======================================================================== +// Clock +// ======================================================================== + +/** + * Retrieves the `Clock` service from the context and provides it to the + * specified effectful function. + * + * **Example** + * + * ```ts + * import { Console, Effect } from "effect" + * + * const program = Effect.clockWith((clock) => + * clock.currentTimeMillis.pipe( + * Effect.map((currentTime) => `Current time is: ${currentTime}`), + * Effect.tap(Console.log) + * ) + * ) + * + * Effect.runFork(program) + * // Example Output: + * // Current time is: 1735484929744 + * ``` + * + * @since 2.0.0 + * @category Clock + */ +export const clockWith: (f: (clock: Clock) => Effect) => Effect = internal.clockWith + // ======================================================================== // Logging // ======================================================================== diff --git a/src/Layer.ts b/src/Layer.ts index 8cde915bee..329ec8f8fc 100644 --- a/src/Layer.ts +++ b/src/Layer.ts @@ -249,6 +249,14 @@ export const unsafeMakeMemoMap = (): MemoMap => new MemoMapImpl() */ export const makeMemoMap: Effect = internalEffect.sync(unsafeMakeMemoMap) +/** + * @since 3.13.0 + * @category models + */ +export class CurrentMemoMap extends Context.Reference("effect/Layer/CurrentMemoMap", { + defaultValue: unsafeMakeMemoMap +}) {} + /** * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. @@ -270,7 +278,12 @@ export const buildWithMemoMap: { self: Layer, memoMap: MemoMap, scope: Scope.Scope -): Effect, E, RIn> => self.build(memoMap, scope)) +): Effect, E, RIn> => + internalEffect.provideService( + self.build(memoMap, scope), + CurrentMemoMap, + memoMap + )) /** * Builds a layer into a scoped value. diff --git a/src/LayerMap.ts b/src/LayerMap.ts new file mode 100644 index 0000000000..22ac9f2bed --- /dev/null +++ b/src/LayerMap.ts @@ -0,0 +1,396 @@ +/** + * @since 3.14.0 + * @experimental + */ +import * as Context from "./Context.js" +import type * as Duration from "./Duration.js" +import * as Effect from "./Effect.js" +import { identity } from "./Function.js" +import * as Layer from "./Layer.js" +import * as RcMap from "./RcMap.js" +import * as Scope from "./Scope.js" +import type { Mutable } from "./Types.js" + +/** + * @since 3.14.0 + * @category Symbols + */ +export const TypeId: unique symbol = Symbol.for("effect/LayerMap") + +/** + * @since 3.14.0 + * @category Symbols + */ +export type TypeId = typeof TypeId + +/** + * @since 3.14.0 + * @category Models + * @experimental + */ +export interface LayerMap { + readonly [TypeId]: TypeId + + /** + * The internal RcMap that stores the resources. + */ + readonly rcMap: RcMap.RcMap, S], E> + + /** + * Retrieves an instance of the resource associated with the key. + */ + get(key: K): Effect.Effect + + /** + * Provides an instance of the resource associated with the key + * to the given effect. + */ + provide(key: K): (effect: Effect.Effect) => Effect.Effect> + + /** + * Invalidates the resource associated with the key. + */ + invalidate(key: K): Effect.Effect +} + +/** + * @since 3.14.0 + * @category Constructors + * @experimental + * + * A `LayerMap` allows you to create a map of Layer's that can be used to + * dynamically access resources based on a key. + * + * ```ts + * import { Completions } from "@effect/ai" + * import { OpenAiClient, OpenAiCompletions } from "@effect/ai-openai" + * import { FetchHttpClient } from "@effect/platform" + * import { NodeRuntime } from "@effect/platform-node" + * import { Config, Effect, Layer, LayerMap } from "effect" + * + * // create the openai client layer + * const OpenAiLayer = OpenAiClient.layerConfig({ + * apiKey: Config.redacted("OPENAI_API_KEY") + * }).pipe(Layer.provide(FetchHttpClient.layer)) + * + * // create a service that wraps a LayerMap + * class AiClients extends LayerMap.Service()("AiClients", { + * // this LayerMap will provide the ai Completions service + * provides: Completions.Completions, + * + * // define the lookup function for the layer map + * // + * // The returned Layer will be used to provide the Completions service for the + * // given model. + * lookup: (model: OpenAiCompletions.Model) => OpenAiCompletions.layer({ model }), + * + * // If a layer is not used for a certain amount of time, it can be removed + * idleTimeToLive: "5 seconds", + * + * // Supply the dependencies for the layers in the LayerMap + * dependencies: [OpenAiLayer] + * }) {} + * + * // usage + * Effect.gen(function*() { + * // access and use the generic Completions service + * const ai = yield* Completions.Completions + * const response = yield* ai.create("Hello, world!") + * console.log(response.text) + * }).pipe( + * // use the AiClients service to provide a variant of the Completions service + * AiClients.provide("gpt-4o"), + * // provide the LayerMap service + * Effect.provide(AiClients.Default), + * NodeRuntime.runMain + * ) + * ``` + */ +export const make: < + Accessor extends Context.Tag | Effect.Effect, + K, + L extends Layer.Layer, Scope.Scope>, any, any> +>( + tagOrAccessor: Accessor, + lookup: (key: K) => L, + options?: { + readonly idleTimeToLive?: Duration.DurationInput | undefined + } | undefined +) => Effect.Effect< + LayerMap< + K, + Exclude, Scope.Scope>, + Effect.Effect.Success, + Effect.Effect.Error | (L extends Layer.Layer ? _E : never) + >, + never, + Scope.Scope | (L extends Layer.Layer ? _R : never) +> = Effect.fnUntraced(function*( + tagOrAccessor: Effect.Effect | Context.Tag, + lookup: (key: K) => Layer.Layer, EL, RL>, + options?: { + readonly idleTimeToLive?: Duration.DurationInput | undefined + } | undefined +) { + const context = yield* Effect.context() + + // If we are inside another layer build, use the current memo map, + // otherwise create a new one. + const memoMap = context.unsafeMap.has(Layer.CurrentMemoMap.key) + ? Context.get(context, Layer.CurrentMemoMap) + : yield* Layer.makeMemoMap + + const rcMap = yield* RcMap.make({ + lookup: Effect.fnUntraced(function*(key: K) { + const scope = yield* Effect.scope + const context = yield* (Layer.buildWithMemoMap(lookup(key), memoMap, scope) as Effect.Effect< + Context.Context> + >) + const service = yield* (Effect.provide(tagOrAccessor.asEffect(), context) as Effect.Effect) + return [context, service] as const + }), + idleTimeToLive: options?.idleTimeToLive + }) + + return identity, S, any>>({ + [TypeId]: TypeId, + rcMap: rcMap as any, + get: (key) => Effect.map(RcMap.get(rcMap, key), ([, service]) => service), + provide: (key) => (effect) => + Effect.scopedWith((scope) => + Effect.flatMap( + Scope.provide(RcMap.get(rcMap, key), scope), + ([context]) => Effect.provide(effect, context) + ) + ), + invalidate: (key) => RcMap.invalidate(rcMap, key) + }) +}) + +/** + * @since 3.14.0 + * @category Constructors + * @experimental + */ +export const fromRecord = < + Accessor extends Context.Tag | Effect.Effect, + const Layers extends Record, Scope.Scope>, any, any>> +>( + tagOrAccessor: Accessor, + layers: Layers, + options?: { + readonly idleTimeToLive?: Duration.DurationInput | undefined + } | undefined +): Effect.Effect< + LayerMap< + keyof Layers, + Exclude, Scope.Scope>, + Effect.Effect.Success, + | Effect.Effect.Error + | (Layers[keyof Layers] extends Layer.Layer ? _E : never) + >, + never, + Scope.Scope | (Layers[keyof Layers] extends Layer.Layer ? _R : never) +> => make(tagOrAccessor, (key: keyof Layers) => layers[key], options) + +/** + * @since 3.14.0 + * @category Service + */ +export interface TagClass< + in out Self, + in out Id extends string, + in out K, + in out I, + in out S, + in out E, + in out R, + in out Deps extends Layer.Layer +> extends Context.TagClass> { + /** + * A default layer for the `LayerMap` service. + */ + readonly layer: Layer.Layer< + Self, + (Deps extends Layer.Layer ? _E : never), + | Exclude ? _A : never)> + | (Deps extends Layer.Layer ? _R : never) + > + + /** + * A default layer for the `LayerMap` service without the dependencies provided. + */ + readonly layerNoDeps: Layer.Layer + + /** + * Retrieves an instance of the resource associated with the key. + */ + readonly get: (key: K) => Effect.Effect + + /** + * Provides an instance of the resource associated with the key to the given + * effect. + */ + readonly provide: ( + key: K + ) => (effect: Effect.Effect) => Effect.Effect | Self> + + /** + * Invalidates the resource associated with the key. + */ + readonly invalidate: (key: K) => Effect.Effect +} + +/** + * @since 3.14.0 + * @category Service + * @experimental + * + * Create a `LayerMap` service that provides a dynamic set of resources based on + * a key. + * + * ```ts + * import { Completions } from "@effect/ai" + * import { OpenAiClient, OpenAiCompletions } from "@effect/ai-openai" + * import { FetchHttpClient } from "@effect/platform" + * import { NodeRuntime } from "@effect/platform-node" + * import { Config, Effect, Layer, LayerMap } from "effect" + * + * // create the openai client layer + * const OpenAiLayer = OpenAiClient.layerConfig({ + * apiKey: Config.redacted("OPENAI_API_KEY") + * }).pipe(Layer.provide(FetchHttpClient.layer)) + * + * // create a service that wraps a LayerMap + * class AiClients extends LayerMap.Service()("AiClients", { + * // this LayerMap will provide the ai Completions service + * provides: Completions.Completions, + * + * // define the lookup function for the layer map + * // + * // The returned Layer will be used to provide the Completions service for the + * // given model. + * lookup: (model: OpenAiCompletions.Model) => OpenAiCompletions.layer({ model }), + * + * // If a layer is not used for a certain amount of time, it can be removed + * idleTimeToLive: "5 seconds", + * + * // Supply the dependencies for the layers in the LayerMap + * dependencies: [OpenAiLayer] + * }) {} + * + * // usage + * Effect.gen(function*() { + * // access and use the generic Completions service + * const ai = yield* Completions.Completions + * const response = yield* ai.create("Hello, world!") + * console.log(response.text) + * }).pipe( + * // use the AiClients service to provide a variant of the Completions service + * AiClients.provide("gpt-4o"), + * // provide the LayerMap service + * Effect.provide(AiClients.Default), + * NodeRuntime.runMain + * ) + * ``` + */ +export const Service = () => +< + const Id extends string, + Accessor extends Context.Tag | Effect.Effect, + Lookup extends { + readonly lookup: (key: any) => Layer.Layer, Scope.Scope>, any, any> + } | { + readonly layers: Record, Scope.Scope>, any, any>> + }, + const Deps extends ReadonlyArray> = [] +>( + id: Id, + options: Lookup & { + readonly provides: Accessor + readonly dependencies?: Deps | undefined + readonly idleTimeToLive?: Duration.DurationInput | undefined + } +): TagClass< + Self, + Id, + Lookup extends { readonly lookup: (key: infer K) => any } ? K + : Lookup extends { readonly layers: infer Layers } ? keyof Layers + : never, + Exclude, Scope.Scope>, + Effect.Effect.Success, + Effect.Effect.Error | Service.Error, + Service.Context, + Deps[number] +> => { + const Err = globalThis.Error as any + const limit = Err.stackTraceLimit + Err.stackTraceLimit = 2 + const creationError = new Err() + Err.stackTraceLimit = limit + + function TagClass() {} + const TagClass_ = TagClass as any as Mutable> + Object.setPrototypeOf(TagClass, Object.getPrototypeOf(Context.GenericTag(id))) + TagClass.key = id + Object.defineProperty(TagClass, "stack", { + get() { + return creationError.stack + } + }) + TagClass_.get = (key: string) => Effect.flatMap(TagClass_.asEffect(), (layerMap) => layerMap.get(key)) + TagClass_.provide = (key: string) => (effect) => + Effect.flatMap(TagClass_.asEffect(), (layerMap) => layerMap.provide(key)(effect)) + TagClass_.invalidate = (key: string) => Effect.flatMap(TagClass_.asEffect(), (layerMap) => layerMap.invalidate(key)) + + TagClass_.layerNoDeps = Layer.effect( + TagClass_, + "lookup" in options + ? make(options.provides, options.lookup, options) as any + : fromRecord(options.provides, options.layers as any, options) + ) + TagClass_.layer = options.dependencies && options.dependencies.length > 0 ? + Layer.provide(TagClass_.layerNoDeps, options.dependencies as any) : + TagClass_.layerNoDeps + + return TagClass as any +} + +/** + * @since 3.14.0 + * @category Service + * @experimental + */ +export declare namespace Service { + /** + * @since 3.14.0 + * @category Service + * @experimental + */ + export type Key = Options extends { readonly lookup: (key: infer K) => any } ? K + : Options extends { readonly layers: infer Layers } ? keyof Layers + : never + + /** + * @since 3.14.0 + * @category Service + * @experimental + */ + export type Layers = Options extends { readonly lookup: (key: infer _K) => infer Layers } ? Layers + : Options extends { readonly layers: infer Layers } ? Layers[keyof Layers] + : never + + /** + * @since 3.14.0 + * @category Service + * @experimental + */ + export type Error = Layers extends Layer.Layer ? _E : never + + /** + * @since 3.14.0 + * @category Service + * @experimental + */ + export type Context = Layers extends Layer.Layer ? _R : never +} diff --git a/src/RcMap.ts b/src/RcMap.ts new file mode 100644 index 0000000000..eef3867100 --- /dev/null +++ b/src/RcMap.ts @@ -0,0 +1,352 @@ +/** + * @since 3.5.0 + */ +import * as Cause from "./Cause.js" +import * as Context from "./Context.js" +import * as Deferred from "./Deferred.js" +import * as Duration from "./Duration.js" +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 MutableHashMap from "./MutableHashMap.js" +import type { Pipeable } from "./Pipeable.js" +import { pipeArguments } from "./Pipeable.js" +import * as Scope from "./Scope.js" + +/** + * @since 3.5.0 + * @category type ids + */ +export const TypeId: unique symbol = Symbol.for("effect/RcMap") + +/** + * @since 3.5.0 + * @category type ids + */ +export type TypeId = typeof TypeId + +/** + * @since 3.5.0 + * @category models + */ +export interface RcMap extends Pipeable { + readonly [TypeId]: TypeId + readonly lookup: (key: K) => Effect.Effect + readonly context: Context.Context + readonly scope: Scope.Scope + readonly idleTimeToLive: Duration.Duration | undefined + readonly capacity: number + readonly semaphore: Effect.Semaphore + state: State +} + +/** + * @since 4.0.0 + * @category Models + */ +export type State = State.Open | State.Closed + +/** + * @since 4.0.0 + * @category Models + */ +export declare namespace State { + /** + * @since 4.0.0 + * @category Models + */ + export interface Open { + readonly _tag: "Open" + readonly map: MutableHashMap.MutableHashMap> + } + + /** + * @since 4.0.0 + * @category Models + */ + export interface Closed { + readonly _tag: "Closed" + } + + /** + * @since 4.0.0 + * @category Models + */ + export interface Entry { + readonly deferred: Deferred.Deferred + readonly scope: Scope.Scope.Closeable + readonly finalizer: Effect.Effect + fiber: Fiber.Fiber | undefined + expiresAt: number + refCount: number + } +} + +const unsafeMake = (options: { + readonly lookup: (key: K) => Effect.Effect + readonly context: Context.Context + readonly scope: Scope.Scope + readonly idleTimeToLive: Duration.Duration | undefined + readonly capacity: number +}): RcMap => ({ + [TypeId]: TypeId, + lookup: options.lookup, + context: options.context, + scope: options.scope, + idleTimeToLive: options.idleTimeToLive, + capacity: options.capacity, + semaphore: Effect.unsafeMakeSemaphore(1), + state: { + _tag: "Open", + map: MutableHashMap.empty() + }, + pipe() { + return pipeArguments(this, arguments) + } +}) + +/** + * An `RcMap` can contain multiple reference counted resources that can be indexed + * by a key. The resources are lazily acquired on the first call to `get` and + * released when the last reference is released. + * + * Complex keys can extend `Equal` and `Hash` to allow lookups by value. + * + * **Options** + * + * - `capacity`: The maximum number of resources that can be held in the map. + * - `idleTimeToLive`: When the reference count reaches zero, the resource will be released after this duration. + * + * @since 3.5.0 + * @category models + * @example + * ```ts + * import { Effect, RcMap } from "effect" + * + * Effect.gen(function*() { + * const map = yield* RcMap.make({ + * lookup: (key: string) => + * Effect.acquireRelease( + * Effect.succeed(`acquired ${key}`), + * () => Effect.log(`releasing ${key}`) + * ) + * }) + * + * // Get "foo" from the map twice, which will only acquire it once. + * // It will then be released once the scope closes. + * yield* RcMap.get(map, "foo").pipe( + * Effect.andThen(RcMap.get(map, "foo")), + * Effect.scoped + * ) + * }) + * ``` + */ +export const make: { + (options: { + readonly lookup: (key: K) => Effect.Effect + readonly idleTimeToLive?: Duration.DurationInput | undefined + readonly capacity?: undefined + }): Effect.Effect, never, Scope.Scope | R> + (options: { + readonly lookup: (key: K) => Effect.Effect + readonly idleTimeToLive?: Duration.DurationInput | undefined + readonly capacity: number + }): Effect.Effect, never, Scope.Scope | R> +} = (options: { + readonly lookup: (key: K) => Effect.Effect + readonly idleTimeToLive?: Duration.DurationInput | undefined + readonly capacity?: number | undefined +}) => + Effect.withFiber, never, R | Scope.Scope>((fiber) => { + const context = fiber.context as Context.Context + const scope = Context.get(context, Scope.Scope) + const self = unsafeMake({ + lookup: options.lookup as any, + context, + scope, + idleTimeToLive: options.idleTimeToLive ? Duration.decode(options.idleTimeToLive) : undefined, + capacity: Math.max(options.capacity ?? Number.POSITIVE_INFINITY, 0) + }) + return Effect.as( + Scope.addFinalizer(scope, () => + Effect.suspend(() => { + if (self.state._tag === "Closed") { + return Effect.void + } + const map = self.state.map + self.state = { _tag: "Closed" } + return Effect.forEach( + map, + ([, entry]) => Scope.close(entry.scope, Exit.void) + ).pipe( + Effect.tap(() => { + MutableHashMap.clear(map) + }), + self.semaphore.withPermits(1) + ) + })), + self + ) + }) + +/** + * @since 3.5.0 + * @category combinators + */ +export const get: { + (key: K): (self: RcMap) => Effect.Effect + (self: RcMap, key: K): Effect.Effect +} = dual(2, (self: RcMap, key: K): Effect.Effect => { + return Effect.uninterruptibleMask((restore) => getImpl(self, key, restore as any)) +}) + +const getImpl = Effect.fnUntraced(function*(self: RcMap, key: K, restore: (a: A) => A) { + if (self.state._tag === "Closed") { + return yield* Effect.interrupt + } + const state = self.state + const o = MutableHashMap.get(state.map, key) + let entry: State.Entry + if (o._tag === "Some") { + entry = o.value + entry.refCount++ + } else if (Number.isFinite(self.capacity) && MutableHashMap.size(self.state.map) >= self.capacity) { + return yield* Effect.fail( + new Cause.ExceededCapacityError(`RcMap attempted to exceed capacity of ${self.capacity}`) + ) as Effect.Effect + } else { + entry = yield* self.semaphore.withPermits(1)(acquire(self, key, restore)) + } + const scope = yield* Scope.Scope + yield* Scope.addFinalizer(scope, () => entry.finalizer) + return yield* restore(Deferred.await(entry.deferred)) +}) + +const acquire = Effect.fnUntraced(function*(self: RcMap, key: K, restore: (a: A) => A) { + const scope = Scope.unsafeMake() + const deferred = Deferred.unsafeMake() + const acquire = self.lookup(key) + const contextMap = new Map(self.context.unsafeMap) + yield* restore(Effect.updateContext( + acquire as Effect.Effect, + (inputContext: Context.Context) => { + inputContext.unsafeMap.forEach((value, key) => { + contextMap.set(key, value) + }) + contextMap.set(Scope.Scope.key, scope) + return Context.unsafeMake(contextMap) + } + )).pipe( + Effect.exit, + Effect.flatMap((exit) => Deferred.done(deferred, exit)), + Effect.forkIn(scope) + ) + const entry: State.Entry = { + deferred, + scope, + finalizer: undefined as any, + fiber: undefined, + expiresAt: 0, + refCount: 1 + } + ;(entry as any).finalizer = release(self, key, entry) + if (self.state._tag === "Open") { + MutableHashMap.set(self.state.map, key, entry) + } + return entry +}) + +const release = (self: RcMap, key: K, entry: State.Entry) => + Effect.clockWith((clock) => { + entry.refCount-- + if (entry.refCount > 0) { + return Effect.void + } else if ( + self.state._tag === "Closed" + || !MutableHashMap.has(self.state.map, key) + || self.idleTimeToLive === undefined + ) { + if (self.state._tag === "Open") { + MutableHashMap.remove(self.state.map, key) + } + return Scope.close(entry.scope, Exit.void) + } + + if (!Duration.isFinite(self.idleTimeToLive)) { + return Effect.void + } + + entry.expiresAt = clock.unsafeCurrentTimeMillis() + Duration.toMillis(self.idleTimeToLive) + if (entry.fiber) return Effect.void + + return Effect.interruptibleMask(function loop(restore): Effect.Effect { + const now = clock.unsafeCurrentTimeMillis() + const remaining = entry.expiresAt - now + if (remaining <= 0) { + if (self.state._tag === "Closed" || entry.refCount > 0) return Effect.void + MutableHashMap.remove(self.state.map, key) + return restore(Scope.close(entry.scope, Exit.void)) + } + return Effect.flatMap(clock.sleep(Duration.millis(remaining)), () => loop(restore)) + }).pipe( + Effect.ensuring(Effect.sync(() => { + entry.fiber = undefined + })), + Effect.forkIn(self.scope), + Effect.tap((fiber) => { + entry.fiber = fiber + }), + self.semaphore.withPermits(1) + ) + }) + +/** + * @since 3.5.0 + * @category combinators + */ +export const keys = (self: RcMap): Effect.Effect> => { + return Effect.suspend(() => + self.state._tag === "Closed" ? Effect.interrupt : Effect.succeed(MutableHashMap.keys(self.state.map)) + ) +} + +/** + * @since 3.5.0 + * @category combinators + */ +export const invalidate: { + (key: K): (self: RcMap) => Effect.Effect + (self: RcMap, key: K): Effect.Effect +} = dual( + 2, + Effect.fnUntraced(function*(self: RcMap, key: K) { + if (self.state._tag === "Closed") return + const o = MutableHashMap.get(self.state.map, key) + if (o._tag === "None") return + const entry = o.value + MutableHashMap.remove(self.state.map, key) + if (entry.refCount > 0) return + yield* Scope.close(entry.scope, Exit.void) + if (entry.fiber) yield* Fiber.interrupt(entry.fiber) + }) +) + +/** + * @since 3.5.0 + * @category combinators + */ +export const touch: { + (key: K): (self: RcMap) => Effect.Effect + (self: RcMap, key: K): Effect.Effect +} = dual( + 2, + (self: RcMap, key: K) => + Effect.clockWith((clock) => { + if (!self.idleTimeToLive || self.state._tag === "Closed") return Effect.void + const o = MutableHashMap.get(self.state.map, key) + if (o._tag === "None") return Effect.void + o.value.expiresAt = clock.unsafeCurrentTimeMillis() + Duration.toMillis(self.idleTimeToLive) + return Effect.void + }) +) diff --git a/src/index.ts b/src/index.ts index 529a4678eb..3ee247ffd1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,8 @@ +/** + * @since 3.10.0 + */ +export * as Arbitrary from "./Arbitrary.js" + /** * This module provides utility functions for working with arrays in TypeScript. * @@ -161,6 +166,11 @@ export * as Equivalence from "./Equivalence.js" */ export * as Exit from "./Exit.js" +/** + * @since 3.10.0 + */ +export * as FastCheck from "./FastCheck.js" + /** * @since 2.0.0 */ @@ -214,6 +224,12 @@ export * as Iterable from "./Iterable.js" */ export * as Layer from "./Layer.js" +/** + * @since 3.14.0 + * @experimental + */ +export * as LayerMap from "./LayerMap.js" + /** * @since 2.0.0 */ @@ -303,6 +319,11 @@ export * as Pipeable from "./Pipeable.js" */ export * as Predicate from "./Predicate.js" +/** + * @since 3.10.0 + */ +export * as Pretty from "./Pretty.js" + /** * @since 2.0.0 */ @@ -323,6 +344,11 @@ export * as Pull from "./Pull.js" */ export * as Queue from "./Queue.js" +/** + * @since 3.5.0 + */ +export * as RcMap from "./RcMap.js" + /** * @since 3.5.0 */ diff --git a/src/internal/context.ts b/src/internal/context.ts index e739f09238..0c94511880 100644 --- a/src/internal/context.ts +++ b/src/internal/context.ts @@ -252,13 +252,13 @@ export const unsafeGet = dual< /** @internal */ export const get: { - | C.Tag>( - tag: T - ): (self: C.Context) => C.Tag.Service - | C.Tag>( + ( + tag: C.Tag + ): (self: C.Context) => S + ( self: C.Context, - tag: T - ): C.Tag.Service + tag: C.Tag + ): S } = unsafeGet as any /** @internal */ @@ -310,10 +310,10 @@ export const merge = dual< }) /** @internal */ -export const pick = >>(...tags: S) => -( +export const pick = >>(...tags: Tags) => +( self: C.Context -): C.Context<{ [k in keyof S]: C.Tag.Identifier }[number]> => { +): C.Context> => { const tagSet = new Set(tags.map((_) => _.key)) const newEnv = new Map() for (const [tag, s] of self.unsafeMap.entries()) { @@ -321,18 +321,14 @@ export const pick = >>(...ta newEnv.set(tag, s) } } - return makeContext<{ [k in keyof S]: C.Tag.Identifier }[number]>( - newEnv - ) + return makeContext(newEnv) } /** @internal */ -export const omit = >>(...tags: S) => -( +export const omit = >>(...tags: Tags) => +( self: C.Context -): C.Context< - Exclude }[keyof S]> -> => { +): C.Context>> => { const newEnv = new Map(self.unsafeMap) for (const tag of tags) { newEnv.delete(tag.key) diff --git a/src/internal/effect.ts b/src/internal/effect.ts index 258e735ebb..ebe902adbc 100644 --- a/src/internal/effect.ts +++ b/src/internal/effect.ts @@ -2644,6 +2644,21 @@ export const uninterruptibleMask = ( return f(interruptible) }) +/** @internal */ +export const interruptibleMask = ( + f: ( + restore: ( + effect: Effect.Effect + ) => Effect.Effect + ) => Effect.Effect +): Effect.Effect => + withFiber((fiber) => { + if (fiber.interruptible) return f(identity) + fiber.interruptible = true + fiber._stack.push(setInterruptible(false)) + return f(uninterruptible) + }) + // ======================================================================== // collecting & elements // ======================================================================== @@ -3739,6 +3754,24 @@ export class IllegalArgumentError extends TaggedError("IllegalArgumentError") { } } +/** @internal */ +export const ExceededCapacityErrorTypeId: Cause.ExceededCapacityErrorTypeId = Symbol.for( + "effect/Cause/ExceededCapacityError" +) as Cause.ExceededCapacityErrorTypeId + +/** @internal */ +export const isExceededCapacityError = ( + u: unknown +): u is Cause.ExceededCapacityError => hasProperty(u, ExceededCapacityErrorTypeId) + +/** @internal */ +export class ExceededCapacityError extends TaggedError("ExceededCapacityError") { + readonly [ExceededCapacityErrorTypeId]: Cause.ExceededCapacityErrorTypeId = ExceededCapacityErrorTypeId + constructor(message?: string) { + super({ message } as any) + } +} + // ---------------------------------------------------------------------------- // Console // ---------------------------------------------------------------------------- diff --git a/test/RcMap.test.ts b/test/RcMap.test.ts new file mode 100644 index 0000000000..f6dccf687f --- /dev/null +++ b/test/RcMap.test.ts @@ -0,0 +1,177 @@ +import { Cause, Data, Effect, Exit, RcMap, Scope, TestClock } from "effect" +import { assert, describe, it } from "./utils/extend.js" + +describe("RcMap", () => { + it.effect("deallocation", () => + Effect.gen(function*() { + const acquired: Array = [] + const released: Array = [] + const mapScope = yield* Scope.make() + const map = yield* RcMap.make({ + lookup: (key: string) => + Effect.acquireRelease( + Effect.sync(() => { + acquired.push(key) + return key + }), + () => Effect.sync(() => released.push(key)) + ) + }).pipe( + Scope.provide(mapScope) + ) + + assert.deepStrictEqual(acquired, []) + assert.strictEqual(yield* Effect.scoped(RcMap.get(map, "foo")), "foo") + assert.deepStrictEqual(acquired, ["foo"]) + assert.deepStrictEqual(released, ["foo"]) + + const scopeA = yield* Scope.make() + const scopeB = yield* Scope.make() + yield* RcMap.get(map, "bar").pipe(Scope.provide(scopeA)) + yield* Effect.scoped(RcMap.get(map, "bar")) + yield* RcMap.get(map, "baz").pipe(Scope.provide(scopeB)) + yield* Effect.scoped(RcMap.get(map, "baz")) + assert.deepStrictEqual(acquired, ["foo", "bar", "baz"]) + assert.deepStrictEqual(released, ["foo"]) + yield* Scope.close(scopeB, Exit.void) + assert.deepStrictEqual(acquired, ["foo", "bar", "baz"]) + assert.deepStrictEqual(released, ["foo", "baz"]) + yield* Scope.close(scopeA, Exit.void) + assert.deepStrictEqual(acquired, ["foo", "bar", "baz"]) + assert.deepStrictEqual(released, ["foo", "baz", "bar"]) + + const scopeC = yield* Scope.make() + yield* RcMap.get(map, "qux").pipe(Scope.provide(scopeC)) + assert.deepStrictEqual(acquired, ["foo", "bar", "baz", "qux"]) + assert.deepStrictEqual(released, ["foo", "baz", "bar"]) + + yield* Scope.close(mapScope, Exit.void) + assert.deepStrictEqual(acquired, ["foo", "bar", "baz", "qux"]) + assert.deepStrictEqual(released, ["foo", "baz", "bar", "qux"]) + + const exit = yield* RcMap.get(map, "boom").pipe(Effect.scoped, Effect.exit) + assert.isTrue(Exit.hasInterrupt(exit)) + })) + + it.effect("idleTimeToLive", () => + Effect.gen(function*() { + const acquired: Array = [] + const released: Array = [] + const map = yield* RcMap.make({ + lookup: (key: string) => + Effect.acquireRelease( + Effect.sync(() => { + acquired.push(key) + return key + }), + () => Effect.sync(() => released.push(key)) + ), + idleTimeToLive: 1000 + }) + + assert.deepStrictEqual(acquired, []) + assert.strictEqual(yield* Effect.scoped(RcMap.get(map, "foo")), "foo") + assert.deepStrictEqual(acquired, ["foo"]) + assert.deepStrictEqual(released, []) + + yield* TestClock.adjust(1000) + assert.deepStrictEqual(released, ["foo"]) + + assert.strictEqual(yield* Effect.scoped(RcMap.get(map, "bar")), "bar") + assert.deepStrictEqual(acquired, ["foo", "bar"]) + assert.deepStrictEqual(released, ["foo"]) + + yield* TestClock.adjust(500) + assert.strictEqual(yield* Effect.scoped(RcMap.get(map, "bar")), "bar") + assert.deepStrictEqual(acquired, ["foo", "bar"]) + assert.deepStrictEqual(released, ["foo"]) + + yield* TestClock.adjust(1000) + assert.deepStrictEqual(released, ["foo", "bar"]) + + yield* Effect.scoped(RcMap.get(map, "baz")) + assert.deepStrictEqual(acquired, ["foo", "bar", "baz"]) + yield* RcMap.invalidate(map, "baz") + assert.deepStrictEqual(acquired, ["foo", "bar", "baz"]) + assert.deepStrictEqual(released, ["foo", "bar", "baz"]) + })) + + it.effect(".touch", () => + Effect.gen(function*() { + const acquired: Array = [] + const released: Array = [] + const map = yield* RcMap.make({ + lookup: (key: string) => + Effect.acquireRelease( + Effect.sync(() => { + acquired.push(key) + return key + }), + () => Effect.sync(() => released.push(key)) + ), + idleTimeToLive: 1000 + }) + + assert.deepStrictEqual(acquired, []) + assert.strictEqual(yield* Effect.scoped(RcMap.get(map, "foo")), "foo") + assert.deepStrictEqual(acquired, ["foo"]) + assert.deepStrictEqual(released, []) + + yield* TestClock.adjust(500) + assert.deepStrictEqual(released, []) + + yield* RcMap.touch(map, "foo") + yield* TestClock.adjust(500) + assert.deepStrictEqual(released, []) + yield* TestClock.adjust(500) + assert.deepStrictEqual(released, ["foo"]) + })) + + it.effect("capacity", () => + Effect.gen(function*() { + const map = yield* RcMap.make({ + lookup: (key: string) => Effect.succeed(key), + capacity: 2, + idleTimeToLive: 1000 + }) + + assert.strictEqual(yield* Effect.scoped(RcMap.get(map, "foo")), "foo") + assert.strictEqual(yield* Effect.scoped(RcMap.get(map, "foo")), "foo") + assert.strictEqual(yield* Effect.scoped(RcMap.get(map, "bar")), "bar") + + const exit = yield* RcMap.get(map, "baz").pipe(Effect.scoped, Effect.exit) + assert.deepStrictEqual( + exit, + Exit.fail(new Cause.ExceededCapacityError(`RcMap attempted to exceed capacity of 2`)) + ) + + yield* TestClock.adjust(1000) + assert.strictEqual(yield* Effect.scoped(RcMap.get(map, "baz")), "baz") + })) + + it.effect("complex key", () => + Effect.gen(function*() { + class Key extends Data.Class<{ readonly id: number }> {} + const map = yield* RcMap.make({ + lookup: (key: Key) => Effect.succeed(key.id), + capacity: 1 + }) + + assert.strictEqual(yield* RcMap.get(map, new Key({ id: 1 })), 1) + // no failure means a hit + assert.strictEqual(yield* RcMap.get(map, new Key({ id: 1 })), 1) + })) + + it.effect("keys lookup", () => + Effect.gen(function*() { + const map = yield* RcMap.make({ + lookup: (key: string) => Effect.succeed(key) + }) + + yield* RcMap.get(map, "foo") + yield* RcMap.get(map, "bar") + yield* RcMap.get(map, "baz") + + assert.deepStrictEqual(yield* RcMap.keys(map), ["foo", "bar", "baz"]) + })) +})