From f06b3e98762a1d8f15559ca269669c9bf4fcebcd Mon Sep 17 00:00:00 2001 From: Mustafa Tiritoglu Date: Mon, 16 Nov 2026 21:57:10 -0700 Subject: [PATCH 1/3] Move JSON load/save into a shared JsonRepository base RestaurantRepository now just passes its file path and model to the base, so customers/carts/orders can reuse the same loading and atomic saving instead of copying it. Public methods are unchanged. Updated two repository tests that patched the old module path and added tests for the base class. --- backend/app/repositories/json_repository.py | 55 +++++++++++++++++ .../app/repositories/restaurant_repository.py | 59 +++---------------- backend/tests/test_json_repository.py | 49 +++++++++++++++ backend/tests/test_restaurants_repository.py | 8 +-- 4 files changed, 116 insertions(+), 55 deletions(-) create mode 100644 backend/app/repositories/json_repository.py create mode 100644 backend/tests/test_json_repository.py diff --git a/backend/app/repositories/json_repository.py b/backend/app/repositories/json_repository.py new file mode 100644 index 0000000..6614177 --- /dev/null +++ b/backend/app/repositories/json_repository.py @@ -0,0 +1,55 @@ +from pathlib import Path +import json +from json import JSONDecodeError +import os +import tempfile +import warnings + +from pydantic import BaseModel, TypeAdapter, ValidationError + + +class JsonRepository[T: BaseModel]: + """Shared load/save code for repositories that keep a list of models in one JSON file. + + Each repository (restaurants, customers, carts, orders...) only has to pass in its file + path and model class. The reading, validating and atomic saving live here once. + """ + + def __init__(self, file_path: Path, model: type[T]) -> None: + self.file_path: Path = file_path + self.model: type[T] = model + self._list_adapter = TypeAdapter(list[model]) + + def _load_all(self) -> list[T]: + if not self.file_path.exists(): + warnings.warn(f"'{self.file_path.absolute()}' does not exist. Defaulting to an empty list.") + return [] + + with open(self.file_path, "r", encoding="utf-8") as file: + try: + return self._list_adapter.validate_python(json.load(file)) + except JSONDecodeError as e: + raise JSONDecodeError(f"{self.file_path.absolute()} is not JSON serializable.", e.doc, e.pos) from e + except ValidationError as e: + raise ValueError(f"{self.file_path.absolute()} does not follow the correct list[{self.model.__name__}] schema.") from e + + def _save_all(self, items: list[T]) -> None: + # Write to a temp file in the same folder first, then swap it in with os.replace. + # If anything fails halfway, the original file is left untouched. + temp_file_path = None + + try: + with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=self.file_path.parent, delete=False, suffix=".tmp") as temp_file: + temp_file_path = temp_file.name + json.dump([item.model_dump(mode="json") for item in items], temp_file, indent=4) + + os.replace(temp_file_path, self.file_path) + + except OSError as e: + if temp_file_path is not None: + try: + os.remove(temp_file_path) # don't leave failed temp files behind + except FileNotFoundError: + pass + + raise OSError(f"Failed to save to '{self.file_path.absolute()}'") from e diff --git a/backend/app/repositories/restaurant_repository.py b/backend/app/repositories/restaurant_repository.py index 7b50f42..cf75f1a 100644 --- a/backend/app/repositories/restaurant_repository.py +++ b/backend/app/repositories/restaurant_repository.py @@ -1,64 +1,21 @@ from pathlib import Path -import json -from json import JSONDecodeError -from pydantic import TypeAdapter, ValidationError -import warnings + +from .json_repository import JsonRepository from ..schemas.restaurant import Restaurant -import os -import tempfile -restaurants_list_adapter = TypeAdapter(list[Restaurant]) -class RestaurantRepository: +class RestaurantRepository(JsonRepository[Restaurant]): def __init__(self, restaurants_file_path: Path) -> None: - self.restaurants_file_path: Path = restaurants_file_path - - def __load_restaurants(self) -> list[Restaurant]: - if not self.restaurants_file_path.exists(): - warnings.warn(f"'{self.restaurants_file_path.absolute()}' does not exist. Defaulting to empty restaurants list.") - return [] - - with open(self.restaurants_file_path, "r", encoding="utf-8") as restaurants_file: - try: - return restaurants_list_adapter.validate_python(json.load(restaurants_file)) - except JSONDecodeError as e: - raise JSONDecodeError(f"{self.restaurants_file_path.absolute()} is not JSON serializable.", e.doc, e.pos) from e - except ValidationError as e: - raise ValueError(f"{self.restaurants_file_path.absolute()} does not follow the correct list[Restaurant] schema. See backend/app/schemas/restaurant.py or visit https://www.schema.org/Restaurant for schema specifications.") from e - - def __save_restaurants(self, restaurants: list[Restaurant]) -> None: - temp_file_path = None - - try: - with tempfile.NamedTemporaryFile(mode = "w", - encoding = "utf-8", - dir = self.restaurants_file_path.parent, #creates temporary file in the same directory as the original JSON - delete = False, # so python won't delete this file when the while bloack is exited - suffix = ".tmp") as temp_file: - temp_file_path = temp_file.name - - json.dump([restaurant.model_dump(mode="json") for restaurant in restaurants], temp_file, indent=4) - - os.replace(temp_file_path, self.restaurants_file_path) - - except OSError as e: - if temp_file_path is not None: - try: - os.remove(temp_file_path) # removes failed temp files so that they don't accumulate - except FileNotFoundError: - pass - - raise OSError(f"Failed to save restaurants to '{self.restaurants_file_path.absolute()}'") from e + super().__init__(restaurants_file_path, Restaurant) def get_all_restaurants(self) -> list[Restaurant]: - return self.__load_restaurants() + return self._load_all() def save_restaurants(self, restaurants: list[Restaurant]) -> None: - self.__save_restaurants(restaurants) + self._save_all(restaurants) + def get_restaurant_by_id(self, restaurant_id: str) -> Restaurant | None: - restaurants = self.get_all_restaurants() - - for restaurant in restaurants: + for restaurant in self.get_all_restaurants(): if restaurant.id == restaurant_id: return restaurant return None diff --git a/backend/tests/test_json_repository.py b/backend/tests/test_json_repository.py new file mode 100644 index 0000000..e38bd52 --- /dev/null +++ b/backend/tests/test_json_repository.py @@ -0,0 +1,49 @@ +import json +from unittest.mock import patch + +import pytest +from pydantic import BaseModel + +from backend.app.repositories.json_repository import JsonRepository + + +class Item(BaseModel): + id: str + name: str + + +def test_save_then_load_returns_the_same_items(tmp_path): + repo = JsonRepository(tmp_path / "items.json", Item) + + repo._save_all([Item(id="1", name="first"), Item(id="2", name="second")]) + + assert repo._load_all() == [Item(id="1", name="first"), Item(id="2", name="second")] + + +def test_missing_file_loads_as_empty_list(tmp_path): + repo = JsonRepository(tmp_path / "missing.json", Item) + + with pytest.warns(UserWarning): + assert repo._load_all() == [] + + +def test_file_with_wrong_schema_raises_value_error(tmp_path): + file_path = tmp_path / "items.json" + file_path.write_text(json.dumps([{"id": "1"}])) + repo = JsonRepository(file_path, Item) + + with pytest.raises(ValueError, match=r"list\[Item\]"): + repo._load_all() + + +def test_failed_save_keeps_the_old_file_and_leaves_no_temp_file(tmp_path): + file_path = tmp_path / "items.json" + repo = JsonRepository(file_path, Item) + repo._save_all([Item(id="1", name="original")]) + + with patch("backend.app.repositories.json_repository.os.replace", side_effect=OSError("disk full")): + with pytest.raises(OSError, match="Failed to save"): + repo._save_all([Item(id="2", name="new")]) + + assert repo._load_all() == [Item(id="1", name="original")] + assert list(tmp_path.glob("*.tmp")) == [] diff --git a/backend/tests/test_restaurants_repository.py b/backend/tests/test_restaurants_repository.py index 3904af3..a5b85d7 100644 --- a/backend/tests/test_restaurants_repository.py +++ b/backend/tests/test_restaurants_repository.py @@ -85,18 +85,18 @@ def test_repository_saves_restaurants(tmp_path): assert reloaded[0].name == restaurants[0].name -@patch("backend.app.repositories.restaurant_repository.tempfile.NamedTemporaryFile", side_effect=PermissionError("Permission denied")) +@patch("backend.app.repositories.json_repository.tempfile.NamedTemporaryFile", side_effect=PermissionError("Permission denied")) def test_repository_handles_save_error(mock_file, tmp_path): repo = RestaurantRepository(tmp_path / "restaurants.json") - with pytest.raises(OSError, match="Failed to save restaurants"): + with pytest.raises(OSError, match="Failed to save"): repo.save_restaurants([]) -@patch("backend.app.repositories.restaurant_repository.os.replace", side_effect=OSError("replace failed")) +@patch("backend.app.repositories.json_repository.os.replace", side_effect=OSError("replace failed")) def test_repository_handles_replace_error(mock_replace, tmp_path): output_file = tmp_path / "restaurants.json" repo = RestaurantRepository(output_file) - with pytest.raises(OSError, match="Failed to save restaurants"): + with pytest.raises(OSError, match="Failed to save"): repo.save_restaurants([]) \ No newline at end of file From 94e3c978b9c68740ca4710442d97c52e943dd8fb Mon Sep 17 00:00:00 2001 From: Mustafa Tiritoglu Date: Mon, 16 Nov 2026 22:02:06 -0700 Subject: [PATCH 2/3] Add a per-file lock to JsonRepository Requests run in parallel threads, so two requests could both load the file and the second save would wipe out the first one's change. lock() gives one lock per JSON file that services can hold around load -> change -> save. Without it the new test only keeps 1 of 8 items. --- backend/app/repositories/json_repository.py | 15 ++++++++++ backend/tests/test_json_repository.py | 33 +++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/backend/app/repositories/json_repository.py b/backend/app/repositories/json_repository.py index 6614177..7212c0d 100644 --- a/backend/app/repositories/json_repository.py +++ b/backend/app/repositories/json_repository.py @@ -3,10 +3,16 @@ from json import JSONDecodeError import os import tempfile +import threading import warnings from pydantic import BaseModel, TypeAdapter, ValidationError +# One lock per JSON file, shared by every repository object that points at that file. +# (A new repository is created for each request, so the lock can't live on the object itself.) +_file_locks: dict[Path, threading.RLock] = {} +_file_locks_guard = threading.Lock() + class JsonRepository[T: BaseModel]: """Shared load/save code for repositories that keep a list of models in one JSON file. @@ -20,6 +26,15 @@ def __init__(self, file_path: Path, model: type[T]) -> None: self.model: type[T] = model self._list_adapter = TypeAdapter(list[model]) + def lock(self) -> threading.RLock: + """Hold this around a load -> change -> save, e.g. `with repository.lock(): ...`. + + Requests run in parallel threads, so without it two requests can both load the file, + each add their change, and the second save silently wipes out the first. + """ + with _file_locks_guard: + return _file_locks.setdefault(self.file_path.resolve(), threading.RLock()) + def _load_all(self) -> list[T]: if not self.file_path.exists(): warnings.warn(f"'{self.file_path.absolute()}' does not exist. Defaulting to an empty list.") diff --git a/backend/tests/test_json_repository.py b/backend/tests/test_json_repository.py index e38bd52..bd9840c 100644 --- a/backend/tests/test_json_repository.py +++ b/backend/tests/test_json_repository.py @@ -1,4 +1,6 @@ import json +import threading +import time from unittest.mock import patch import pytest @@ -47,3 +49,34 @@ def test_failed_save_keeps_the_old_file_and_leaves_no_temp_file(tmp_path): assert repo._load_all() == [Item(id="1", name="original")] assert list(tmp_path.glob("*.tmp")) == [] + + +def test_lock_stops_parallel_saves_from_overwriting_each_other(tmp_path): + file_path = tmp_path / "items.json" + JsonRepository(file_path, Item)._save_all([]) + + def add_item(number): + # A new repository per call, like a new request + repo = JsonRepository(file_path, Item) + with repo.lock(): + items = repo._load_all() + time.sleep(0.01) # widen the gap between load and save + items.append(Item(id=str(number), name=f"item {number}")) + repo._save_all(items) + + threads = [threading.Thread(target=add_item, args=(n,)) for n in range(8)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert len(JsonRepository(file_path, Item)._load_all()) == 8 + + +def test_repositories_for_the_same_file_share_one_lock(tmp_path): + first = JsonRepository(tmp_path / "items.json", Item) + second = JsonRepository(tmp_path / "items.json", Item) + other = JsonRepository(tmp_path / "other.json", Item) + + assert first.lock() is second.lock() + assert first.lock() is not other.lock() From ea5038524c744ae4e1b4916a8166ca2551b41467 Mon Sep 17 00:00:00 2001 From: Mustafa Tiritoglu Date: Tue, 17 Nov 2026 13:54:06 -0700 Subject: [PATCH 3/3] Remove the temp file whatever makes a save fail Before, only OSError cleaned it up, so a TypeError/ValueError from json.dump left a .tmp file behind (from Nathan's review). Cleanup is now in a finally block. OSError is still wrapped with the file path like before. --- backend/app/repositories/json_repository.py | 9 ++++++--- backend/tests/test_json_repository.py | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/backend/app/repositories/json_repository.py b/backend/app/repositories/json_repository.py index 7212c0d..42080c6 100644 --- a/backend/app/repositories/json_repository.py +++ b/backend/app/repositories/json_repository.py @@ -59,12 +59,15 @@ def _save_all(self, items: list[T]) -> None: json.dump([item.model_dump(mode="json") for item in items], temp_file, indent=4) os.replace(temp_file_path, self.file_path) + temp_file_path = None # the temp file is now the real file except OSError as e: + raise OSError(f"Failed to save to '{self.file_path.absolute()}'") from e + + finally: + # Whatever went wrong (disk error, data that can't be turned into JSON...), don't leave the temp file behind if temp_file_path is not None: try: - os.remove(temp_file_path) # don't leave failed temp files behind + os.remove(temp_file_path) except FileNotFoundError: pass - - raise OSError(f"Failed to save to '{self.file_path.absolute()}'") from e diff --git a/backend/tests/test_json_repository.py b/backend/tests/test_json_repository.py index bd9840c..32389d9 100644 --- a/backend/tests/test_json_repository.py +++ b/backend/tests/test_json_repository.py @@ -80,3 +80,17 @@ def test_repositories_for_the_same_file_share_one_lock(tmp_path): assert first.lock() is second.lock() assert first.lock() is not other.lock() + + +@pytest.mark.parametrize("error", [TypeError("not JSON serializable"), ValueError("bad value")]) +def test_save_that_fails_while_writing_json_leaves_no_temp_file(tmp_path, error): + file_path = tmp_path / "items.json" + repo = JsonRepository(file_path, Item) + repo._save_all([Item(id="1", name="original")]) + + with patch("backend.app.repositories.json_repository.json.dump", side_effect=error): + with pytest.raises(type(error)): + repo._save_all([Item(id="2", name="new")]) + + assert repo._load_all() == [Item(id="1", name="original")] + assert list(tmp_path.glob("*.tmp")) == []