From deee6f84c7cbdbcc612eb6c9ef09a533893a265e Mon Sep 17 00:00:00 2001 From: Robert Swain Date: Thu, 18 May 2017 11:10:41 +0200 Subject: [PATCH] mediaapi/writers/upload: Move file first as db is source of truth The database is the source of truth. If we add the metadata to the database and it succeeds, and then the file fails to be moved, we think we have a file when we actually don't. --- .../dendrite/mediaapi/writers/upload.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/github.com/matrix-org/dendrite/mediaapi/writers/upload.go b/src/github.com/matrix-org/dendrite/mediaapi/writers/upload.go index fc0c3602a..37749ca10 100644 --- a/src/github.com/matrix-org/dendrite/mediaapi/writers/upload.go +++ b/src/github.com/matrix-org/dendrite/mediaapi/writers/upload.go @@ -209,9 +209,14 @@ func Upload(req *http.Request, cfg *config.MediaAPI, db *storage.Database) util. // TODO: generate thumbnails - err = db.StoreMediaMetadata(r.MediaMetadata) + finalPath := getPathFromMediaMetadata(r.MediaMetadata, cfg.BasePath) + + err = moveFile( + types.Path(path.Join(string(tmpDir), "content")), + types.Path(finalPath), + ) if err != nil { - logger.Warnf("Failed to store metadata: %q\n", err) + logger.Warnf("Failed to move file to final destination: %q\n", err) removeDir(tmpDir, logger) return util.JSONResponse{ Code: 400, @@ -219,13 +224,10 @@ func Upload(req *http.Request, cfg *config.MediaAPI, db *storage.Database) util. } } - err = moveFile( - types.Path(path.Join(string(tmpDir), "content")), - types.Path(getPathFromMediaMetadata(r.MediaMetadata, cfg.BasePath)), - ) + err = db.StoreMediaMetadata(r.MediaMetadata) if err != nil { - logger.Warnf("Failed to move file to final destination: %q\n", err) - removeDir(tmpDir, logger) + logger.Warnf("Failed to store metadata: %q\n", err) + removeDir(types.Path(path.Dir(finalPath)), logger) return util.JSONResponse{ Code: 400, JSON: jsonerror.Unknown(fmt.Sprintf("Failed to upload")),