Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions backend/app/repositories/json_repository.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from pathlib import Path
import json
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.

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 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.")
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)
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)
except FileNotFoundError:
pass
59 changes: 8 additions & 51 deletions backend/app/repositories/restaurant_repository.py
Original file line number Diff line number Diff line change
@@ -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
96 changes: 96 additions & 0 deletions backend/tests/test_json_repository.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import json
import threading
import time
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")) == []


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()


@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")) == []
8 changes: 4 additions & 4 deletions backend/tests/test_restaurants_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -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([])
Loading