]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/controllers/api/videos.js
Server: remote request process refractoring
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos.js
index 6573b12103efa9c30870b8905e83b6a37434601e..75a661bccd77eeead99dde093b4efa36ac558984 100644 (file)
@@ -20,6 +20,7 @@ const validatorsSort = validators.sort
 const validatorsVideos = validators.videos
 const search = middlewares.search
 const sort = middlewares.sort
+const databaseUtils = require('../../helpers/database-utils')
 const utils = require('../../helpers/utils')
 
 const router = express.Router()
@@ -106,34 +107,27 @@ module.exports = router
 // Wrapper to video add that retry the function if there is a database error
 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
 function addVideoRetryWrapper (req, res, next) {
-  utils.transactionRetryer(
-    function (callback) {
-      return addVideo(req, res, req.files.videofile[0], callback)
-    },
-    function (err) {
-      if (err) {
-        logger.error('Cannot insert the video with many retries.', { error: err })
-        return next(err)
-      }
+  const options = {
+    arguments: [ req, res, req.files.videofile[0] ],
+    errorMessage: 'Cannot insert the video with many retries.'
+  }
 
-      // TODO : include Location of the new video -> 201
-      return res.type('json').status(204).end()
-    }
-  )
+  databaseUtils.retryTransactionWrapper(addVideo, options, function (err) {
+    if (err) return next(err)
+
+    // TODO : include Location of the new video -> 201
+    return res.type('json').status(204).end()
+  })
 }
 
