Skip to content

Commit

Permalink
Improve robustness of timestamp.set_last()
Browse files Browse the repository at this point in the history
Previously, if the system crashed mid-write, it could result in the file being replaced by null-characters.

This fixes that by writing to a temporary file and properly flushing and syncing the memory before replacing the original file.
  • Loading branch information
Naxesss committed Sep 27, 2024
1 parent 5dcfa61 commit eca764c
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions aiess/timestamp.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from datetime import datetime
from contextlib import suppress
import os
import tempfile

from aiess.settings import ROOT_PATH

Expand Down Expand Up @@ -41,8 +42,12 @@ def set_last(new_datetime: datetime, _id: str=None) -> None:
if not os.path.exists(get_dir_path(_id)):
os.makedirs(get_dir_path(_id))

with open(get_path(_id), "w") as _file:
_file.write(to_string(new_datetime))
with tempfile.NamedTemporaryFile("w", dir=get_dir_path(_id), delete=False) as temp_file:
temp_file.write(to_string(new_datetime))
temp_file.flush()
os.fsync(temp_file.fileno())

os.replace(temp_file.name, get_path(_id))

def exists(_id: str=None) -> bool:
"""Returns whether a datetime file for this id exists."""
Expand Down

0 comments on commit eca764c

Please sign in to comment.