Stopping two uploads from claiming the same filename
Checking whether a name exists is not enough when requests run at the same time. A short reservation closes the gap.
The obvious way to avoid overwriting a file is to check whether the name exists, and if so, try name-2. That works for one request at a time. With two, both can check, both can find the name free, and both can use it. The problem is the gap between checking and writing.
- Reserve the name
- Check real storage
- Write the file
- Release the reservation
Claim first, then check
The fix is to make claiming a name a single operation that only one caller can win. In the database that is one SQL statement:
INSERT INTO file_name_reservations (name, owner, expires) VALUES (?, ?, ?)
ON CONFLICT(name) DO UPDATE
SET owner = excluded.owner, expires = excluded.expires
WHERE file_name_reservations.expires <= ?
RETURNING owner
If the name is unclaimed, the row is inserted. If an old reservation has expired, it is taken over. If someone else holds a live one, nothing is returned. The caller compares the returned owner with its own random ID to learn whether it won.
Why reservations expire
An upload can be abandoned: a tab gets closed, or a laptop goes to sleep. Without an expiry, that name would stay locked forever. With one, it frees itself, and no cleanup job is needed for correctness.
Releasing safely
Releasing deletes the row only when both the name and the owner match. A slow request that wakes up after its reservation was taken over cannot delete the new holder's claim. The release also sits in a finally block, so an error while writing does not leave the name stuck.
One wrapper for every operation
Uploading is not the only way to create a name. Copying, renaming and restoring from Trash can too. Rather than repeating the logic, the storage object is wrapped so that all of these go through the same reservation step. Restoring a folder reserves its names in sorted order and releases them together.
Some operations pick the next free name automatically, such as an upload. Others, such as a rename, report a conflict, because silently choosing a different name would surprise the person who typed it.