All files / cache / ttl_cache.ts

98.65% Branches 73/74
100.00% Functions 8/8
99.12% Lines 113/114
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
 
x21
x42
x42
x42
x42
x21
 
 
 
 
 
 
 
 
 
 
 
x21
x21
x21
x21
x42
x42
x3
x3
 
x3
x39
x42
x42
x42
x12
x12
x12
x42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x21
x21
x21
x21
x52
x1
x1
 
x1
 
x52
x52
x3
x3
 
x3
 
x52
x52
x2
x2
 
x2
 
x46
x52
x46
x46
 
x52
x10
x10
x2
x10
x8
x8
x10
 
x46
x52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x45
x44
x27
x45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x7
x3
x7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x28
x28
x28
 
x27
x27
x27
x28
x28
x28
x28
x28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x23
x16
x16
x23
x23
x23
x23
x23
x23
x23
x16
x16
x16
x1
x1
x16
x23
x23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x19
x19
 
x21
x12
 
 
x12
x12
x12
x12
 
x12
x12
x12
x12
x12
 
x12
x21











































































































































































































































































































































































I













// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.

import type { MemoizationCache } from "./memoize.ts";

/**
 * Options for {@linkcode TtlCache.prototype.set}.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 */
export interface TtlCacheSetOptions {
  /**
   * A custom time-to-live in milliseconds for this entry. If supplied,
   * overrides the cache's default TTL. Must be a finite, non-negative number.
   */
  ttl?: number;
  /**
   * A maximum lifetime in milliseconds for this entry, measured from the
   * time it is set. When
   * {@linkcode TtlCacheOptions.slidingExpiration | slidingExpiration} is
   * enabled, the sliding window cannot extend past this duration. Throws
   * if `slidingExpiration` is not enabled.
   */
  absoluteExpiration?: number;
}

/**
 * Options for the {@linkcode TtlCache} constructor.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 */
export interface TtlCacheOptions<K, V> {
  /**
   * Callback invoked when an entry is removed, whether by TTL expiry,
   * manual deletion, or clearing the cache.
   */
  onEject?: (ejectedKey: K, ejectedValue: V) => void;
  /**
   * When `true`, each {@linkcode TtlCache.prototype.get | get()} call resets
   * the entry's TTL.
   *
   * If both `slidingExpiration` and `absoluteExpiration` are set on an entry,
   * the sliding window cannot extend past the absolute expiration.
   *
   * @default {false}
   */
  slidingExpiration?: boolean;
}

/**
 * Time-to-live cache.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * Automatically removes entries after the configured amount of time elapses.
 *
 * @typeParam K The type of the cache keys.
 * @typeParam V The type of the cache values.
 * @example Usage
 * ```ts
 * import { TtlCache } from "@std/cache/ttl-cache";
 * import { assertEquals } from "@std/assert/equals";
 * import { delay } from "@std/async/delay";
 *
 * const cache = new TtlCache<string, number>(1000);
 *
 * cache.set("a", 1);
 * assertEquals(cache.size, 1);
 * await delay(2000);
 * assertEquals(cache.size, 0);
 * ```
 *
 * @example Sliding expiration
 * ```ts
 * import { TtlCache } from "@std/cache/ttl-cache";
 * import { assertEquals } from "@std/assert/equals";
 * import { FakeTime } from "@std/testing/time";
 *
 * using time = new FakeTime(0);
 * const cache = new TtlCache<string, number>(100, {
 *   slidingExpiration: true,
 * });
 *
 * cache.set("a", 1);
 * time.now = 80;
 * assertEquals(cache.get("a"), 1); // resets TTL
 * time.now = 160;
 * assertEquals(cache.get("a"), 1); // still alive, TTL was reset at t=80
 * time.now = 260;
 * assertEquals(cache.get("a"), undefined); // expired
 * ```
 */
