From f09521c34438bd7f88e721fe143614270b158d86 Mon Sep 17 00:00:00 2001 From: Johanna England Date: Tue, 3 Sep 2024 13:57:17 +0200 Subject: [PATCH] Dump state to temp file before renaming to correct file --- changelog.d/364.fixed.md | 1 + src/zino/state.py | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 changelog.d/364.fixed.md diff --git a/changelog.d/364.fixed.md b/changelog.d/364.fixed.md new file mode 100644 index 00000000..052fd035 --- /dev/null +++ b/changelog.d/364.fixed.md @@ -0,0 +1 @@ +Avoid potential state corruption issues by saving the running state to a temporary file before overwriting the existing state file diff --git a/src/zino/state.py b/src/zino/state.py index 29cd4d8f..062201b8 100644 --- a/src/zino/state.py +++ b/src/zino/state.py @@ -4,6 +4,7 @@ import json import logging +import os from typing import Dict, Optional from pydantic import BaseModel, Field @@ -42,8 +43,10 @@ class ZinoState(BaseModel): def dump_state_to_file(self, filename: str): """Dumps the full state to a file in JSON format""" _log.debug("dumping state to %s", filename) - with open(filename, "w") as statefile: + temp_file = f"{filename}.tmp" + with open(temp_file, "w") as statefile: statefile.write(self.model_dump_json(exclude_none=True, indent=2)) + os.replace(src=temp_file, dst=filename) @classmethod @log_time_spent()