|
| 1 | +import { consola } from 'consola'; |
| 2 | + |
| 3 | +const logger = consola.withTag('version-cache'); |
| 4 | + |
| 5 | +export interface FetchResult { |
| 6 | + version: string |
| 7 | + lastModified?: Date |
| 8 | +} |
| 9 | + |
| 10 | +interface StoredVersion { |
| 11 | + version?: string // omitted for failed lookups — avoids null in JSON |
| 12 | + lastModified: string // ISO 8601 — Date doesn't survive JSON round-trip |
| 13 | +} |
| 14 | + |
| 15 | +interface InflightResult { |
| 16 | + result: FetchResult | undefined |
| 17 | + lastModified: Date |
| 18 | + ttl: number |
| 19 | +} |
| 20 | + |
| 21 | +const TTL_OK = 3600; // 1 hour |
| 22 | +const TTL_ERROR = 60; // 1 minute |
| 23 | + |
| 24 | +// In-flight deduplication — only holds promises for active upstream |
| 25 | +// fetches, so naturally bounded by concurrency, not by key space. |
| 26 | +// The originating caller writes to KV; joiners just read the result. |
| 27 | +const inflight = new Map<string, Promise<InflightResult>>(); |
| 28 | + |
| 29 | +/** Remove a cached version entry, forcing a fresh upstream poll. */ |
| 30 | +export async function deleteCachedVersion(key: string): Promise<void> { |
| 31 | + inflight.delete(key); // any running IIFE will see it lost its slot and skip the KV write |
| 32 | + try { |
| 33 | + await useStorage('versions').removeItem(key); |
| 34 | + } catch (error) { |
| 35 | + logger.warn(`failed to delete ${key}:`, error); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Returns the last known version, polling upstream only when |
| 41 | + * the KV entry has expired. Uses the upstream publish time |
| 42 | + * when available, otherwise falls back to the current time. |
| 43 | + * |
| 44 | + * Degrades gracefully — KV failures fall through to an |
| 45 | + * upstream fetch rather than crashing the handler. |
| 46 | + */ |
| 47 | +export async function fetchVersion( |
| 48 | + key: string, |
| 49 | + fetcher: () => Promise<FetchResult | undefined>, |
| 50 | +): Promise<{ version: string | undefined; lastModified: Date }> { |
| 51 | + const storage = useStorage('versions'); |
| 52 | + |
| 53 | + // KV cache hit — return stored data directly |
| 54 | + try { |
| 55 | + const stored = await storage.getItem<StoredVersion>(key); |
| 56 | + if (stored) { |
| 57 | + return { |
| 58 | + version: stored.version, |
| 59 | + lastModified: new Date(stored.lastModified), |
| 60 | + }; |
| 61 | + } |
| 62 | + } catch (error) { |
| 63 | + logger.warn(`KV read failed for ${key}:`, error); |
| 64 | + } |
| 65 | + |
| 66 | + // KV miss or expired — poll upstream with in-flight dedup. |
| 67 | + // The first caller fetches + writes KV; concurrent joiners |
| 68 | + // just await the same result without duplicate writes. |
| 69 | + let pending = inflight.get(key); |
| 70 | + if (!pending) { |
| 71 | + pending = (async () => { |
| 72 | + let result: FetchResult | undefined; |
| 73 | + try { |
| 74 | + result = await fetcher(); |
| 75 | + } catch (error) { |
| 76 | + logger.warn(`upstream fetch failed for ${key}:`, error); |
| 77 | + } |
| 78 | + const version = result?.version; |
| 79 | + const lastModified = result?.lastModified ?? new Date(); |
| 80 | + const ttl = version === undefined ? TTL_ERROR : TTL_OK; |
| 81 | + |
| 82 | + const entry: StoredVersion = { lastModified: lastModified.toISOString() }; |
| 83 | + if (version) entry.version = version; |
| 84 | + |
| 85 | + // Skip the write if a DELETE evicted us from inflight mid-fetch |
| 86 | + if (inflight.get(key) === pending) { |
| 87 | + try { |
| 88 | + await storage.setItem(key, entry, { ttl }); |
| 89 | + } catch (error) { |
| 90 | + logger.warn(`KV write failed for ${key}:`, error); |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + return { result, lastModified, ttl }; |
| 95 | + })(); |
| 96 | + inflight.set(key, pending); |
| 97 | + pending.finally(() => { |
| 98 | + if (inflight.get(key) === pending) inflight.delete(key); |
| 99 | + }); |
| 100 | + } |
| 101 | + |
| 102 | + const { result, lastModified } = await pending; |
| 103 | + return { version: result?.version, lastModified }; |
| 104 | +} |
0 commit comments