PeerTube/server/helpers/database-utils.ts

71 lines
2.1 KiB
TypeScript
Raw Normal View History

2017-06-10 22:15:25 +02:00
import * as Sequelize from 'sequelize'
2017-05-15 22:22:03 +02:00
// TODO: import from ES6 when retry typing file will include errorFilter function
2017-06-05 21:53:49 +02:00
import * as retry from 'async/retry'
2017-05-22 20:58:25 +02:00
import { database as db } from '../initializers/database'
2017-05-15 22:22:03 +02:00
import { logger } from './logger'
2017-01-17 20:38:45 +01:00
2017-06-10 22:15:25 +02:00
function commitTransaction (t: Sequelize.Transaction, callback: (err: Error) => void) {
2017-01-17 20:38:45 +01:00
return t.commit().asCallback(callback)
}
2017-06-10 22:15:25 +02:00
function rollbackTransaction (err: Error, t: Sequelize.Transaction, callback: (err: Error) => void) {
2017-01-17 20:38:45 +01:00
// Try to rollback transaction
if (t) {
// Do not catch err, report the original one
t.rollback().asCallback(function () {
return callback(err)
})
} else {
return callback(err)
}
}
2017-06-10 22:15:25 +02:00
type RetryTransactionWrapperOptions = { errorMessage: string, arguments?: any[] }
function retryTransactionWrapper (functionToRetry: Function, options: RetryTransactionWrapperOptions, finalCallback: Function) {
const args = options.arguments ? options.arguments : []
2017-05-15 22:22:03 +02:00
transactionRetryer(
function (callback) {
return functionToRetry.apply(this, args.concat([ callback ]))
},
function (err) {
if (err) {
logger.error(options.errorMessage, { error: err })
}
// Do not return the error, continue the process
return finalCallback(null)
}
)
}
2017-06-10 22:15:25 +02:00
function transactionRetryer (func: Function, callback: (err: Error) => void) {
retry({
times: 5,
errorFilter: function (err) {
const willRetry = (err.name === 'SequelizeDatabaseError')
logger.debug('Maybe retrying the transaction function.', { willRetry })
return willRetry
}
}, func, callback)
}
2017-06-10 22:15:25 +02:00
function startSerializableTransaction (callback: (err: Error, t: Sequelize.Transaction) => void) {
2017-05-22 20:58:25 +02:00
db.sequelize.transaction(/* { isolationLevel: 'SERIALIZABLE' } */).asCallback(function (err, t) {
// We force to return only two parameters
return callback(err, t)
})
}
// ---------------------------------------------------------------------------
2017-05-15 22:22:03 +02:00
export {
commitTransaction,
retryTransactionWrapper,
rollbackTransaction,
startSerializableTransaction,
transactionRetryer
}