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