MCPcopy
hub / github.com/mastra-ai/mastra / InMemoryServerCache

Class InMemoryServerCache

packages/core/src/cache/inmemory.ts:22–110  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

20}
21
22export class InMemoryServerCache extends MastraServerCache {
23 private cache: TTLCache<string, unknown>;
24 private ttlMs: number;
25
26 constructor(options: InMemoryServerCacheOptions = {}) {
27 super({ name: 'InMemoryServerCache' });
28
29 this.ttlMs = options.ttlMs ?? 1000 * 60 * 5;
30 // TTLCache requires positive integer or Infinity; use Infinity when TTL is disabled
31 const ttl = this.ttlMs > 0 ? this.ttlMs : Infinity;
32
33 this.cache = new TTLCache<string, unknown>({
34 max: options.maxSize ?? 1000,
35 ttl,
36 });
37 }
38
39 async get(key: string): Promise<unknown> {
40 return this.cache.get(key);
41 }
42
43 async set(key: string, value: unknown, ttlMs?: number): Promise<void> {
44 if (ttlMs === undefined) {
45 this.cache.set(key, value);
46 return;
47 }
48 // TTLCache requires positive integer or Infinity; non-positive overrides
49 // mean "no expiry" and must be normalized.
50 this.cache.set(key, value, { ttl: ttlMs > 0 ? ttlMs : Infinity });
51 }
52
53 async listLength(key: string): Promise<number> {
54 const value = this.cache.get(key);
55 if (value === undefined) {
56 return 0; // Key doesn't exist - return 0
57 }
58 if (!Array.isArray(value)) {
59 throw new Error(`${key} exists but is not an array`);
60 }
61 return value.length;
62 }
63
64 async listPush(key: string, value: unknown): Promise<void> {
65 const existing = this.cache.get(key);
66 if (Array.isArray(existing)) {
67 existing.push(value);
68 // Refresh TTL on push by re-setting the key with the updated list
69 if (this.ttlMs > 0) {
70 this.cache.set(key, existing, { ttl: this.ttlMs });
71 }
72 } else if (existing !== undefined) {
73 throw new Error(`${key} exists but is not an array`);
74 } else {
75 this.cache.set(key, [value]);
76 }
77 }
78
79 async listFromTo(key: string, from: number, to: number = -1): Promise<unknown[]> {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…