MCPcopy Create free account
hub / github.com/Effect-TS/effect / ResourceMap

Class ResourceMap

packages/cluster/src/internal/resourceMap.ts:9–86  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7import * as Scope from "effect/Scope"
8
9export class ResourceMap<K, A, E> {
10 constructor(
11 readonly lookup: (key: K, scope: Scope.Scope) => Effect.Effect<A, E>,
12 readonly entries: BackingMap<K, A, E>,
13 readonly isClosed: MutableRef.MutableRef<boolean>
14 ) {}
15
16 static make = Effect.fnUntraced(function*<K, A, E, R>(lookup: (key: K) => Effect.Effect<A, E, R>, options?: {
17 readonly referential?: boolean | undefined
18 }) {
19 const scope = yield* Effect.scope
20 const context = yield* Effect.context<R>()
21 const isClosed = MutableRef.make(false)
22
23 const entries: BackingMap<K, A, E> = options?.referential
24 ? { _tag: "Referential", map: new Map() }
25 : { _tag: "Equal", map: MutableHashMap.empty() }
26
27 yield* Scope.addFinalizerExit(
28 scope,
29 (exit) => {
30 MutableRef.set(isClosed, true)
31 return Effect.forEach(entries.map, ([key, { scope }]) => {
32 backingDelete(entries, key)
33 return Effect.exit(Scope.close(scope, exit))
34 }, { concurrency: "unbounded", discard: true })
35 }
36 )
37
38 return new ResourceMap(
39 (key, scope) => Effect.provide(lookup(key), Context.add(context, Scope.Scope, scope)),
40 entries,
41 isClosed
42 )
43 })
44
45 get(key: K): Effect.Effect<A, E> {
46 return Effect.withFiberRuntime((fiber) => {
47 if (MutableRef.get(this.isClosed)) {
48 return Effect.interrupt
49 }
50 const existing = backingGet(this.entries, key)
51 if (existing) {
52 return Deferred.await(existing.deferred)
53 }
54 const scope = Effect.runSync(Scope.make())
55 const deferred = Deferred.unsafeMake<A, E>(fiber.id())
56 backingSet(this.entries, key, { scope, deferred })
57 return Effect.onExit(this.lookup(key, scope), (exit) => {
58 if (exit._tag === "Success") {
59 return Deferred.done(deferred, exit)
60 }
61 backingDelete(this.entries, key)
62 return Effect.andThen(Deferred.done(deferred, exit), Scope.close(scope, exit))
63 })
64 })
65 }
66

Callers

nothing calls this directly

Calls 8

backingDeleteFunction · 0.85
lookupFunction · 0.85
contextMethod · 0.65
makeMethod · 0.65
setMethod · 0.65
closeMethod · 0.65
provideMethod · 0.65
addMethod · 0.65

Tested by

no test coverage detected