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
12 changes: 9 additions & 3 deletions matter_server/server/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
import asyncio
import logging
from pathlib import Path
import shutil
from typing import TYPE_CHECKING, Any, cast

from atomicwrites import atomic_write

from ..common.helpers.json import JSON_DECODE_EXCEPTIONS, json_dumps, json_loads

if TYPE_CHECKING:
Expand Down Expand Up @@ -152,11 +155,14 @@ async def async_save(self) -> None:

def do_save() -> None:
# make backup before we write a new file
if self.filename.is_file():
self.filename.replace(self.filename_backup)
self.filename_backup.unlink(True)
shutil.copy(self.filename, self.filename_backup)

with open(self.filename, "w", encoding="utf-8") as _file:
# use atomomic write to avoid corrupting the file
# if power is cut during write, we don't write a corrupted file
with atomic_write(self.filename, encoding="utf-8", overwrite=True) as _file:
_file.write(json_dumps(self._data))

LOGGER.debug("Saved data to persistent storage")

async with self._save_lock:
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ server = [
"aiohttp==3.11.10",
"aiorun==2024.8.1",
"async-timeout==5.0.1",
"atomicwrites==1.4.1",
"coloredlogs==15.0.1",
"cryptography==44.0.0",
"orjson==3.10.12",
Expand Down
Loading