Skip to content

Commit fde1fb7

Browse files
authored
Merge pull request #78 from OpenDash-Team/fix/json-save-retry
Retry JSON file swap on Windows file locks
2 parents 8409179 + 973a8f3 commit fde1fb7

2 files changed

Lines changed: 55 additions & 7 deletions

File tree

‎backend/app/repositories/json_repository.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
import tempfile
66
import threading
7+
import time
78
import warnings
89

910
from pydantic import BaseModel, TypeAdapter, ValidationError
@@ -13,6 +14,11 @@
1314
_file_locks: dict[Path, threading.RLock] = {}
1415
_file_locks_guard = threading.Lock()
1516

17+
# On Windows, os.replace fails with PermissionError if another program (antivirus, search indexer)
18+
# has the file open for a moment, so the swap is retried a few times before giving up.
19+
REPLACE_ATTEMPTS = 5
20+
REPLACE_RETRY_DELAY = 0.05 # seconds
21+
1622

1723
class JsonRepository[T: BaseModel]:
1824
"""Shared load/save code for repositories that keep a list of models in one JSON file.
@@ -58,7 +64,7 @@ def _save_all(self, items: list[T]) -> None:
5864
temp_file_path = temp_file.name
5965
json.dump([item.model_dump(mode="json") for item in items], temp_file, indent=4)
6066

61-
os.replace(temp_file_path, self.file_path)
67+
self._replace_with_retry(temp_file_path)
6268
temp_file_path = None # the temp file is now the real file
6369

6470
except OSError as e:
@@ -71,3 +77,13 @@ def _save_all(self, items: list[T]) -> None:
7177
os.remove(temp_file_path)
7278
except FileNotFoundError:
7379
pass
80+
81+
def _replace_with_retry(self, temp_file_path: str) -> None:
82+
for attempt in range(1, REPLACE_ATTEMPTS + 1):
83+
try:
84+
os.replace(temp_file_path, self.file_path)
85+
return
86+
except PermissionError:
87+
if attempt == REPLACE_ATTEMPTS:
88+
raise
89+
time.sleep(REPLACE_RETRY_DELAY * attempt)

‎backend/tests/test_json_repository.py‎

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import json
2-
import threading
2+
import os
3+
from concurrent.futures import ThreadPoolExecutor
34
import time
45
from unittest.mock import patch
56

@@ -64,11 +65,8 @@ def add_item(number):
6465
items.append(Item(id=str(number), name=f"item {number}"))
6566
repo._save_all(items)
6667

67-
threads = [threading.Thread(target=add_item, args=(n,)) for n in range(8)]
68-
for thread in threads:
69-
thread.start()
70-
for thread in threads:
71-
thread.join()
68+
with ThreadPoolExecutor(max_workers=8) as executor:
69+
list(executor.map(add_item, range(8))) # list() re-raises any error from a thread
7270

7371
assert len(JsonRepository(file_path, Item)._load_all()) == 8
7472

@@ -94,3 +92,37 @@ def test_save_that_fails_while_writing_json_leaves_no_temp_file(tmp_path, error)
9492

9593
assert repo._load_all() == [Item(id="1", name="original")]
9694
assert list(tmp_path.glob("*.tmp")) == []
95+
96+
97+
def test_save_retries_when_the_file_is_briefly_locked(tmp_path):
98+
# Windows refuses os.replace while another program has the file open for a moment
99+
repo = JsonRepository(tmp_path / "items.json", Item)
100+
real_replace = os.replace
101+
calls = []
102+
103+
def locked_twice(src, dst):
104+
calls.append(src)
105+
if len(calls) <= 2:
106+
raise PermissionError("file is in use")
107+
real_replace(src, dst)
108+
109+
with patch("backend.app.repositories.json_repository.os.replace", side_effect=locked_twice), \
110+
patch("backend.app.repositories.json_repository.time.sleep"):
111+
repo._save_all([Item(id="1", name="saved")])
112+
113+
assert len(calls) == 3
114+
assert repo._load_all() == [Item(id="1", name="saved")]
115+
116+
117+
def test_save_gives_up_after_too_many_attempts(tmp_path):
118+
repo = JsonRepository(tmp_path / "items.json", Item)
119+
repo._save_all([Item(id="1", name="original")])
120+
121+
with patch("backend.app.repositories.json_repository.os.replace", side_effect=PermissionError("file is in use")) as replace, \
122+
patch("backend.app.repositories.json_repository.time.sleep"):
123+
with pytest.raises(OSError, match="Failed to save"):
124+
repo._save_all([Item(id="2", name="new")])
125+
126+
assert replace.call_count == 5
127+
assert repo._load_all() == [Item(id="1", name="original")]
128+
assert list(tmp_path.glob("*.tmp")) == []

0 commit comments

Comments
 (0)