MCPcopy Index your code
hub / github.com/Effect-TS/effect / ResourceRef

Class ResourceRef

packages/cluster/src/internal/resourceRef.ts:19–91  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

17}
18
19export class ResourceRef<A, E = never> {
20 static from = Effect.fnUntraced(function*<A, E>(
21 parentScope: Scope.Scope,
22 acquire: (scope: Scope.Scope) => Effect.Effect<A, E>
23 ) {
24 const state = MutableRef.make<State<A>>({ _tag: "Closed" })
25
26 yield* Scope.addFinalizerExit(parentScope, (exit) => {
27 const s = MutableRef.get(state)
28 if (s._tag === "Closed") {
29 return Effect.void
30 }
31 const scope = s.scope
32 MutableRef.set(state, { _tag: "Closed" })
33 return Scope.close(scope, exit)
34 })
35
36 const scope = yield* Scope.make()
37 MutableRef.set(state, { _tag: "Acquiring", scope })
38 const value = yield* acquire(scope)
39 MutableRef.set(state, { _tag: "Acquired", scope, value })
40
41 return new ResourceRef(state, acquire)
42 })
43
44 constructor(
45 readonly state: MutableRef.MutableRef<State<A>>,
46 readonly acquire: (scope: Scope.Scope) => Effect.Effect<A, E>
47 ) {}
48
49 latch = Effect.unsafeMakeLatch(true)
50
51 unsafeGet(): Option.Option<A> {
52 if (this.state.current._tag === "Acquired") {
53 return Option.some(this.state.current.value)
54 }
55 return Option.none()
56 }
57
58 unsafeRebuild(): Effect.Effect<void, E> {
59 const s = this.state.current
60 if (s._tag === "Closed") {
61 return Effect.interrupt
62 }
63 const prevScope = s.scope
64 const scope = Effect.runSync(Scope.make())
65 this.latch.unsafeClose()
66 MutableRef.set(this.state, { _tag: "Acquiring", scope })
67 return Effect.fiberIdWith((fiberId) => {
68 internalInterruptors.add(fiberId)
69 return Scope.close(prevScope, Exit.void)
70 }).pipe(
71 Effect.andThen(this.acquire(scope)),
72 Effect.flatMap((value) => {
73 if (this.state.current._tag === "Closed") {
74 return Effect.interrupt
75 }
76 MutableRef.set(this.state, { _tag: "Acquired", scope, value })

Callers

nothing calls this directly

Calls 5

makeMethod · 0.65
getMethod · 0.65
setMethod · 0.65
closeMethod · 0.65
acquireFunction · 0.50

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…