Skip to content

Commit 9a870b5

Browse files
fix: atomic writes for userdata to prevent data loss on crash (Comfy-Org#12987)
Write to a temp file in the same directory then os.replace() onto the target path. If the process crashes mid-write, the original file is left intact instead of being truncated to zero bytes. Fixes Comfy-Org#11298
1 parent ca17fc8 commit 9a870b5

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

app/user_manager.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import glob
77
import shutil
88
import logging
9+
import tempfile
910
from aiohttp import web
1011
from urllib import parse
1112
from comfy.cli_args import args
@@ -377,8 +378,15 @@ async def post_userdata(request):
377378
try:
378379
body = await request.read()
379380

380-
with open(path, "wb") as f:
381-
f.write(body)
381+
dir_name = os.path.dirname(path)
382+
fd, tmp_path = tempfile.mkstemp(dir=dir_name)
383+
try:
384+
with os.fdopen(fd, "wb") as f:
385+
f.write(body)
386+
os.replace(tmp_path, path)
387+
except:
388+
os.unlink(tmp_path)
389+
raise
382390
except OSError as e:
383391
logging.warning(f"Error saving file '{path}': {e}")
384392
return web.Response(

0 commit comments

Comments
 (0)