export class TtlCache<K, V> extends Map<K, V>
  implements MemoizationCache<K, V> {
  #defaultTtl: number;
  #timeouts = new Map<K, number>();
  #eject?: ((ejectedKey: K, ejectedValue: V) => void) | undefined;
  #slidingExpiration: boolean;
  #entryTtls?: Map<K, number>;
  #absoluteDeadlines?: Map<K, number>;

  /**
   * Constructs a new instance.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @param defaultTtl The default time-to-live in milliseconds. This value must
   * be a finite, non-negative number. Its upper limit is determined by the
   * current runtime's {@linkcode setTimeout} implementation.
   * @param options Additional options.
   */
  constructor(
    defaultTtl: number,
    options?: TtlCacheOptions<K, V>,
  ) {
    super();
    if (!(defaultTtl >= 0) || !Number.isFinite(defaultTtl)) {
      throw new RangeError(
        `Cannot create TtlCache: defaultTtl must be a finite, non-negative number: received ${defaultTtl}`,
      );
    }
    this.#defaultTtl = defaultTtl;
    this.#eject = options?.onEject;
    this.#slidingExpiration = options?.slidingExpiration ?? false;
    if (this.#slidingExpiration) {
      this.#entryTtls = new Map();
      this.#absoluteDeadlines = new Map();
    }
  }

  /**
   * Set a value in the cache.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @param key The cache key.
   * @param value The value to set.
   * @param options Options for this entry.
   * @returns `this` for chaining.
   *
   * @example Usage
   * ```ts
   * import { TtlCache } from "@std/cache/ttl-cache";
   * import { assertEquals } from "@std/assert/equals";
   * import { delay } from "@std/async/delay";
   *
   * const cache = new TtlCache<string, number>(100);
   *
   * cache.set("a", 1);
   * assertEquals(cache.get("a"), 1);
   *
   * await delay(200);
   * assertEquals(cache.get("a"), undefined);
   * ```
   */
  override set(
    key: K,
    value: V,
    options?: TtlCacheSetOptions,
  ): this {
    if (options?.absoluteExpiration !== undefined && !this.#slidingExpiration) {
      throw new TypeError(
        "Cannot set entry in TtlCache: absoluteExpiration requires slidingExpiration to be enabled",
      );
    }

    const ttl = options?.ttl ?? this.#defaultTtl;
    if (!(ttl >= 0) || !Number.isFinite(ttl)) {
      throw new RangeError(
        `Cannot set entry in TtlCache: ttl must be a finite, non-negative number: received ${ttl}`,
      );
    }

    const abs = options?.absoluteExpiration;
    if (abs !== undefined && (!(abs >= 0) || !Number.isFinite(abs))) {
      throw new RangeError(
        `Cannot set entry in TtlCache: absoluteExpiration must be a finite, non-negative number: received ${abs}`,
      );
    }

    const existing = this.#timeouts.get(key);
    if (existing !== undefined) clearTimeout(existing);
    super.set(key, value);
    this.#timeouts.set(key, setTimeout(() => this.delete(key), ttl));

    if (this.#slidingExpiration) {
      this.#entryTtls!.set(key, ttl);
      if (abs !== undefined) {
        this.#absoluteDeadlines!.set(key, Date.now() + abs);
      } else {
        this.#absoluteDeadlines!.delete(key);
      }
    }

    return this;
  }

  /**
   * Gets the value associated with the specified key.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * When {@linkcode TtlCacheOptions.slidingExpiration | slidingExpiration} is
   * enabled, accessing an entry resets its TTL.
   *
   * @param key The key to get the value for.
   * @returns The value associated with the specified key, or `undefined` if
   * the key is not present in the cache.
   *
   * @example Usage
   * ```ts
   * import { TtlCache } from "@std/cache/ttl-cache";
   * import { assertEquals } from "@std/assert/equals";
   *
   * using cache = new TtlCache<string, number>(1000);
   *
   * cache.set("a", 1);
   * assertEquals(cache.get("a"), 1);
   * ```
   */
  override get(key: K): V | undefined {
    if (!super.has(key)) return undefined;
    if (this.#slidingExpiration) this.#resetTtl(key);
    return super.get(key);
  }

  /**
   * Returns the value associated with the given key, or `undefined` if the
   * key is not present, **without** resetting its TTL.
   *
   * This is the TTL-cache equivalent of
   * {@linkcode LruCache.prototype.peek | LruCache.peek()}: a side-effect-free
   * read that leaves the entry's expiration unchanged.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @param key The key to look up.
   * @returns The value, or `undefined` if not present.
   *
   * @example Peeking at a value without resetting the sliding TTL
   * ```ts
   * import { TtlCache } from "@std/cache/ttl-cache";
   * import { assertEquals } from "@std/assert/equals";
   * import { FakeTime } from "@std/testing/time";
   *
   * using time = new FakeTime(0);
   * const cache = new TtlCache<string, number>(100, {
   *   slidingExpiration: true,
   * });
   *
   * cache.set("a", 1);
   * time.now = 80;
   *
   * // peek does not reset the TTL
   * assertEquals(cache.peek("a"), 1);
   *
   * // entry still expires at t=100
   * time.now = 100;
   * assertEquals(cache.peek("a"), undefined);
   * ```
   */
  peek(key: K): V | undefined {
    if (!super.has(key)) return undefined;
    return super.get(key);
  }

  /**
   * Deletes the value associated with the given key.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @param key The key to delete.
   * @returns `true` if the key was deleted, `false` otherwise.
   *
   * @example Usage
   * ```ts
   * import { TtlCache } from "@std/cache";
   * import { assertEquals } from "@std/assert/equals";
   *
   * const cache = new TtlCache<string, number>(1000);
   *
   * cache.set("a", 1);
   * cache.delete("a");
   * assertEquals(cache.has("a"), false);
   * ```
   */
  override delete(key: K): boolean {
    const value = super.get(key);
    const existed = super.delete(key);
    if (!existed) return false;

    const timeout = this.#timeouts.get(key);
    if (timeout !== undefined) clearTimeout(timeout);
    this.#timeouts.delete(key);
    this.#entryTtls?.delete(key);
    this.#absoluteDeadlines?.delete(key);
    this.#eject?.(key, value!);
    return true;
  }

  /**
   * Clears the cache.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @example Usage
   * ```ts
   * import { TtlCache } from "@std/cache";
   * import { assertEquals } from "@std/assert/equals";
   *
   * const cache = new TtlCache<string, number>(1000);
   *
   * cache.set("a", 1);
   * cache.set("b", 2);
   * cache.clear();
   * assertEquals(cache.size, 0);
   * ```
   */
  override clear(): void {
    for (const timeout of this.#timeouts.values()) {
      clearTimeout(timeout);
    }
    this.#timeouts.clear();
    this.#entryTtls?.clear();
    this.#absoluteDeadlines?.clear();
    const entries = [...super.entries()];
    super.clear();
    let error: unknown;
    for (const [key, value] of entries) {
      try {
        this.#eject?.(key, value);
      } catch (e) {
        error ??= e;
      }
    }
    if (error !== undefined) throw error;
  }

  /**
   * Automatically clears all remaining timeouts once the cache goes out of
   * scope if the cache is declared with `using`.
   *
   * @experimental **UNSTABLE**: New API, yet to be vetted.
   *
   * @example Usage
   * ```ts no-assert
   * import { TtlCache } from "@std/cache/ttl-cache";
   * import { assertEquals } from "@std/assert/equals";
   *
   * let c: TtlCache<string, number>;
   * {
   *  using cache = new TtlCache<string, number>(1000);
   *  cache.set("a", 1);
   *  c = cache;
   * }
   * assertEquals(c.size, 0);
   * ```
   */
  [Symbol.dispose](): void {
    this.clear();
  }

  #resetTtl(key: K): void {
    const ttl = this.#entryTtls!.get(key);
    if (ttl === undefined) return;

    const deadline = this.#absoluteDeadlines!.get(key);
    const effectiveTtl = deadline !== undefined
      ? Math.min(ttl, Math.max(0, deadline - Date.now()))
      : ttl;

    const existing = this.#timeouts.get(key);
    if (existing !== undefined) clearTimeout(existing);
    this.#timeouts.set(
      key,
      setTimeout(() => this.delete(key), effectiveTtl),
    );
  }
}