| 43 | } |
| 44 | |
| 45 | export function cacheLargeValue( |
| 46 | id: string, |
| 47 | value: unknown, |
| 48 | size: number, |
| 49 | scope?: LargeValueCacheScope, |
| 50 | options: { recoverable?: boolean } = {} |
| 51 | ): boolean { |
| 52 | if (size > MAX_IN_MEMORY_BYTES) { |
| 53 | return false |
| 54 | } |
| 55 | |
| 56 | cleanupExpiredValues() |
| 57 | |
| 58 | const existing = inMemoryValues.get(id) |
| 59 | if (existing) { |
| 60 | inMemoryValues.delete(id) |
| 61 | inMemoryBytes -= existing.size |
| 62 | } |
| 63 | |
| 64 | while (inMemoryBytes + size > MAX_IN_MEMORY_BYTES && inMemoryValues.size > 0) { |
| 65 | const oldestRecoverableId = Array.from(inMemoryValues.entries()).find( |
| 66 | ([, entry]) => entry.recoverable |
| 67 | )?.[0] |
| 68 | if (!oldestRecoverableId) break |
| 69 | const oldest = inMemoryValues.get(oldestRecoverableId) |
| 70 | inMemoryValues.delete(oldestRecoverableId) |
| 71 | inMemoryBytes -= oldest?.size ?? 0 |
| 72 | } |
| 73 | |
| 74 | if (inMemoryBytes + size > MAX_IN_MEMORY_BYTES) { |
| 75 | if (existing) { |
| 76 | inMemoryValues.set(id, existing) |
| 77 | inMemoryBytes += existing.size |
| 78 | } |
| 79 | return false |
| 80 | } |
| 81 | |
| 82 | inMemoryValues.set(id, { |
| 83 | value, |
| 84 | size, |
| 85 | scope, |
| 86 | recoverable: options.recoverable ?? false, |
| 87 | expiresAt: Date.now() + FALLBACK_TTL_MS, |
| 88 | }) |
| 89 | inMemoryBytes += size |
| 90 | return true |
| 91 | } |
| 92 | |
| 93 | function scopeMatchesRef( |
| 94 | ref: LargeValueRef, |