|
| 1 | +import {ensureDirectory, fileExists, readJson, writeJson} from "./fs-utils.js"; |
| 2 | +import path from "node:path"; |
| 3 | + |
| 4 | +const DEFAULT_VERSION = 1; |
| 5 | + |
| 6 | +function normalizeKey (key) { |
| 7 | + if (typeof key !== "string" || key.length === 0) { |
| 8 | + throw new TypeError("Persistent cache keys must be non-empty strings"); |
| 9 | + } |
| 10 | + return key; |
| 11 | +} |
| 12 | + |
| 13 | +function cloneCacheEntry (entry) { |
| 14 | + const cloned = { |
| 15 | + value: structuredClone(entry.value), |
| 16 | + updatedAt: entry.updatedAt, |
| 17 | + expiresAt: entry.expiresAt, |
| 18 | + ttlMs: entry.ttlMs |
| 19 | + }; |
| 20 | + if (entry.metadata) { |
| 21 | + cloned.metadata = structuredClone(entry.metadata); |
| 22 | + } |
| 23 | + return cloned; |
| 24 | +} |
| 25 | + |
| 26 | +function buildStoredEntry ({value, metadata, expiresAt, timestamp, ttlMs}) { |
| 27 | + const stored = { |
| 28 | + value: structuredClone(value), |
| 29 | + updatedAt: timestamp, |
| 30 | + expiresAt, |
| 31 | + ttlMs: ttlMs ?? null |
| 32 | + }; |
| 33 | + if (metadata) { |
| 34 | + stored.metadata = structuredClone(metadata); |
| 35 | + } |
| 36 | + return stored; |
| 37 | +} |
| 38 | + |
| 39 | +function toIsoString (timestamp) { |
| 40 | + return new Date(timestamp).toISOString(); |
| 41 | +} |
| 42 | + |
| 43 | +function isExpired ({expiresAt}, now) { |
| 44 | + if (!expiresAt) { |
| 45 | + return false; |
| 46 | + } |
| 47 | + |
| 48 | + return new Date(expiresAt).getTime() <= now; |
| 49 | +} |
| 50 | + |
| 51 | +function createEmptyState ({version}) { |
| 52 | + return { |
| 53 | + version, |
| 54 | + generatedAt: toIsoString(Date.now()), |
| 55 | + entries: {} |
| 56 | + }; |
| 57 | +} |
| 58 | + |
| 59 | +export function createPersistentCache ({filePath, version = DEFAULT_VERSION, defaultTtlMs = 0, now = () => Date.now()} = {}) { |
| 60 | + if (typeof filePath !== "string" || filePath.length === 0) { |
| 61 | + throw new TypeError("createPersistentCache requires a non-empty filePath"); |
| 62 | + } |
| 63 | + |
| 64 | + const resolvedPath = path.resolve(filePath); |
| 65 | + const state = createEmptyState({version}); |
| 66 | + let loaded = false; |
| 67 | + let dirty = false; |
| 68 | + |
| 69 | + async function load () { |
| 70 | + if (loaded) { |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + if (await fileExists(resolvedPath)) { |
| 75 | + try { |
| 76 | + const stored = await readJson(resolvedPath); |
| 77 | + if (stored && typeof stored === "object" && stored.entries) { |
| 78 | + state.version = stored.version ?? version; |
| 79 | + state.generatedAt = stored.generatedAt ?? toIsoString(now()); |
| 80 | + state.entries = stored.entries ?? {}; |
| 81 | + } |
| 82 | + } catch (error) { |
| 83 | + const message = error instanceof Error ? error.message : String(error); |
| 84 | + throw new Error(`Failed to load persistent cache at ${resolvedPath}: ${message}`, {cause: error}); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + loaded = true; |
| 89 | + await pruneExpired(); |
| 90 | + } |
| 91 | + |
| 92 | + function snapshot () { |
| 93 | + return { |
| 94 | + version: state.version, |
| 95 | + generatedAt: state.generatedAt, |
| 96 | + entries: state.entries |
| 97 | + }; |
| 98 | + } |
| 99 | + |
| 100 | + function pruneExpired () { |
| 101 | + const current = now(); |
| 102 | + let removed = false; |
| 103 | + |
| 104 | + for (const [key, entry] of Object.entries(state.entries)) { |
| 105 | + if (isExpired(entry, current)) { |
| 106 | + delete state.entries[key]; |
| 107 | + removed = true; |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + if (removed) { |
| 112 | + dirty = true; |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + function get (key) { |
| 117 | + const normalizedKey = normalizeKey(key); |
| 118 | + const entry = state.entries[normalizedKey]; |
| 119 | + |
| 120 | + if (!entry) { |
| 121 | + return null; |
| 122 | + } |
| 123 | + |
| 124 | + if (isExpired(entry, now())) { |
| 125 | + delete state.entries[normalizedKey]; |
| 126 | + dirty = true; |
| 127 | + return null; |
| 128 | + } |
| 129 | + |
| 130 | + return cloneCacheEntry(entry); |
| 131 | + } |
| 132 | + |
| 133 | + function set (key, value, {ttlMs = defaultTtlMs, metadata} = {}) { |
| 134 | + const normalizedKey = normalizeKey(key); |
| 135 | + const current = now(); |
| 136 | + const expiresAt = ttlMs && ttlMs > 0 ? toIsoString(current + ttlMs) : null; |
| 137 | + |
| 138 | + state.entries[normalizedKey] = buildStoredEntry({ |
| 139 | + value, |
| 140 | + metadata, |
| 141 | + expiresAt, |
| 142 | + timestamp: toIsoString(current), |
| 143 | + ttlMs |
| 144 | + }); |
| 145 | + dirty = true; |
| 146 | + return cloneCacheEntry(state.entries[normalizedKey]); |
| 147 | + } |
| 148 | + |
| 149 | + function deleteKey (key) { |
| 150 | + const normalizedKey = normalizeKey(key); |
| 151 | + if (Object.hasOwn(state.entries, normalizedKey)) { |
| 152 | + delete state.entries[normalizedKey]; |
| 153 | + dirty = true; |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + function entries () { |
| 158 | + return Object.entries(state.entries).map(([key, entry]) => ({key, entry: cloneCacheEntry(entry)})); |
| 159 | + } |
| 160 | + |
| 161 | + async function flush () { |
| 162 | + if (!loaded || !dirty) { |
| 163 | + return; |
| 164 | + } |
| 165 | + |
| 166 | + const dirPath = path.dirname(resolvedPath); |
| 167 | + await ensureDirectory(dirPath); |
| 168 | + |
| 169 | + const snapshotData = snapshot(); |
| 170 | + snapshotData.generatedAt = toIsoString(now()); |
| 171 | + await writeJson(resolvedPath, snapshotData, {pretty: 2, ensureDir: true}); |
| 172 | + dirty = false; |
| 173 | + } |
| 174 | + |
| 175 | + return { |
| 176 | + load, |
| 177 | + flush, |
| 178 | + get, |
| 179 | + set, |
| 180 | + delete: deleteKey, |
| 181 | + entries, |
| 182 | + pruneExpired, |
| 183 | + snapshot |
| 184 | + }; |
| 185 | +} |
0 commit comments