-function addVideo (req, res, videoFile, callback) {
+function addVideo (req, res, videoFile, finalCallback) {
   const videoInfos = req.body
 
   waterfall([
 
-    function startTransaction (callbackWaterfall) {
-      db.sequelize.transaction({ isolationLevel: 'SERIALIZABLE' }).asCallback(function (err, t) {
-        return callbackWaterfall(err, t)
-      })
-    },
+    databaseUtils.startSerializableTransaction,
 
-    function findOrCreateAuthor (t, callbackWaterfall) {
+    function findOrCreateAuthor (t, callback) {
       const user = res.locals.oauth.token.User
 
       const name = user.username
@@ -142,19 +136,19 @@ function addVideo (req, res, videoFile, callback) {
       const userId = user.id
 
       db.Author.findOrCreateAuthor(name, podId, userId, t, function (err, authorInstance) {
-        return callbackWaterfall(err, t, authorInstance)
+        return callback(err, t, authorInstance)
       })
     },
 
-    function findOrCreateTags (t, author, callbackWaterfall) {
+    function findOrCreateTags (t, author, callback) {
       const tags = videoInfos.tags
 
       db.Tag.findOrCreateTags(tags, t, function (err, tagInstances) {
-        return callbackWaterfall(err, t, author, tagInstances)
+        return callback(err, t, author, tagInstances)
       })
     },
 
-    function createVideoObject (t, author, tagInstances, callbackWaterfall) {
+    function createVideoObject (t, author, tagInstances, callback) {
       const videoData = {
         name: videoInfos.name,
         remoteId: null,
@@ -166,107 +160,95 @@ function addVideo (req, res, videoFile, callback) {
 
       const video = db.Video.build(videoData)
 
-      return callbackWaterfall(null, t, author, tagInstances, video)
+      return callback(null, t, author, tagInstances, video)
     },
 
      // Set the videoname the same as the id
-    function renameVideoFile (t, author, tagInstances, video, callbackWaterfall) {
+    function renameVideoFile (t, author, tagInstances, video, callback) {
       const videoDir = constants.CONFIG.STORAGE.VIDEOS_DIR
       const source = path.join(videoDir, videoFile.filename)
       const destination = path.join(videoDir, video.getVideoFilename())
 
       fs.rename(source, destination, function (err) {
-        if (err) return callbackWaterfall(err)
+        if (err) return callback(err)
 
         // This is important in case if there is another attempt
         videoFile.filename = video.getVideoFilename()
-        return callbackWaterfall(null, t, author, tagInstances, video)
+        return callback(null, t, author, tagInstances, video)
       })
     },
 
-    function insertVideoIntoDB (t, author, tagInstances, video, callbackWaterfall) {
+    function insertVideoIntoDB (t, author, tagInstances, video, callback) {
       const options = { transaction: t }
 
       // Add tags association
       video.save(options).asCallback(function (err, videoCreated) {
-        if (err) return callbackWaterfall(err)
+        if (err) return callback(err)
 
         // Do not forget to add Author informations to the created video
         videoCreated.Author = author
 
-        return callbackWaterfall(err, t, tagInstances, videoCreated)
+        return callback(err, t, tagInstances, videoCreated)
       })
     },
 
-    function associateTagsToVideo (t, tagInstances, video, callbackWaterfall) {
+    function associateTagsToVideo (t, tagInstances, video, callback) {
       const options = { transaction: t }
 
       video.setTags(tagInstances, options).asCallback(function (err) {
         video.Tags = tagInstances
 
-        return callbackWaterfall(err, t, video)
+        return callback(err, t, video)
       })
     },
 
-    function sendToFriends (t, video, callbackWaterfall) {
+    function sendToFriends (t, video, callback) {
       video.toAddRemoteJSON(function (err, remoteVideo) {
-        if (err) return callbackWaterfall(err)
+        if (err) return callback(err)
 
         // Now we'll add the video's meta data to our friends
         friends.addVideoToFriends(remoteVideo, t, function (err) {
-          return callbackWaterfall(err, t)
+          return callback(err, t)
         })
       })
-    }
+    },
+
+    databaseUtils.commitTransaction
 
   ], function andFinally (err, t) {
     if (err) {
       // This is just a debug because we will retry the insert
       logger.debug('Cannot insert the video.', { error: err })
-
-      // Abort transaction?
-      if (t) t.rollback()
-
-      return callback(err)
+      return databaseUtils.rollbackTransaction(err, t, finalCallback)
     }
 
-    // Commit transaction
-    t.commit()
-
     logger.info('Video with name %s created.', videoInfos.name)
-
-    return callback(null)
+    return finalCallback(null)
   })
 }
 
 function updateVideoRetryWrapper (req, res, next) {
-  utils.transactionRetryer(
-    function (callback) {
-      return updateVideo(req, res, callback)
-    },
-    function (err) {
-      if (err) {
-        logger.error('Cannot update the video with many retries.', { error: err })
-        return next(err)
-      }
+  const options = {
+    arguments: [ req, res ],
+    errorMessage: 'Cannot update the video with many retries.'
+  }
 
-      // TODO : include Location of the new video -> 201
-      return res.type('json').status(204).end()
-    }
-  )
+  databaseUtils.retryTransactionWrapper(updateVideo, options, function (err) {
+    if (err) return next(err)
+
+    // TODO : include Location of the new video -> 201
+    return res.type('json').status(204).end()
+  })
 }
 
 function updateVideo (req, res, finalCallback) {
   const videoInstance = res.locals.video
+  const videoFieldsSave = videoInstance.toJSON()
   const videoInfosToUpdate = req.body
 
   waterfall([
 
-    function startTransaction (callback) {
-      db.sequelize.transaction().asCallback(function (err, t) {
-        return callback(err, t)
-      })
-    },
+    databaseUtils.startSerializableTransaction,
 
     function findOrCreateTags (t, callback) {
       if (videoInfosToUpdate.tags) {
@@ -279,12 +261,13 @@ function updateVideo (req, res, finalCallback) {
     },
 
     function updateVideoIntoDB (t, tagInstances, callback) {
-      const options = { transaction: t }
+      const options = {
+        transaction: t
+      }
 
       if (videoInfosToUpdate.name) videoInstance.set('name', videoInfosToUpdate.name)
       if (videoInfosToUpdate.description) videoInstance.set('description', videoInfosToUpdate.description)
 
-      // Add tags association
       videoInstance.save(options).asCallback(function (err) {
         return callback(err, t, tagInstances)
       })
@@ -311,21 +294,26 @@ function updateVideo (req, res, finalCallback) {
       friends.updateVideoToFriends(json, t, function (err) {
         return callback(err, t)
       })
-    }
+    },
+
+    databaseUtils.commitTransaction
 
   ], function andFinally (err, t) {
     if (err) {
       logger.debug('Cannot update the video.', { error: err })
 
-      // Abort transaction?
-      if (t) t.rollback()
+      // Force fields we want to update
+      // If the transaction is retried, sequelize will think the object has not changed
+      // So it will skip the SQL request, even if the last one was ROLLBACKed!
+      Object.keys(videoFieldsSave).forEach(function (key) {
+        const value = videoFieldsSave[key]
+        videoInstance.set(key, value)
+      })
 
-      return finalCallback(err)
+      return databaseUtils.rollbackTransaction(err, t, finalCallback)
     }
 
-    // Commit transaction
-    t.commit()
-
+    logger.info('Video with name %s updated.', videoInfosToUpdate.name)
     return finalCallback(null)
   })
 }
@@ -376,19 +364,16 @@ function listVideoAbuses (req, res, next) {
 }
 
 function reportVideoAbuseRetryWrapper (req, res, next) {
-  utils.transactionRetryer(
-    function (callback) {
-      return reportVideoAbuse(req, res, callback)
-    },
-    function (err) {
-      if (err) {
-        logger.error('Cannot report abuse to the video with many retries.', { error: err })
-        return next(err)
-      }
+  const options = {
+    arguments: [ req, res ],
+    errorMessage: 'Cannot report abuse to the video with many retries.'
+  }
 
-      return res.type('json').status(204).end()
-    }
-  )
+  databaseUtils.retryTransactionWrapper(reportVideoAbuse, options, function (err) {
+    if (err) return next(err)
+
+    return res.type('json').status(204).end()
+  })
 }
 
 function reportVideoAbuse (req, res, finalCallback) {
@@ -429,21 +414,17 @@ function reportVideoAbuse (req, res, finalCallback) {
       }
 
       return callback(null, t)
-    }
+    },
+
+    databaseUtils.commitTransaction
 
   ], function andFinally (err, t) {
     if (err) {
       logger.debug('Cannot update the video.', { error: err })
-
-      // Abort transaction?
-      if (t) t.rollback()
-
-      return finalCallback(err)
+      return databaseUtils.rollbackTransaction(err, t, finalCallback)
     }
 
-    // Commit transaction
-    t.commit()
-
+    logger.info('Abuse report for video %s created.', videoInstance.name)
     return finalCallback(null)
   })
 }