From b94d1e8168d4d3c4141e271cdfbdeddfe6014aaf Mon Sep 17 00:00:00 2001 From: miruka Date: Fri, 24 Jul 2020 01:01:37 -0400 Subject: [PATCH] Fix possible race condition when writing user file While a user file write operation #1 was queued in the _write_loop, it was possible meanwhile for another function to read the file (the current old version on disk), add some data to it, add submit the write (operation #2). The modifications from operatio #1 were then completly lost at best. --- src/backend/user_files.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/backend/user_files.py b/src/backend/user_files.py index 96873328..458ce88a 100644 --- a/src/backend/user_files.py +++ b/src/backend/user_files.py @@ -65,7 +65,10 @@ class DataFile: async def read(self): - """Return content of the existing file on disk, or default content.""" + """Return future, existing or default content for the file on disk.""" + + if self._to_write is not None: + return self._to_write try: return self.path.read_text() @@ -125,7 +128,7 @@ class JSONDataFile(DataFile): async def read(self) -> JsonData: - """Return content of the existing file on disk, or default content. + """Return future, existing or default content for the file on disk. If the file has missing keys, the missing data will be merged and written to disk before returning. @@ -134,6 +137,9 @@ class JSONDataFile(DataFile): created. """ + if self._to_write is not None: + return json.loads(self._to_write) + try: data = json.loads(self.path.read_text()) except FileNotFoundError: