Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Cache.ts

1,405 lines42.1 KB

1/**
2 * Caches values loaded by an Effect lookup function.
3 *
4 * A cache stores successful and failed lookup results, shares an in-progress
5 * lookup when multiple callers request the same missing key, and limits entries
6 * by capacity and optional time-to-live rules. This module includes helpers for
7 * reading, setting, refreshing, invalidating, and inspecting cache contents.
8 *
9 * @since 4.0.0
10 */
11import * as Context from "./Context.ts"
12import * as Duration from "./Duration.ts"
13import type * as Effect from "./Effect.ts"
14import type * as Exit from "./Exit.ts"
15import type * as Fiber from "./Fiber.ts"
16import { dual } from "./Function.ts"
17import * as core from "./internal/core.ts"
18import { PipeInspectableProto } from "./internal/core.ts"
19import * as effect from "./internal/effect.ts"
20import * as Iterable from "./Iterable.ts"
21import * as MutableHashMap from "./MutableHashMap.ts"
22import * as Option from "./Option.ts"
23import type { Pipeable } from "./Pipeable.ts"
24import type { Predicate } from "./Predicate.ts"
25import * as Result from "./Result.ts"
26​
27const TypeId = "~effect/Cache"
28​
29/**
30 * A cache interface that provides a mutable key-value store with automatic TTL management,
31 * capacity limits, and lookup functions for cache misses.
32 *
33 * **Example** (Creating a basic cache)
34 *
35 * ```ts import.meta.vitest
36 * import { Cache, Effect } from "effect"
37 *
38 * // Basic cache with string keys and number values
39 * const program = Effect.gen(function*() {
40 * const cache = yield* Cache.make<string, number>({
41 * capacity: 100,
42 * lookup: (key: string) => Effect.succeed(key.length)
43 * })
44 *
45 * // Cache operations
46 * const value1 = yield* Cache.get(cache, "hello") // 5
47 * const value2 = yield* Cache.get(cache, "world") // 5
48 * const value3 = yield* Cache.get(cache, "hello") // 5 (cached)
49 *
50 * return [value1, value2, value3]
51 * })
52 *
53 * const actual = await Effect.runPromise(program)
54 * actual // => [5, 5, 5]
55 * ```
56 *
57 * **Example** (Handling lookup failures)
58 *
59 * ```ts import.meta.vitest
60 * import { Cache, Effect, Exit } from "effect"
61 *
62 * // Cache with error handling
63 * const program = Effect.gen(function*() {
64 * const cache = yield* Cache.make<string, number, string>({
65 * capacity: 10,
66 * lookup: (key: string) =>
67 * key === "error"
68 * ? Effect.fail("Lookup failed")
69 * : Effect.succeed(key.length)
70 * })
71 *
72 * // Handle successful and failed lookups
73 * const success = yield* Cache.get(cache, "test")
74 * const failure = yield* Effect.exit(Cache.get(cache, "error"))
75 *
76 * return [success, failure] as const
77 * })
78 *
79 * const actual = await Effect.runPromise(program)
80 * actual // => [4, Exit.fail("Lookup failed")]
81 * ```
82 *
83 * **Example** (Using complex keys with TTL)
84 *
85 * ```ts import.meta.vitest
86 * import { Cache, Data, Duration, Effect } from "effect"
87 *
88 * // Cache with complex key types and TTL
89 * class UserId extends Data.Class<{ id: number }> {}
90 *
91 * const program = Effect.gen(function*() {
92 * const userCache = yield* Cache.make<UserId, string>({
93 * capacity: 1000,
94 * lookup: (userId: UserId) => Effect.succeed(`User-${userId.id}`),
95 * timeToLive: Duration.minutes(5)
96 * })
97 *
98 * const userId = new UserId({ id: 123 })
99 * const userName = yield* Cache.get(userCache, userId)
100 *
101 * return userName
102 * })
103 *
104 * const actual = await Effect.runPromise(program)
105 * actual // => "User-123"
106 * ```
107 *
108 * @category models
109 * @since 2.0.0
110 */
111export interface Cache<in out Key, in out A, in out E = never, out R = never> extends Pipeable {
112 readonly [TypeId]: typeof TypeId
113 readonly map: MutableHashMap.MutableHashMap<Key, Entry<A, E>>
114 readonly capacity: number
115 readonly lookup: (key: Key) => Effect.Effect<A, E, R>
116 readonly timeToLive: (exit: Exit.Exit<A, E>, key: Key) => Duration.Duration
118​
119/**
120 * Represents a low-level cache entry containing a deferred lookup result and
121 * an optional expiration timestamp.
122 *
123 * **When to use**
124 *
125 * Use when inspecting a `Cache`'s low-level map and you need the stored
126 * deferred lookup result or expiration timestamp for a key.
127 *
128 * **Details**
129 *
130 * An `expiresAt` value of `undefined` means the entry does not expire.
131 *
132 * @see {@link Cache} for the public cache API that manages entries through
133 * combinators
134 *
135 * @category models
136 * @since 4.0.0
137 */
138export interface Entry<A, E> {
139 expiresAt: number | undefined
140 awaiters: number
141 readonly fiber: Fiber.Fiber<A, E>
142 await(this: Entry<A, E>): Effect.Effect<A, E>
144​
145/**
146 * Creates a cache with dynamic time-to-live based on the result and key.
147 *
148 * **When to use**
149 *
150 * Use when you need different cache entry lifetimes based on the lookup result
151 * or key characteristics.
152 *
153 * **Details**
154 *
155 * The timeToLive function receives both the exit result and the key, allowing
156 * for flexible TTL policies based on success/failure state and key characteristics.
157 *
158 * **Example** (Configuring dynamic time to live)
159 *
160 * ```ts import.meta.vitest
161 * import { Cache, Effect, Exit } from "effect"
162 *
163 * // Cache with TTL based on computed value
164 * const program = Effect.gen(function*() {
165 * const cache = yield* Cache.makeWith(
166 * (id: number) => Effect.succeed({ id, active: id % 2 === 0 }),
167 * {
168 * capacity: 1000,
169 * timeToLive(exit) {
170 * if (Exit.isSuccess(exit)) {
171 * const user = exit.value
172 * return user.active ? "1 hour" : "5 minutes"
173 * }
174 * return "30 seconds"
175 * }
176 * }
177 * )
178 *
179 * return cache.capacity
180 * })
181 *
182 * const actual = await Effect.runPromise(program)
183 * actual // => 1000
184 * ```
185 *
186 * @see {@link make} for a simpler cache constructor with a fixed time-to-live for all entries
187 * @category constructors
188 * @since 2.0.0
189 */
190export const makeWith = <
191 Key,
192 A,
193 E = never,
194 R = never,
195 ServiceMode extends "lookup" | "construction" = never
196>(lookup: (key: Key) => Effect.Effect<A, E, R>, options: {
197 readonly capacity: number
198 readonly timeToLive?: ((exit: Exit.Exit<A, E>, key: Key) => Duration.Input) | undefined
199 readonly requireServicesAt?: ServiceMode | undefined
200}): Effect.Effect<
201 Cache<Key, A, E, "lookup" extends ServiceMode ? R : never>,
202 never,
203 "lookup" extends ServiceMode ? never : R
204> =>
205 effect.contextWith((context: Context.Context<any>) => {
206 const self = Object.create(Proto)
207 self.lookup = (key: Key): Effect.Effect<A, E> =>
208 effect.updateContext(
209 lookup(key),
210 (input) => Context.merge(context, input)
211 )
212 self.map = MutableHashMap.make()
213 self.capacity = options.capacity
214 self.timeToLive = options.timeToLive
215 ? (exit: Exit.Exit<A, E>, key: Key) => Duration.fromInputUnsafe(options.timeToLive!(exit, key))
216 : defaultTimeToLive
217 return effect.succeed(self as Cache<Key, A, E>)
218 })
219​
220/**
221 * Creates a cache with a fixed time-to-live for all entries.
222 *
223 * **Details**
224 *
225 * This is the basic cache constructor where all entries share the same TTL.
226 * The lookup function will be called when a key is not found or has expired.
227 *
228 * **Example** (Creating a basic cache)
229 *
230 * ```ts import.meta.vitest
231 * import { Cache, Effect } from "effect"
232 *
233 * // Basic cache with string keys
234 * const program = Effect.gen(function*() {
235 * const cache = yield* Cache.make<string, number>({
236 * capacity: 100,
237 * lookup: (key) => Effect.succeed(key.length)
238 * })
239 *
240 * const result1 = yield* Cache.get(cache, "hello")
241 * const result2 = yield* Cache.get(cache, "world")
242 * return { result1, result2 }
243 * })
244 *
245 * const actual = await Effect.runPromise(program)
246 * actual // => { result1: 5, result2: 5 }
247 * ```
248 *
249 * **Example** (Creating a cache with TTL)
250 *
251 * ```ts import.meta.vitest
252 * import { Cache, Effect } from "effect"
253 *
254 * const program = Effect.gen(function*() {
255 * const users = new Map([
256 * [123, { name: "Ada", email: "ada@example.com" }],
257 * [456, { name: "Grace", email: "grace@example.com" }]
258 * ])
259 *
260 * const cache = yield* Cache.make<
261 * number,
262 * { name: string; email: string },
263 * string
264 * >({
265 * capacity: 500,
266 * lookup: (userId) =>
267 * Effect.suspend(() => {
268 * const user = users.get(userId)
269 * return user === undefined
270 * ? Effect.fail(`User ${userId} not found`)
271 * : Effect.succeed(user)
272 * }),
273 * timeToLive: "15 minutes"
274 * })
275 *
276 * const user1 = yield* Cache.get(cache, 123)
277 * const user2 = yield* Cache.get(cache, 123)
278 * return [user1, user2, user1 === user2] as const
279 * })
280 *
281 * const actual = await Effect.runPromise(program)
282 * actual // => [{ name: "Ada", email: "ada@example.com" }, { name: "Ada", email: "ada@example.com" }, true]
283 * ```
284 *
285 * @category constructors
286 * @since 2.0.0
287 */
288export const make = <
289 Key,
290 A,
291 E = never,
292 R = never,
293 ServiceMode extends "lookup" | "construction" = never
294>(
295 options: {
296 readonly lookup: (key: Key) => Effect.Effect<A, E, R>
297 readonly capacity: number
298 readonly timeToLive?: Duration.Input | undefined
299 readonly requireServicesAt?: ServiceMode | undefined
300 }
301): Effect.Effect<
302 Cache<Key, A, E, "lookup" extends ServiceMode ? R : never>,
303 never,
304 "lookup" extends ServiceMode ? never : R
305> =>
306 makeWith<Key, A, E, R, ServiceMode>(options.lookup, {
307 ...options,
308 timeToLive: options.timeToLive !== undefined ? () => options.timeToLive! : defaultTimeToLive
309 })
310​
311const Proto = {
312 ...PipeInspectableProto,
313 [TypeId]: TypeId,
314 toJSON(this: Cache<any, any, any>) {
315 return {
316 _id: "Cache",
317 capacity: this.capacity,
318 map: this.map
319 }
320 }
322​
323const defaultTimeToLive = <A, E>(_: Exit.Exit<A, E>, _key: unknown): Duration.Duration => Duration.infinity
324​
325/**
326 * Retrieves the value for a key, invoking the lookup function on a cache miss
327 * or expired entry.
328 *
329 * **Details**
330 *
331 * Concurrent `get` calls for the same missing key share the same pending
332 * lookup. The cache stores the lookup `Exit`, so failed lookups are cached and
333 * will fail again until the entry expires, is invalidated, or is refreshed.
334 *
335 * **Example** (Getting cached values)
336 *
337 * ```ts import.meta.vitest
338 * import { Cache, Effect } from "effect"
339 *
340 * const program = Effect.gen(function*() {
341 * const cache = yield* Cache.make({
342 * capacity: 10,
343 * lookup: (key: string) => Effect.succeed(key.length)
344 * })
345 *
346 * // Cache miss - triggers lookup function
347 * const result1 = yield* Cache.get(cache, "hello")
348 *
349 * // Cache hit - returns cached value without lookup
350 * const result2 = yield* Cache.get(cache, "hello")
351 *
352 * return { result1, result2 }
353 * })
354 *
355 * const actual = await Effect.runPromise(program)
356 * actual // => { result1: 5, result2: 5 }
357 * ```
358 *
359 * **Example** (Handling lookup failures)
360 *
361 * ```ts import.meta.vitest
362 * import { Cache, Effect, Exit } from "effect"
363 *
364 * // Error handling when lookup fails
365 * const program = Effect.gen(function*() {
366 * const cache = yield* Cache.make<string, number, string>({
367 * capacity: 10,
368 * lookup: (key: string) =>
369 * key === "error"
370 * ? Effect.fail("Lookup failed")
371 * : Effect.succeed(key.length)
372 * })
373 *
374 * // Successful lookup
375 * const success = yield* Cache.get(cache, "hello")
376 *
377 * // Failed lookup - returns error
378 * const failure = yield* Effect.exit(Cache.get(cache, "error"))
379 * return [success, failure] as const
380 * })
381 *
382 * const actual = await Effect.runPromise(program)
383 * actual // => [5, Exit.fail("Lookup failed")]
384 * ```
385 *
386 * **Example** (Sharing concurrent lookups)
387 *
388 * ```ts import.meta.vitest
389 * import { Cache, Effect } from "effect"
390 *
391 * // Concurrent access - multiple gets of same key only invoke lookup once
392 * const program = Effect.gen(function*() {
393 * let lookupCount = 0
394 * const cache = yield* Cache.make({
395 * capacity: 10,
396 * lookup: (key: string) =>
397 * Effect.sync(() => {
398 * lookupCount++
399 * return key.length
400 * })
401 * })
402 *
403 * // Multiple concurrent gets
404 * const results = yield* Effect.all([
405 * Cache.get(cache, "hello"),
406 * Cache.get(cache, "hello"),
407 * Cache.get(cache, "hello")
408 * ], { concurrency: "unbounded" })
409 *
410 * return { results, lookupCount }
411 * })
412 *
413 * const actual = await Effect.runPromise(program)
414 * actual // => { results: [5, 5, 5], lookupCount: 1 }
415 * ```
416 *
417 * @category combinators
418 * @since 4.0.0
419 */
420export const get: {
421 <Key, A>(key: Key): <E, R>(self: Cache<Key, A, E, R>) => Effect.Effect<A, E, R>
422 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key): Effect.Effect<A, E, R>
423} = dual(
424 2,
425 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key): Effect.Effect<A, E, R> =>
426 core.withFiber((fiber) => {
427 const oentry = MutableHashMap.get(self.map, key)
428 if (Option.isSome(oentry) && !hasExpired(oentry.value, fiber)) {
429 // Move the entry to the end of the map to keep it fresh
430 MutableHashMap.remove(self.map, key)
431 MutableHashMap.set(self.map, key, oentry.value)
432 return oentry.value.await()
433 }
434 const entry = new EntryImpl(fiber, self.lookup(key))
435 entry.fiber.addObserver((exit) => {
436 if (effect.exitHasInterrupts(exit)) {
437 const current = MutableHashMap.get(self.map, key)
438 if (Option.isSome(current) && current.value === entry) {
439 MutableHashMap.remove(self.map, key)
440 }
441 return
442 }
443 const ttl = self.timeToLive(exit, key)
444 if (Duration.isFinite(ttl)) {
445 entry.expiresAt = fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe() + Duration.toMillis(ttl)
446 } else if (Duration.isZero(ttl)) {
447 MutableHashMap.remove(self.map, key)
448 }
449 })
450 const exit = entry.fiber.pollUnsafe()
451 if (exit === undefined || !effect.exitHasInterrupts(exit)) {
452 MutableHashMap.set(self.map, key, entry)
453 }
454 if (Number.isFinite(self.capacity)) {
455 checkCapacity(self)
456 }
457 return entry.await()
458 })
460​
461class EntryImpl<A, E> implements Entry<A, E> {
462 expiresAt: number | undefined
463 awaiters: number
464 fiber: Fiber.Fiber<A, E>
465​
466 constructor(
467 parent: Fiber.Fiber<unknown, unknown>,
468 valueEffect: Effect.Effect<A, E, any>
469 ) {
470 this.fiber = effect.forkUnsafe(parent, valueEffect, true, true)
471 this.awaiters = 0
472 this.expiresAt = undefined
473 }
474​
475 await(): Effect.Effect<A, E> {
476 const exit = this.fiber.pollUnsafe()
477 if (exit) return exit
478 this.awaiters++
479 return effect.onExit(effect.fiberJoin(this.fiber), () => {
480 this.awaiters--
481 if (this.awaiters > 0 || this.fiber.pollUnsafe()) return effect.void
482 return effect.fiberInterrupt(this.fiber)
483 })
484 }
486​
487const hasExpired = <A, E>(entry: Entry<A, E>, fiber: Fiber.Fiber<unknown, unknown>): boolean => {
488 if (entry.expiresAt === undefined) {
489 return false
490 }
491 return fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe() >= entry.expiresAt
493​
494const checkCapacity = <K, A, E, R>(self: Cache<K, A, E, R>) => {
495 let diff = MutableHashMap.size(self.map) - self.capacity
496 if (diff <= 0) return
497 // MutableHashMap has insertion order, so we can remove the oldest entries
498 for (const [key] of self.map) {
499 MutableHashMap.remove(self.map, key)
500 diff--
501 if (diff === 0) return
502 }
504​
505/**
506 * Reads an existing cache entry without invoking the lookup function.
507 *
508 * **Details**
509 *
510 * Returns `Option.none()` when the key is missing or expired, and `Option.some`
511 * when a cached lookup has succeeded. If the entry is still pending, waits for
512 * it to complete. If the cached or pending lookup fails, this effect fails with
513 * the same error.
514 *
515 * **Example** (Reading cached values without lookup)
516 *
517 * ```ts import.meta.vitest
518 * import { Cache, Effect, Option } from "effect"
519 *
520 * const program = Effect.gen(function*() {
521 * const cache = yield* Cache.make({
522 * capacity: 10,
523 * lookup: (key: string) => Effect.succeed(key.length)
524 * })
525 *
526 * // No value in cache yet - returns None without lookup
527 * const empty = yield* Cache.getOption(cache, "hello")
528 *
529 * // Populate cache using get
530 * yield* Cache.get(cache, "hello")
531 *
532 * // Now getOption returns the cached value
533 * const cached = yield* Cache.getOption(cache, "hello")
534 * return [empty, cached] as const
535 * })
536 *
537 * const actual = await Effect.runPromise(program)
538 * actual // => [Option.none(), Option.some(5)]
539 * ```
540 *
541 * **Example** (Skipping expired entries)
542 *
543 * ```ts import.meta.vitest
544 * import { Cache, Effect, Option } from "effect"
545 * import { TestClock } from "effect/testing"
546 *
547 * // Expired entries return None
548 * const program = Effect.gen(function*() {
549 * const cache = yield* Cache.make({
550 * capacity: 10,
551 * lookup: (key: string) => Effect.succeed(key.length),
552 * timeToLive: "1 hour"
553 * })
554 *
555 * // Add value to cache
556 * yield* Cache.get(cache, "hello")
557 *
558 * // Value exists before expiration
559 * const beforeExpiry = yield* Cache.getOption(cache, "hello")
560 *
561 * // Simulate time passing
562 * yield* TestClock.adjust("2 hours")
563 *
564 * // Value expired - returns None
565 * const afterExpiry = yield* Cache.getOption(cache, "hello")
566 * return [beforeExpiry, afterExpiry] as const
567 * })
568 *
569 * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))
570 * actual // => [Option.some(5), Option.none()]
571 * ```
572 *
573 * **Example** (Waiting for pending lookups)
574 *
575 * ```ts import.meta.vitest
576 * import { Cache, Deferred, Effect, Fiber, Option } from "effect"
577 *
578 * // Waits for ongoing computation to complete
579 * const program = Effect.gen(function*() {
580 * const deferred = yield* Deferred.make<void>()
581 * const cache = yield* Cache.make({
582 * capacity: 10,
583 * lookup: (_key: string) => Deferred.await(deferred).pipe(Effect.as(42))
584 * })
585 *
586 * // Start lookup in background
587 * const getFiber = yield* Effect.forkChild(Cache.get(cache, "key"))
588 *
589 * // getOption waits for ongoing computation
590 * const optionFiber = yield* Effect.forkChild(Cache.getOption(cache, "key"))
591 *
592 * // Complete the computation
593 * yield* Deferred.succeed(deferred, void 0)
594 *
595 * const result = yield* Fiber.join(optionFiber)
596 * const value = yield* Fiber.join(getFiber)
597 * return [result, value] as const
598 * })
599 *
600 * const actual = await Effect.runPromise(program)
601 * actual // => [Option.some(42), 42]
602 * ```
603 *
604 * @category combinators
605 * @since 4.0.0
606 */
607export const getOption: {
608 <Key, A>(key: Key): <E, R>(self: Cache<Key, A, E, R>) => Effect.Effect<Option.Option<A>, E>
609 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key): Effect.Effect<Option.Option<A>, E>
610} = dual(
611 2,
612 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key): Effect.Effect<Option.Option<A>, E> =>
613 core.withFiber((fiber) => {
614 const entry = getImpl(self, key, fiber)
615 return entry ? effect.asSome(entry.await()) : effect.succeedNone
616 })
618​
619const getImpl = <Key, A, E, R>(
620 self: Cache<Key, A, E, R>,
621 key: Key,
622 fiber: Fiber.Fiber<any, any>,
623 isRead = true
624): Entry<A, E> | undefined => {
625 const oentry = MutableHashMap.get(self.map, key)
626 if (Option.isNone(oentry)) {
627 return undefined
628 } else if (hasExpired(oentry.value, fiber)) {
629 MutableHashMap.remove(self.map, key)
630 return undefined
631 } else if (isRead) {
632 MutableHashMap.remove(self.map, key)
633 MutableHashMap.set(self.map, key, oentry.value)
634 }
635 return oentry.value
637​
638/**
639 * Retrieves the value associated with the specified key from the cache, only if
640 * it contains a resolved successful value.
641 *
642 * **Details**
643 *
644 * This checks only an existing non-expired entry. It returns `Option.some` when
645 * the entry has already resolved successfully, and `Option.none` for missing,
646 * expired, failed, or still-pending entries.
647 *
648 * @see {@link get} for triggering or awaiting the cache lookup
649 * @see {@link getOption} for reading an existing entry as an optional effect
650 *
651 * @category combinators
652 * @since 4.0.0
653 */
654export const getSuccess: {
655 <Key, A, R>(key: Key): <E>(self: Cache<Key, A, E, R>) => Effect.Effect<Option.Option<A>>
656 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key): Effect.Effect<Option.Option<A>>
657} = dual(
658 2,
659 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key): Effect.Effect<Option.Option<A>> =>
660 core.withFiber((fiber) => {
661 const exit = getImpl(self, key, fiber)?.fiber.pollUnsafe()
662 if (exit && effect.exitIsSuccess(exit)) {
663 return effect.succeedSome(exit.value)
664 }
665 return effect.succeedNone
666 })
668​
669/**
670 * Sets the value associated with the specified key in the cache. This will
671 * overwrite any existing value for that key, skipping the lookup function.
672 *
673 * **Example** (Setting values directly)
674 *
675 * ```ts import.meta.vitest
676 * import { Cache, Effect } from "effect"
677 *
678 * const program = Effect.gen(function*() {
679 * const cache = yield* Cache.make({
680 * capacity: 100,
681 * lookup: (key: string) => Effect.succeed(key.length)
682 * })
683 *
684 * // Set a value directly without invoking lookup
685 * yield* Cache.set(cache, "hello", 42)
686 * return yield* Cache.get(cache, "hello")
687 * })
688 *
689 * const actual = await Effect.runPromise(program)
690 * actual // => 42
691 * ```
692 *
693 * **Example** (Overwriting cached values)
694 *
695 * ```ts import.meta.vitest
696 * import { Cache, Effect } from "effect"
697 *
698 * // Overwriting existing cached values
699 * const program = Effect.gen(function*() {
700 * const cache = yield* Cache.make({
701 * capacity: 100,
702 * lookup: (key: string) => Effect.succeed(key.length)
703 * })
704 *
705 * // First get populates via lookup
706 * const original = yield* Cache.get(cache, "test") // 4
707 *
708 * // Set overwrites the cached value
709 * yield* Cache.set(cache, "test", 999)
710 * const updated = yield* Cache.get(cache, "test") // 999
711 *
712 * return { original, updated }
713 * })
714 *
715 * const actual = await Effect.runPromise(program)
716 * actual // => { original: 4, updated: 999 }
717 * ```
718 *
719 * **Example** (Applying TTL to set values)
720 *
721 * ```ts import.meta.vitest
722 * import { Cache, Effect } from "effect"
723 * import { TestClock } from "effect/testing"
724 *
725 * // TTL behavior with set operations
726 * const program = Effect.gen(function*() {
727 * const cache = yield* Cache.make({
728 * capacity: 100,
729 * lookup: (key: string) => Effect.succeed(key.length),
730 * timeToLive: "1 hour"
731 * })
732 *
733 * // Set value with TTL applied
734 * yield* Cache.set(cache, "temporary", 123)
735 * const beforeExpiry = yield* Cache.has(cache, "temporary")
736 *
737 * // Advance time past TTL
738 * yield* TestClock.adjust("2 hours")
739 * const afterExpiry = yield* Cache.has(cache, "temporary")
740 * return [beforeExpiry, afterExpiry]
741 * })
742 *
743 * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))
744 * actual // => [true, false]
745 * ```
746 *
747 * **Example** (Enforcing capacity when setting values)
748 *
749 * ```ts import.meta.vitest
750 * import { Cache, Effect } from "effect"
751 *
752 * // Capacity enforcement with set operations
753 * const program = Effect.gen(function*() {
754 * const cache = yield* Cache.make({
755 * capacity: 2,
756 * lookup: (key: string) => Effect.succeed(key.length)
757 * })
758 *
759 * // Fill cache to capacity
760 * yield* Cache.set(cache, "a", 1)
761 * yield* Cache.set(cache, "b", 2)
762 * const sizeBeforeEviction = yield* Cache.size(cache)
763 *
764 * // Adding another entry evicts oldest
765 * yield* Cache.set(cache, "c", 3)
766 * const sizeAfterEviction = yield* Cache.size(cache)
767 * const hasOldest = yield* Cache.has(cache, "a")
768 * const hasNewest = yield* Cache.has(cache, "c")
769 * return [sizeBeforeEviction, sizeAfterEviction, hasOldest, hasNewest]
770 * })
771 *
772 * const actual = await Effect.runPromise(program)
773 * actual // => [2, 2, false, true]
774 * ```
775 *
776 * @category combinators
777 * @since 4.0.0
778 */
779export const set: {
780 <Key, A>(key: Key, value: A): <E, R>(self: Cache<Key, A, E, R>) => Effect.Effect<void>
781 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key, value: A): Effect.Effect<void>
782} = dual(
783 3,
784 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key, value: A): Effect.Effect<void> =>
785 core.withFiber((fiber) => {
786 const exit = core.exitSucceed(value)
787 const entry = new EntryImpl(fiber, exit)
788 const ttl = self.timeToLive(exit, key)
789 if (Duration.isZero(ttl)) {
790 MutableHashMap.remove(self.map, key)
791 return effect.void
792 }
793 entry.expiresAt = Duration.isFinite(ttl)
794 ? fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe() + Duration.toMillis(ttl)
795 : undefined
796 MutableHashMap.set(self.map, key, entry)
797 checkCapacity(self)
798 return effect.void
799 })
801​
802/**
803 * Checks whether the cache contains an entry for the specified key.
804 *
805 * **Details**
806 *
807 * This checks for an existing non-expired entry without invoking the cache
808 * lookup function. Expired entries are treated as absent.
809 *
810 * **Example** (Checking for cached keys)
811 *
812 * ```ts import.meta.vitest
813 * import { Cache, Effect } from "effect"
814 *
815 * const program = Effect.gen(function*() {
816 * const cache = yield* Cache.make({
817 * capacity: 100,
818 * lookup: (key: string) => Effect.succeed(key.length)
819 * })
820 *
821 * // Check non-existent key
822 * const missing = yield* Cache.has(cache, "missing")
823 *
824 * // Add entry and check existence
825 * yield* Cache.get(cache, "hello")
826 * const present = yield* Cache.has(cache, "hello")
827 * return [missing, present]
828 * })
829 *
830 * const actual = await Effect.runPromise(program)
831 * actual // => [false, true]
832 * ```
833 *
834 * **Example** (Checking TTL expiration)
835 *
836 * ```ts import.meta.vitest
837 * import { Cache, Effect } from "effect"
838 * import { TestClock } from "effect/testing"
839 *
840 * // TTL expiration behavior
841 * const program = Effect.gen(function*() {
842 * const cache = yield* Cache.make({
843 * capacity: 100,
844 * lookup: (key: string) => Effect.succeed(key.length),
845 * timeToLive: "1 hour"
846 * })
847 *
848 * // Add entry with TTL
849 * yield* Cache.get(cache, "expires")
850 * const initial = yield* Cache.has(cache, "expires")
851 *
852 * // Still valid before expiration
853 * yield* TestClock.adjust("30 minutes")
854 * const beforeExpiry = yield* Cache.has(cache, "expires")
855 *
856 * // Expired after TTL
857 * yield* TestClock.adjust("31 minutes")
858 * const afterExpiry = yield* Cache.has(cache, "expires")
859 * return [initial, beforeExpiry, afterExpiry]
860 * })
861 *
862 * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))
863 * actual // => [true, true, false]
864 * ```
865 *
866 * **Example** (Checking multiple keys)
867 *
868 * ```ts import.meta.vitest
869 * import { Cache, Effect } from "effect"
870 *
871 * // Checking multiple keys efficiently
872 * const program = Effect.gen(function*() {
873 * const cache = yield* Cache.make({
874 * capacity: 100,
875 * lookup: (key: string) => Effect.succeed(key.length)
876 * })
877 *
878 * // Populate some entries
879 * yield* Cache.set(cache, "apple", 5)
880 * yield* Cache.set(cache, "banana", 6)
881 *
882 * // Check multiple keys
883 * const keys = ["apple", "banana", "cherry", "date"]
884 * const results: Array<string> = []
885 * for (const key of keys) {
886 * const exists = yield* Cache.has(cache, key)
887 * results.push(`${key}: ${exists}`)
888 * }
889 * return results
890 * })
891 *
892 * const actual = await Effect.runPromise(program)
893 * actual // => ["apple: true", "banana: true", "cherry: false", "date: false"]
894 * ```
895 *
896 * @category combinators
897 * @since 4.0.0
898 */
899export const has: {
900 <Key, A>(key: Key): <E, R>(self: Cache<Key, A, E, R>) => Effect.Effect<boolean>
901 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key): Effect.Effect<boolean>
902} = dual(
903 2,
904 <Key, A, E>(self: Cache<Key, A, E>, key: Key): Effect.Effect<boolean> =>
905 core.withFiber((fiber) => {
906 const oentry = getImpl(self, key, fiber, false)
907 return effect.succeed(oentry !== undefined)
908 })
910​
911/**
912 * Invalidates the entry associated with the specified key in the cache.
913 *
914 * **Example** (Invalidating cached entries)
915 *
916 * ```ts import.meta.vitest
917 * import { Cache, Effect } from "effect"
918 *
919 * const program = Effect.gen(function*() {
920 * const cache = yield* Cache.make({
921 * capacity: 10,
922 * lookup: (key: string) => Effect.succeed(key.length)
923 * })
924 *
925 * // Add a value to the cache
926 * yield* Cache.get(cache, "hello")
927 * const beforeInvalidation = yield* Cache.has(cache, "hello")
928 *
929 * // Invalidate the entry
930 * yield* Cache.invalidate(cache, "hello")
931 * const afterInvalidation = yield* Cache.has(cache, "hello")
932 *
933 * // Invalidating non-existent keys doesn't error
934 * yield* Cache.invalidate(cache, "nonexistent")
935 *
936 * // Get after invalidation will invoke lookup again
937 * let lookupCount = 0
938 * const cache2 = yield* Cache.make({
939 * capacity: 10,
940 * lookup: (key: string) =>
941 * Effect.sync(() => {
942 * lookupCount++
943 * return key.length
944 * })
945 * })
946 *
947 * yield* Cache.get(cache2, "test") // lookupCount = 1
948 * yield* Cache.invalidate(cache2, "test")
949 * yield* Cache.get(cache2, "test") // lookupCount = 2 (lookup called again)
950 * return { beforeInvalidation, afterInvalidation, lookupCount }
951 * })
952 *
953 * const actual = await Effect.runPromise(program)
954 * actual // => { beforeInvalidation: true, afterInvalidation: false, lookupCount: 2 }
955 * ```
956 *
957 * @category combinators
958 * @since 4.0.0
959 */
960export const invalidate: {
961 <Key, A>(key: Key): <E, R>(self: Cache<Key, A, E, R>) => Effect.Effect<void>
962 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key): Effect.Effect<void>
963} = dual(2, <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key): Effect.Effect<void> =>
964 effect.sync(() => {
965 MutableHashMap.remove(self.map, key)
966 }))
967​
968/**
969 * Invalidates the entry associated with the specified key in the cache when the
970 * predicate returns true for the cached value.
971 *
972 * **Example** (Invalidating entries conditionally)
973 *
974 * ```ts import.meta.vitest
975 * import { Cache, Effect } from "effect"
976 *
977 * const program = Effect.gen(function*() {
978 * const cache = yield* Cache.make({
979 * capacity: 10,
980 * lookup: (key: string) => Effect.succeed(key.length)
981 * })
982 *
983 * // Add values to the cache
984 * yield* Cache.get(cache, "hello") // value = 5
985 * yield* Cache.get(cache, "hi") // value = 2
986 *
987 * // Invalidate when value equals 5
988 * const invalidated1 = yield* Cache.invalidateWhen(
989 * cache,
990 * "hello",
991 * (value) => value === 5
992 * )
993 * const hasHello = yield* Cache.has(cache, "hello")
994 *
995 * // Don't invalidate when predicate doesn't match
996 * const invalidated2 = yield* Cache.invalidateWhen(
997 * cache,
998 * "hi",
999 * (value) => value === 5
1000 * )
1001 * const hasHi = yield* Cache.has(cache, "hi")
1003 * // Returns false for non-existent keys
1004 * const invalidated3 = yield* Cache.invalidateWhen(
1005 * cache,
1006 * "nonexistent",
1007 * () => true
1008 * )
1010 * // Returns false for failed cached values
1011 * const cacheWithErrors = yield* Cache.make<string, number, string>({
1012 * capacity: 10,
1013 * lookup: (key: string) =>
1014 * key === "fail" ? Effect.fail("error") : Effect.succeed(key.length)
1015 * })
1017 * yield* Effect.exit(Cache.get(cacheWithErrors, "fail"))
1018 * const invalidated4 = yield* Cache.invalidateWhen(
1019 * cacheWithErrors,
1020 * "fail",
1021 * () => true
1022 * )
1023 * return [invalidated1, hasHello, invalidated2, hasHi, invalidated3, invalidated4]
1024 * })
1026 * const actual = await Effect.runPromise(program)
1027 * actual // => [true, false, false, true, false, false]
1028 * ```
1030 * @category combinators
1031 * @since 4.0.0
1032 */
1033export const invalidateWhen: {
1034 <Key, A>(key: Key, f: Predicate<A>): <E, R>(self: Cache<Key, A, E, R>) => Effect.Effect<boolean>
1035 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key, f: Predicate<A>): Effect.Effect<boolean>
1036} = dual(
1037 3,
1038 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key, f: Predicate<A>): Effect.Effect<boolean> =>
1039 core.withFiber((fiber) => {
1040 const oentry = getImpl(self, key, fiber, false)
1041 if (oentry === undefined) {
1042 return effect.succeed(false)
1044 return oentry.await().pipe(
1045 effect.map((value) => {
1046 if (f(value)) {
1047 const current = MutableHashMap.get(self.map, key)
1048 if (Option.isNone(current) || current.value !== oentry) {
1049 return false
1051 MutableHashMap.remove(self.map, key)
1052 return true
1054 return false
1055 }),
1056 effect.catchCause(() => effect.succeed(false))
1058 })
1060​
1061/**
1062 * Forces a refresh of the value associated with the specified key in the cache.
1064 * **Details**
1066 * It will always invoke the lookup function to construct a new value,
1067 * overwriting any existing value for that key.
1069 * **Example** (Refreshing cached values)
1071 * ```ts import.meta.vitest
1072 * import { Cache, Effect } from "effect"
1074 * // Force refresh of existing cached values
1075 * const program = Effect.gen(function*() {
1076 * let counter = 0
1077 * const cache = yield* Cache.make({
1078 * capacity: 10,
1079 * lookup: (key: string) => Effect.sync(() => `${key}-${++counter}`)
1080 * })
1082 * // Initial cache population
1083 * const value1 = yield* Cache.get(cache, "user")
1085 * // Get from cache (no lookup)
1086 * const value2 = yield* Cache.get(cache, "user")
1088 * // Force refresh - always calls lookup
1089 * const refreshed = yield* Cache.refresh(cache, "user")
1091 * // Subsequent gets return refreshed value
1092 * const value3 = yield* Cache.get(cache, "user")
1093 * return [value1, value2, refreshed, value3, counter]
1094 * })
1096 * const actual = await Effect.runPromise(program)
1097 * actual // => ["user-1", "user-1", "user-2", "user-2", 2]
1098 * ```
1100 * **Example** (Resetting TTL on refresh)
1102 * ```ts import.meta.vitest
1103 * import { Cache, Effect } from "effect"
1104 * import { TestClock } from "effect/testing"
1106 * // Refresh resets TTL (Time To Live)
1107 * const program = Effect.gen(function*() {
1108 * const cache = yield* Cache.make({
1109 * capacity: 10,
1110 * lookup: (key: string) => Effect.succeed(key.length),
1111 * timeToLive: "1 hour"
1112 * })
1114 * yield* Cache.get(cache, "test")
1115 * yield* TestClock.adjust("45 minutes")
1117 * // Entry would normally expire in 15 minutes
1118 * const beforeRefresh = yield* Cache.has(cache, "test")
1120 * // Refresh resets the TTL to full 1 hour
1121 * yield* Cache.refresh(cache, "test")
1122 * yield* TestClock.adjust("30 minutes")
1124 * // Still valid because TTL was reset
1125 * const afterRefresh = yield* Cache.has(cache, "test")
1126 * return [beforeRefresh, afterRefresh]
1127 * })
1129 * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))
1130 * actual // => [true, true]
1131 * ```
1133 * **Example** (Refreshing missing keys)
1135 * ```ts import.meta.vitest
1136 * import { Cache, Effect } from "effect"
1138 * // Refresh non-existent keys
1139 * const program = Effect.gen(function*() {
1140 * const cache = yield* Cache.make({
1141 * capacity: 10,
1142 * lookup: (key: string) => Effect.succeed(`value-for-${key}`)
1143 * })
1145 * // Refresh non-existent key creates new entry
1146 * const result = yield* Cache.refresh(cache, "newKey")
1148 * // Verify it's now cached
1149 * const cached = yield* Cache.has(cache, "newKey")
1150 * return [result, cached]
1151 * })
1153 * const actual = await Effect.runPromise(program)
1154 * actual // => ["value-for-newKey", true]
1155 * ```
1157 * @category combinators
1158 * @since 4.0.0
1159 */
1160export const refresh: {
1161 <Key, A>(key: Key): <E, R>(self: Cache<Key, A, E, R>) => Effect.Effect<A, E, R>
1162 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key): Effect.Effect<A, E, R>
1163} = dual(
1164 2,
1165 <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key): Effect.Effect<A, E, R> =>
1166 core.withFiber((fiber) => {
1167 const entry = new EntryImpl(fiber, self.lookup(key))
1168 const existing = getImpl(self, key, fiber, false) !== undefined
1169 if (!existing) {
1170 MutableHashMap.set(self.map, key, entry)
1171 checkCapacity(self)
1173 entry.fiber.addObserver((exit) => {
1174 if (effect.exitHasInterrupts(exit)) {
1175 const current = MutableHashMap.get(self.map, key)
1176 if (Option.isSome(current) && current.value === entry) {
1177 MutableHashMap.remove(self.map, key)
1179 return
1181 const ttl = self.timeToLive(exit, key)
1182 if (Duration.isZero(ttl)) {
1183 const current = MutableHashMap.get(self.map, key)
1184 if (existing || (Option.isSome(current) && current.value === entry)) {
1185 MutableHashMap.remove(self.map, key)
1187 return effect.void
1189 entry.expiresAt = Duration.isFinite(ttl)
1190 ? fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe() + Duration.toMillis(ttl)
1191 : undefined
1192 if (existing) {
1193 MutableHashMap.set(self.map, key, entry)
1194 checkCapacity(self)
1196 })
1197 return entry.await()
1198 })
1200​
1201/**
1202 * Invalidates all entries in the cache.
1204 * **Example** (Invalidating all entries)
1206 * ```ts import.meta.vitest
1207 * import { Cache, Effect } from "effect"
1209 * // Clear all cached entries at once
1210 * const program = Effect.gen(function*() {
1211 * const cache = yield* Cache.make({
1212 * capacity: 10,
1213 * lookup: (key: string) => Effect.succeed(key.length)
1214 * })
1216 * // Populate cache with multiple entries
1217 * yield* Cache.get(cache, "apple")
1218 * yield* Cache.get(cache, "banana")
1219 * yield* Cache.get(cache, "cherry")
1221 * const sizeBeforeInvalidation = yield* Cache.size(cache)
1222 * const hasAppleBeforeInvalidation = yield* Cache.has(cache, "apple")
1224 * // Clear all entries
1225 * yield* Cache.invalidateAll(cache)
1227 * // Verify cache is empty
1228 * const sizeAfterInvalidation = yield* Cache.size(cache)
1229 * const hasAppleAfterInvalidation = yield* Cache.has(cache, "apple")
1230 * const hasBananaAfterInvalidation = yield* Cache.has(cache, "banana")
1231 * const hasCherryAfterInvalidation = yield* Cache.has(cache, "cherry")
1232 * return [
1233 * sizeBeforeInvalidation,
1234 * hasAppleBeforeInvalidation,
1235 * sizeAfterInvalidation,
1236 * hasAppleAfterInvalidation,
1237 * hasBananaAfterInvalidation,
1238 * hasCherryAfterInvalidation
1239 * ]
1240 * })
1242 * const actual = await Effect.runPromise(program)
1243 * actual // => [3, true, 0, false, false, false]
1244 * ```
1246 * @category combinators
1247 * @since 4.0.0
1248 */
1249export const invalidateAll = <Key, A, E, R>(self: Cache<Key, A, E, R>): Effect.Effect<void> =>
1250 effect.sync(() => {
1251 MutableHashMap.clear(self.map)
1252 })
1253​
1254/**
1255 * Retrieves the approximate number of entries in the cache.
1257 * **Details**
1259 * Note that expired entries are counted until they are accessed and removed.
1260 * The size reflects the current number of entries stored, not the number
1261 * of valid entries.
1263 * **Example** (Reading cache size)
1265 * ```ts import.meta.vitest
1266 * import { Cache, Effect } from "effect"
1268 * const program = Effect.gen(function*() {
1269 * const cache = yield* Cache.make({
1270 * capacity: 10,
1271 * lookup: (key: string) => Effect.succeed(key.length)
1272 * })
1274 * // Empty cache has size 0
1275 * const emptySize = yield* Cache.size(cache)
1277 * // Add entries and check size
1278 * yield* Cache.get(cache, "hello")
1279 * yield* Cache.get(cache, "world")
1280 * const sizeAfterAdding = yield* Cache.size(cache)
1282 * // Size decreases after invalidation
1283 * yield* Cache.invalidate(cache, "hello")
1284 * const sizeAfterInvalidation = yield* Cache.size(cache)
1285 * return [emptySize, sizeAfterAdding, sizeAfterInvalidation]
1286 * })
1288 * const actual = await Effect.runPromise(program)
1289 * actual // => [0, 2, 1]
1290 * ```
1292 * @category combinators
1293 * @since 4.0.0
1294 */
1295export const size = <Key, A, E, R>(self: Cache<Key, A, E, R>): Effect.Effect<number> =>
1296 effect.sync(() => MutableHashMap.size(self.map))
1297​
1298/**
1299 * Retrieves all active keys from the cache, automatically filtering out expired entries.
1301 * **Example** (Reading active keys)
1303 * ```ts import.meta.vitest
1304 * import { Cache, Effect } from "effect"
1306 * // Basic key enumeration
1307 * const program = Effect.gen(function*() {
1308 * const cache = yield* Cache.make({
1309 * capacity: 10,
1310 * lookup: (key: string) => Effect.succeed(key.length)
1311 * })
1313 * // Add some entries to the cache
1314 * yield* Cache.get(cache, "hello")
1315 * yield* Cache.get(cache, "world")
1316 * yield* Cache.get(cache, "cache")
1318 * // Retrieve all active keys
1319 * const keys = yield* Cache.keys(cache)
1320 * return Array.from(keys).sort()
1321 * })
1323 * const actual = await Effect.runPromise(program)
1324 * actual // => ["cache", "hello", "world"]
1325 * ```
1327 * @category combinators
1328 * @since 4.0.0
1329 */
1330export const keys = <Key, A, E, R>(self: Cache<Key, A, E, R>): Effect.Effect<Iterable<Key>> =>
1331 core.withFiber((fiber) => {
1332 const now = fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe()
1333 return effect.succeed(Iterable.filterMap(self.map, ([key, entry]) => {
1334 if (entry.expiresAt === undefined || entry.expiresAt > now) {
1335 return Result.succeed(key)
1337 MutableHashMap.remove(self.map, key)
1338 return Result.failVoid
1339 }))
1340 })
1341​
1342/**
1343 * Retrieves all successfully cached values from the cache, excluding failed
1344 * lookups and expired entries.
1346 * **Example** (Reading all cached values)
1348 * ```ts import.meta.vitest
1349 * import { Cache, Effect } from "effect"
1351 * const program = Effect.gen(function*() {
1352 * const cache = yield* Cache.make({
1353 * capacity: 10,
1354 * lookup: (key: string) => Effect.succeed(key.length)
1355 * })
1357 * // Add some values to the cache
1358 * yield* Cache.get(cache, "a")
1359 * yield* Cache.get(cache, "ab")
1360 * yield* Cache.get(cache, "abc")
1362 * // Retrieve all cached values
1363 * const values = yield* Cache.values(cache)
1364 * return Array.from(values).sort()
1365 * })
1367 * const actual = await Effect.runPromise(program)
1368 * actual // => [1, 2, 3]
1369 * ```
1371 * @category combinators
1372 * @since 4.0.0
1373 */
1374export const values = <Key, A, E, R>(self: Cache<Key, A, E, R>): Effect.Effect<Iterable<A>> =>
1375 effect.map(entries(self), Iterable.map(([, value]) => value))
1376​
1377/**
1378 * Retrieves all key-value pairs from the cache as an iterable. This function
1379 * only returns entries with successfully resolved values, filtering out any
1380 * failed lookups or expired entries.
1382 * **Gotchas**
1384 * Expired entries are removed from the cache while `entries` filters them out.
1386 * @see {@link keys} for retrieving only cached keys
1387 * @see {@link values} for retrieving only cached values
1389 * @category combinators
1390 * @since 4.0.0
1391 */
1392export const entries = <Key, A, E, R>(self: Cache<Key, A, E, R>): Effect.Effect<Iterable<[Key, A]>> =>
1393 core.withFiber((fiber) => {
1394 const now = fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe()
1395 return effect.succeed(Iterable.filterMap(self.map, ([key, entry]) => {
1396 if (entry.expiresAt === undefined || entry.expiresAt > now) {
1397 const exit = entry.fiber.pollUnsafe()
1398 return exit && exit._tag === "Success"
1399 ? Result.succeed([key, exit.value])
1400 : Result.failVoid
1402 MutableHashMap.remove(self.map, key)
1403 return Result.failVoid
1404 }))
1405 })