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.
This commit is contained in:
miruka 2020-07-24 01:01:37 -04:00
parent 872ee49a79
commit b94d1e8168

View File

@ -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: