Skip to content

fix: handle potential DB conflict due to concurrent upload requests in postFile #19005

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
handle conflict in postFile
Signed-off-by: Callum Styan <callumstyan@gmail.com>
  • Loading branch information
cstyan committed Jul 22, 2025
commit a009ba710ed30448973ae4ce61564a00a248c0db
21 changes: 16 additions & 5 deletions coderd/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,22 @@ func (api *API) postFile(rw http.ResponseWriter, r *http.Request) {
Data: data,
})
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error saving file.",
Detail: err.Error(),
})
return
if database.IsUniqueViolation(err, database.UniqueFilesHashCreatedByKey) {
// The file was uploaded by some concurrent process since the last time we checked for it, fetch it again.
file, err = api.Database.GetFileByHashAndCreator(ctx, database.GetFileByHashAndCreatorParams{
Hash: hash,
CreatedBy: apiKey.UserID,
})
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even though we suspect that this won't happen often enough to be an issue, would it be worth adding a log here so that we can verify how often this happens later, or would that be needless clutter to the logs?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Absolutely, added one 👍

// At this point the first error was either not the UniqueViolation OR there's still an error even after we
// attempt to fetch the file again, so we should return here.
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error saving file.",
Detail: err.Error(),
})
return
}
}

httpapi.Write(ctx, rw, http.StatusCreated, codersdk.UploadResponse{
Expand Down