2017-05-15 15:22:03 -05:00
|
|
|
// TODO: import from ES6 when retry typing file will include errorFilter function
|
2017-06-05 14:53:49 -05:00
|
|
|
import * as retry from 'async/retry'
|
2017-01-15 12:53:11 -06:00
|
|
|
|
2017-05-22 13:58:25 -05:00
|
|
|
import { database as db } from '../initializers/database'
|
2017-05-15 15:22:03 -05:00
|
|
|
import { logger } from './logger'
|
2017-01-17 13:38:45 -06:00
|
|
|
|
|
|
|
function commitTransaction (t, callback) {
|
|
|
|
return t.commit().asCallback(callback)
|
|
|
|
}
|
|
|
|
|
|
|
|
function rollbackTransaction (err, t, callback) {
|
|
|
|
// 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-01-15 12:53:11 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// { arguments, errorMessage }
|
|
|
|
function retryTransactionWrapper (functionToRetry, options, finalCallback) {
|
|
|
|
const args = options.arguments ? options.arguments : []
|
|
|
|
|
2017-05-15 15:22:03 -05:00
|
|
|
transactionRetryer(
|
2017-01-15 12:53:11 -06:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
function transactionRetryer (func, callback) {
|
|
|
|
retry({
|
|
|
|
times: 5,
|
|
|
|
|
|
|
|
errorFilter: function (err) {
|
|
|
|
const willRetry = (err.name === 'SequelizeDatabaseError')
|
|
|
|
logger.debug('Maybe retrying the transaction function.', { willRetry })
|
|
|
|
return willRetry
|
|
|
|
}
|
|
|
|
}, func, callback)
|
|
|
|
}
|
|
|
|
|
|
|
|
function startSerializableTransaction (callback) {
|
2017-05-22 13:58:25 -05:00
|
|
|
db.sequelize.transaction(/* { isolationLevel: 'SERIALIZABLE' } */).asCallback(function (err, t) {
|
2017-01-15 12:53:11 -06:00
|
|
|
// We force to return only two parameters
|
|
|
|
return callback(err, t)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
2017-05-15 15:22:03 -05:00
|
|
|
export {
|
|
|
|
commitTransaction,
|
|
|
|
retryTransactionWrapper,
|
|
|
|
rollbackTransaction,
|
|
|
|
startSerializableTransaction,
|
|
|
|
transactionRetryer
|
|
|
|
}
|