-
-
Notifications
You must be signed in to change notification settings - Fork 35
fix: Create media files atomically #1658
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
It’s unlikely, but very bad, for a partially-written media file to be served by nginx (which doesn’t consult the `media` table) with `Cache-Control: immutable`. It would be nice if we could use the standard library’s `tempfile.NamedTemporaryFile` for this, but its deletion options are too limited to be much cleaner, and it sets different file permissions.
…dia` table row Might as well? `os.open` applies `O_CLOEXEC` by default.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| with _os_closing(os.open(dir_path, os.O_RDONLY | os.O_DIRECTORY)) as dir_fd: | ||
| temp_name = f"tmp-{os.urandom(8).hex()}" | ||
| outfile = open(temp_name, "xb", opener=partial(os.open, dir_fd=dir_fd)) | ||
|
|
||
| try: | ||
| with outfile: | ||
| outfile.write(data) | ||
| outfile.flush() | ||
| os.fsync(outfile) | ||
| except: | ||
| os.unlink(temp_name, dir_fd=dir_fd) | ||
| raise | ||
|
|
||
| os.replace(temp_name, hash_filename, src_dir_fd=dir_fd, dst_dir_fd=dir_fd) | ||
|
|
||
| # Try to make sure the hash-named file is persisted before inserting it into the database | ||
| os.fsync(dir_fd) |
Copilot
AI
Jan 2, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The new atomic file creation logic (lines 53-69) lacks test coverage. Consider adding tests to verify: 1) temporary files are cleaned up on write failures, 2) the atomic rename succeeds, and 3) the fsync operations complete without errors. The existing tests in libweasyl/test/test_media.py only verify successful file creation paths.
and do a best-effort directory
fsyncafter the rename before inserting them into the database.It’s unlikely, but very bad, for a partially-written media file to be served by nginx (which doesn’t consult the
mediatable) withCache-Control: immutable.It would be nice if we could use the standard library’s
tempfile.NamedTemporaryFilefor this, but its deletion options are too limited to be much cleaner, and it sets different file permissions.