fix: atomic writes for userdata to prevent data loss on crash (#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 #11298
This commit is contained in:
Christian Byrne
2026-03-16 18:56:35 -07:00
committed by GitHub
parent ca17fc8355
commit 9a870b5102
+9 -1
View File
@@ -6,6 +6,7 @@ import uuid
import glob import glob
import shutil import shutil
import logging import logging
import tempfile
from aiohttp import web from aiohttp import web
from urllib import parse from urllib import parse
from comfy.cli_args import args from comfy.cli_args import args
@@ -377,8 +378,15 @@ class UserManager():
try: try:
body = await request.read() body = await request.read()
with open(path, "wb") as f: dir_name = os.path.dirname(path)
fd, tmp_path = tempfile.mkstemp(dir=dir_name)
try:
with os.fdopen(fd, "wb") as f:
f.write(body) f.write(body)
os.replace(tmp_path, path)
except:
os.unlink(tmp_path)
raise
except OSError as e: except OSError as e:
logging.warning(f"Error saving file '{path}': {e}") logging.warning(f"Error saving file '{path}': {e}")
return web.Response( return web.Response(