fix: write models.dev disk cache atomically (#3588)
Use atomic_json_write() from utils.py instead of plain open()/json.dump()
for the models.dev disk cache. Prevents corrupted cache if the process is
killed mid-write — _load_disk_cache() silently returns {} on corrupt JSON,
losing all model metadata until the next successful API fetch.
Co-authored-by: memosr <memosr@users.noreply.github.com>
This commit is contained in:
@@ -15,6 +15,8 @@ import time
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, Optional
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
from utils import atomic_json_write
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -64,12 +66,10 @@ def _load_disk_cache() -> Dict[str, Any]:
|
|||||||
|
|
||||||
|
|
||||||
def _save_disk_cache(data: Dict[str, Any]) -> None:
|
def _save_disk_cache(data: Dict[str, Any]) -> None:
|
||||||
"""Save models.dev data to disk cache."""
|
"""Save models.dev data to disk cache atomically."""
|
||||||
try:
|
try:
|
||||||
cache_path = _get_cache_path()
|
cache_path = _get_cache_path()
|
||||||
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
atomic_json_write(cache_path, data, indent=None, separators=(",", ":"))
|
||||||
with open(cache_path, "w", encoding="utf-8") as f:
|
|
||||||
json.dump(data, f, separators=(",", ":"))
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.debug("Failed to save models.dev disk cache: %s", e)
|
logger.debug("Failed to save models.dev disk cache: %s", e)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user