fix(cli): make models snapshot cache write and read fault-tolerant

This commit is contained in:
marius-kilocode
2026-08-07 14:08:59 +02:00
parent cb2bd4df5e
commit 3f05a2a536
+18 -7
View File
@@ -16,21 +16,32 @@ const raw = await (async () => {
return await Bun.file(process.env.MODELS_DEV_API_JSON).text()
}
const cached = Bun.file(cacheFile)
const exists = await cached.exists()
if (exists) {
const st = await cached.stat()
if (st && Date.now() - st.mtimeMs < 6 * 3600 * 1000) {
return await cached.text()
try {
if (await cached.exists()) {
const st = await cached.stat()
if (st && Date.now() - st.mtimeMs < 6 * 3600 * 1000) {
return await cached.text()
}
}
} catch (err) {
console.warn("[generate] cache read check failed, fetching live", err)
}
try {
const res = await fetch(`${modelsUrl}/api.json`, { signal: AbortSignal.timeout(5000) })
if (!res.ok) throw new Error(`Failed to fetch models.dev snapshot: HTTP ${res.status}`)
const text = await res.text()
await Bun.write(cacheFile, text)
try {
await Bun.write(cacheFile, text)
} catch (err) {
console.warn("[generate] cache write failed", err)
}
return text
} catch (err) {
if (exists) return await cached.text()
try {
if (await cached.exists()) return await cached.text()
} catch (fallbackErr) {
console.warn("[generate] cache fallback read failed", fallbackErr)
}
throw err
}
})()