]>
Commit | Line | Data |
---|---|---|
4df023f2 C |
1 | 'use strict' |
2 | ||
3 | const retry = require('async/retry') | |
4 | ||
5 | const db = require('../initializers/database') | |
6 | const logger = require('./logger') | |
7 | ||
8 | const utils = { | |
4145c1c6 | 9 | commitTransaction, |
4df023f2 | 10 | retryTransactionWrapper, |
4145c1c6 C |
11 | rollbackTransaction, |
12 | startSerializableTransaction, | |
13 | transactionRetryer | |
14 | } | |
15 | ||
16 | function commitTransaction (t, callback) { | |
17 | return t.commit().asCallback(callback) | |
18 | } | |
19 | ||
20 | function rollbackTransaction (err, t, callback) { | |
21 | // Try to rollback transaction | |
22 | if (t) { | |
23 | // Do not catch err, report the original one | |
24 | t.rollback().asCallback(function () { | |
25 | return callback(err) | |
26 | }) | |
27 | } else { | |
28 | return callback(err) | |
29 | } | |
4df023f2 C |
30 | } |
31 | ||
32 | // { arguments, errorMessage } | |
33 | function retryTransactionWrapper (functionToRetry, options, finalCallback) { | |
34 | const args = options.arguments ? options.arguments : [] | |
35 | ||
36 | utils.transactionRetryer( | |
37 | function (callback) { | |
38 | return functionToRetry.apply(this, args.concat([ callback ])) | |
39 | }, | |
40 | function (err) { | |
41 | if (err) { | |
42 | logger.error(options.errorMessage, { error: err }) | |
43 | } | |
44 | ||
45 | // Do not return the error, continue the process | |
46 | return finalCallback(null) | |
47 | } | |
48 | ) | |
49 | } | |
50 | ||
51 | function transactionRetryer (func, callback) { | |
52 | retry({ | |
53 | times: 5, | |
54 | ||
55 | errorFilter: function (err) { | |
56 | const willRetry = (err.name === 'SequelizeDatabaseError') | |
57 | logger.debug('Maybe retrying the transaction function.', { willRetry }) | |
58 | return willRetry | |
59 | } | |
60 | }, func, callback) | |
61 | } | |
62 | ||
63 | function startSerializableTransaction (callback) { | |
4df023f2 C |
64 | db.sequelize.transaction({ isolationLevel: 'SERIALIZABLE' }).asCallback(function (err, t) { |
65 | // We force to return only two parameters | |
66 | return callback(err, t) | |
67 | }) | |
68 | } | |
69 | ||
70 | // --------------------------------------------------------------------------- | |
71 | ||
72 | module.exports = utils |