add RcMap & LayerMap (#68)

This commit is contained in:
Tim
2025-03-21 14:20:00 +01:00
committed by GitHub
parent 07688cb530
commit adfa56d73b
10 changed files with 1150 additions and 33 deletions
+33
View File
@@ -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
+8 -15
View File
@@ -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> = R extends infer S ? Tag<S, any> : never
/**
* @since 2.0.0
* @category models
@@ -317,8 +311,8 @@ export const add: {
* @category getters
*/
export const get: {
<Services, T extends ValidTagsById<Services> | Tag<never, any>>(tag: T): (self: Context<Services>) => Tag.Service<T>
<Services, T extends ValidTagsById<Services> | Tag<never, any>>(self: Context<Services>, tag: T): Tag.Service<T>
<Services, I extends Services, S>(tag: Tag<I, S>): (self: Context<Services>) => S
<Services, I extends Services, S>(self: Context<Services>, tag: Tag<I, S>): S
} = internal.get
/**
@@ -446,17 +440,16 @@ export const merge: {
*
* @since 2.0.0
*/
export const pick: <Services, S extends Array<ValidTagsById<Services>>>(
...tags: S
) => (self: Context<Services>) => Context<{ [k in keyof S]: Tag.Identifier<S[k]> }[number]> = internal.pick
export const pick: <Tags extends ReadonlyArray<Tag<any, any>>>(
...tags: Tags
) => <Services>(self: Context<Services>) => Context<Services & Tag.Identifier<Tags[number]>> = internal.pick
/**
* @since 2.0.0
*/
export const omit: <Services, S extends Array<ValidTagsById<Services>>>(
...tags: S
) => (self: Context<Services>) => Context<Exclude<Services, { [k in keyof S]: Tag.Identifier<S[k]> }[keyof S]>> =
internal.omit
export const omit: <Tags extends ReadonlyArray<Tag<any, any>>>(
...tags: Tags
) => <Services>(self: Context<Services>) => Context<Exclude<Services, Tag.Identifier<Tags[number]>>> = internal.omit
/**
* @example
+98
View File
@@ -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: <I, S>(tag: Context.Tag<I, S>) => Effect<S, never, I> = in
*/
export const serviceOption: <I, S>(tag: Context.Tag<I, S>) => Effect<Option<S>> = 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")<Service1, { readonly port: number }>() {}
* class Service2 extends Context.Tag("Service2")<Service2, { readonly connection: string }>() {}
*
* 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<string, never, Service2>
* // ▼
* const programWithService1 = Effect.updateContext(
* program,
* (ctx: Context.Context<Service2>) => 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: {
<R2, R>(
f: (context: Context.Context<R2>) => Context.Context<NoInfer<R>>
): <A, E>(self: Effect<A, E, R>) => Effect<A, E, R2>
<A, E, R, R2>(
self: Effect<A, E, R>,
f: (context: Context.Context<R2>) => Context.Context<NoInfer<R>>
): Effect<A, E, R2>
} = internal.updateContext
/**
* Updates the service with the required service entry.
*
@@ -4026,6 +4082,18 @@ export const uninterruptibleMask: <A, E, R>(
f: (restore: <AX, EX, RX>(effect: Effect<AX, EX, RX>) => Effect<AX, EX, RX>) => Effect<A, E, R>
) => Effect<A, E, R> = 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: <A, E, R>(
f: (restore: <AX, EX, RX>(effect: Effect<AX, EX, RX>) => Effect<AX, EX, RX>) => Effect<A, E, R>
) => Effect<A, E, R> = 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: <A, E, R>(f: (clock: Clock) => Effect<A, E, R>) => Effect<A, E, R> = internal.clockWith
// ========================================================================
// Logging
// ========================================================================
+14 -1
View File
@@ -249,6 +249,14 @@ export const unsafeMakeMemoMap = (): MemoMap => new MemoMapImpl()
*/
export const makeMemoMap: Effect<MemoMap> = 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<ROut, E, RIn>,
memoMap: MemoMap,
scope: Scope.Scope
): Effect<Context.Context<ROut>, E, RIn> => self.build(memoMap, scope))
): Effect<Context.Context<ROut>, E, RIn> =>
internalEffect.provideService(
self.build(memoMap, scope),
CurrentMemoMap,
memoMap
))
/**
* Builds a layer into a scoped value.
+396
View File
@@ -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<in out K, in out I, in out S, in out E = never> {
readonly [TypeId]: TypeId
/**
* The internal RcMap that stores the resources.
*/
readonly rcMap: RcMap.RcMap<K, readonly [Context.Context<I>, S], E>
/**
* Retrieves an instance of the resource associated with the key.
*/
get(key: K): Effect.Effect<S, E, Scope.Scope>
/**
* Provides an instance of the resource associated with the key
* to the given effect.
*/
provide(key: K): <A, EX, R>(effect: Effect.Effect<A, EX, R>) => Effect.Effect<A, EX | E, Exclude<R, I>>
/**
* Invalidates the resource associated with the key.
*/
invalidate(key: K): Effect.Effect<void>
}
/**
* @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>()("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<any, any> | Effect.Effect<any, any, any>,
K,
L extends Layer.Layer<Exclude<Effect.Effect.Context<Accessor>, Scope.Scope>, any, any>
>(
tagOrAccessor: Accessor,
lookup: (key: K) => L,
options?: {
readonly idleTimeToLive?: Duration.DurationInput | undefined
} | undefined
) => Effect.Effect<
LayerMap<
K,
Exclude<Effect.Effect.Context<Accessor>, Scope.Scope>,
Effect.Effect.Success<Accessor>,
Effect.Effect.Error<Accessor> | (L extends Layer.Layer<infer _A, infer _E, infer _R> ? _E : never)
>,
never,
Scope.Scope | (L extends Layer.Layer<infer _A, infer _E, infer _R> ? _R : never)
> = Effect.fnUntraced(function*<I, S, K, EL, RL, E = never>(
tagOrAccessor: Effect.Effect<S, E, I> | Context.Tag<I, S>,
lookup: (key: K) => Layer.Layer<Exclude<I, Scope.Scope>, EL, RL>,
options?: {
readonly idleTimeToLive?: Duration.DurationInput | undefined
} | undefined
) {
const context = yield* Effect.context<never>()
// 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<Exclude<I, Scope.Scope>>
>)
const service = yield* (Effect.provide(tagOrAccessor.asEffect(), context) as Effect.Effect<S>)
return [context, service] as const
}),
idleTimeToLive: options?.idleTimeToLive
})
return identity<LayerMap<K, Exclude<I, Scope.Scope>, 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<any, any> | Effect.Effect<any, any, any>,
const Layers extends Record<string, Layer.Layer<Exclude<Effect.Effect.Context<Accessor>, Scope.Scope>, any, any>>
>(
tagOrAccessor: Accessor,
layers: Layers,
options?: {
readonly idleTimeToLive?: Duration.DurationInput | undefined
} | undefined
): Effect.Effect<
LayerMap<
keyof Layers,
Exclude<Effect.Effect.Context<Accessor>, Scope.Scope>,
Effect.Effect.Success<Accessor>,
| Effect.Effect.Error<Accessor>
| (Layers[keyof Layers] extends Layer.Layer<infer _A, infer _E, infer _R> ? _E : never)
>,
never,
Scope.Scope | (Layers[keyof Layers] extends Layer.Layer<infer _A, infer _E, infer _R> ? _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<any, any, any>
> extends Context.TagClass<Self, Id, LayerMap<K, I, S, E>> {
/**
* A default layer for the `LayerMap` service.
*/
readonly layer: Layer.Layer<
Self,
(Deps extends Layer.Layer<infer _A, infer _E, infer _R> ? _E : never),
| Exclude<R, (Deps extends Layer.Layer<infer _A, infer _E, infer _R> ? _A : never)>
| (Deps extends Layer.Layer<infer _A, infer _E, infer _R> ? _R : never)
>
/**
* A default layer for the `LayerMap` service without the dependencies provided.
*/
readonly layerNoDeps: Layer.Layer<Self, never, R>
/**
* Retrieves an instance of the resource associated with the key.
*/
readonly get: (key: K) => Effect.Effect<S, E, Scope.Scope | Self>
/**
* Provides an instance of the resource associated with the key to the given
* effect.
*/
readonly provide: (
key: K
) => <A, EX, R>(effect: Effect.Effect<A, EX, R>) => Effect.Effect<A, EX | E, Exclude<R, I> | Self>
/**
* Invalidates the resource associated with the key.
*/
readonly invalidate: (key: K) => Effect.Effect<void, never, Self>
}
/**
* @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>()("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 = <Self>() =>
<
const Id extends string,
Accessor extends Context.Tag<any, any> | Effect.Effect<any, any, any>,
Lookup extends {
readonly lookup: (key: any) => Layer.Layer<Exclude<Effect.Effect.Context<Accessor>, Scope.Scope>, any, any>
} | {
readonly layers: Record<string, Layer.Layer<Exclude<Effect.Effect.Context<Accessor>, Scope.Scope>, any, any>>
},
const Deps extends ReadonlyArray<Layer.Layer<any, any, any>> = []
>(
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<Effect.Effect.Context<Accessor>, Scope.Scope>,
Effect.Effect.Success<Accessor>,
Effect.Effect.Error<Accessor> | Service.Error<Lookup>,
Service.Context<Lookup>,
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<TagClass<Self, Id, string, any, any, any, any, any>>
Object.setPrototypeOf(TagClass, Object.getPrototypeOf(Context.GenericTag<Self, any>(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> = 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> = 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<Options> = Layers<Options> extends Layer.Layer<infer _A, infer _E, infer _R> ? _E : never
/**
* @since 3.14.0
* @category Service
* @experimental
*/
export type Context<Options> = Layers<Options> extends Layer.Layer<infer _A, infer _E, infer _R> ? _R : never
}
+352
View File
@@ -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<in out K, in out A, in out E = never> extends Pipeable {
readonly [TypeId]: TypeId
readonly lookup: (key: K) => Effect.Effect<A, E, Scope.Scope>
readonly context: Context.Context<never>
readonly scope: Scope.Scope
readonly idleTimeToLive: Duration.Duration | undefined
readonly capacity: number
readonly semaphore: Effect.Semaphore
state: State<K, A, E>
}
/**
* @since 4.0.0
* @category Models
*/
export type State<K, A, E> = State.Open<K, A, E> | State.Closed
/**
* @since 4.0.0
* @category Models
*/
export declare namespace State {
/**
* @since 4.0.0
* @category Models
*/
export interface Open<K, A, E> {
readonly _tag: "Open"
readonly map: MutableHashMap.MutableHashMap<K, Entry<A, E>>
}
/**
* @since 4.0.0
* @category Models
*/
export interface Closed {
readonly _tag: "Closed"
}
/**
* @since 4.0.0
* @category Models
*/
export interface Entry<A, E> {
readonly deferred: Deferred.Deferred<A, E>
readonly scope: Scope.Scope.Closeable
readonly finalizer: Effect.Effect<void>
fiber: Fiber.Fiber<void> | undefined
expiresAt: number
refCount: number
}
}
const unsafeMake = <K, A, E>(options: {
readonly lookup: (key: K) => Effect.Effect<A, E, Scope.Scope>
readonly context: Context.Context<never>
readonly scope: Scope.Scope
readonly idleTimeToLive: Duration.Duration | undefined
readonly capacity: number
}): RcMap<K, A, E> => ({
[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: {
<K, A, E, R>(options: {
readonly lookup: (key: K) => Effect.Effect<A, E, R>
readonly idleTimeToLive?: Duration.DurationInput | undefined
readonly capacity?: undefined
}): Effect.Effect<RcMap<K, A, E>, never, Scope.Scope | R>
<K, A, E, R>(options: {
readonly lookup: (key: K) => Effect.Effect<A, E, R>
readonly idleTimeToLive?: Duration.DurationInput | undefined
readonly capacity: number
}): Effect.Effect<RcMap<K, A, E | Cause.ExceededCapacityError>, never, Scope.Scope | R>
} = <K, A, E, R>(options: {
readonly lookup: (key: K) => Effect.Effect<A, E, R>
readonly idleTimeToLive?: Duration.DurationInput | undefined
readonly capacity?: number | undefined
}) =>
Effect.withFiber<RcMap<K, A, E>, never, R | Scope.Scope>((fiber) => {
const context = fiber.context as Context.Context<R | Scope.Scope>
const scope = Context.get(context, Scope.Scope)
const self = unsafeMake<K, A, E>({
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: {
<K>(key: K): <A, E>(self: RcMap<K, A, E>) => Effect.Effect<A, E, Scope.Scope>
<K, A, E>(self: RcMap<K, A, E>, key: K): Effect.Effect<A, E, Scope.Scope>
} = dual(2, <K, A, E>(self: RcMap<K, A, E>, key: K): Effect.Effect<A, E, Scope.Scope> => {
return Effect.uninterruptibleMask((restore) => getImpl(self, key, restore as any))
})
const getImpl = Effect.fnUntraced(function*<K, A, E>(self: RcMap<K, A, E>, key: K, restore: <A>(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<A, E>
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<never>
} 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*<K, A, E>(self: RcMap<K, A, E>, key: K, restore: <A>(a: A) => A) {
const scope = Scope.unsafeMake()
const deferred = Deferred.unsafeMake<A, E>()
const acquire = self.lookup(key)
const contextMap = new Map(self.context.unsafeMap)
yield* restore(Effect.updateContext(
acquire as Effect.Effect<A, E>,
(inputContext: Context.Context<never>) => {
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<A, E> = {
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 = <K, A, E>(self: RcMap<K, A, E>, key: K, entry: State.Entry<A, E>) =>
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<void> {
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 = <K, A, E>(self: RcMap<K, A, E>): Effect.Effect<Array<K>> => {
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: {
<K>(key: K): <A, E>(self: RcMap<K, A, E>) => Effect.Effect<void>
<K, A, E>(self: RcMap<K, A, E>, key: K): Effect.Effect<void>
} = dual(
2,
Effect.fnUntraced(function*<K, A, E>(self: RcMap<K, A, E>, 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: {
<K>(key: K): <A, E>(self: RcMap<K, A, E>) => Effect.Effect<void>
<K, A, E>(self: RcMap<K, A, E>, key: K): Effect.Effect<void>
} = dual(
2,
<K, A, E>(self: RcMap<K, A, E>, 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
})
)
+26
View File
@@ -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
*/
+13 -17
View File
@@ -252,13 +252,13 @@ export const unsafeGet = dual<
/** @internal */
export const get: {
<Services, T extends C.ValidTagsById<Services> | C.Tag<never, any>>(
tag: T
): (self: C.Context<Services>) => C.Tag.Service<T>
<Services, T extends C.ValidTagsById<Services> | C.Tag<never, any>>(
<Services, I extends Services, S>(
tag: C.Tag<I, S>
): (self: C.Context<Services>) => S
<Services, I extends Services, S>(
self: C.Context<Services>,
tag: T
): C.Tag.Service<T>
tag: C.Tag<I, S>
): S
} = unsafeGet as any
/** @internal */
@@ -310,10 +310,10 @@ export const merge = dual<
})
/** @internal */
export const pick = <Services, S extends Array<C.ValidTagsById<Services>>>(...tags: S) =>
(
export const pick = <Tags extends ReadonlyArray<C.Tag<any, any>>>(...tags: Tags) =>
<Services>(
self: C.Context<Services>
): C.Context<{ [k in keyof S]: C.Tag.Identifier<S[k]> }[number]> => {
): C.Context<Services & C.Tag.Identifier<Tags[number]>> => {
const tagSet = new Set<string>(tags.map((_) => _.key))
const newEnv = new Map()
for (const [tag, s] of self.unsafeMap.entries()) {
@@ -321,18 +321,14 @@ export const pick = <Services, S extends Array<C.ValidTagsById<Services>>>(...ta
newEnv.set(tag, s)
}
}
return makeContext<{ [k in keyof S]: C.Tag.Identifier<S[k]> }[number]>(
newEnv
)
return makeContext(newEnv)
}
/** @internal */
export const omit = <Services, S extends Array<C.ValidTagsById<Services>>>(...tags: S) =>
(
export const omit = <Tags extends ReadonlyArray<C.Tag<any, any>>>(...tags: Tags) =>
<Services>(
self: C.Context<Services>
): C.Context<
Exclude<Services, { [k in keyof S]: C.Tag.Identifier<S[k]> }[keyof S]>
> => {
): C.Context<Exclude<Services, C.Tag.Identifier<Tags[number]>>> => {
const newEnv = new Map(self.unsafeMap)
for (const tag of tags) {
newEnv.delete(tag.key)
+33
View File
@@ -2644,6 +2644,21 @@ export const uninterruptibleMask = <A, E, R>(
return f(interruptible)
})
/** @internal */
export const interruptibleMask = <A, E, R>(
f: (
restore: <A, E, R>(
effect: Effect.Effect<A, E, R>
) => Effect.Effect<A, E, R>
) => Effect.Effect<A, E, R>
): Effect.Effect<A, E, R> =>
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
// ----------------------------------------------------------------------------
+177
View File
@@ -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<string> = []
const released: Array<string> = []
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<string> = []
const released: Array<string> = []
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<string> = []
const released: Array<string> = []
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"])
}))
})