Last active
July 1, 2020 00:36
-
-
Save coagmano/61cd143ca06adf4961da5fe6e14d3f39 to your computer and use it in GitHub Desktop.
Mongo Transaction Wrappers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function commitWithRetry(session) { | |
try { | |
await session.commitTransaction(); | |
} catch (error) { | |
if ( | |
error.errorLabels && | |
error.errorLabels.includes('UnknownTransactionCommitResult') | |
) { | |
log.error( | |
'UnknownTransactionCommitResult, retrying commit operation ...' | |
); | |
await commitWithRetry(session); | |
} else { | |
log.error('Error during commit ...'); | |
throw error; | |
} | |
} | |
} | |
async function runTransactionWithRetry(txnFunc, session) { | |
session.startTransaction(); | |
try { | |
await txnFunc(); | |
await commitWithRetry(session); | |
} catch (error) { | |
await session.abortTransaction(); | |
log.error('Transaction aborted. Caught exception during transaction.'); | |
// If transient error, retry the whole transaction | |
if ( | |
error.errorLabels && | |
error.errorLabels.includes('TransientTransactionError') | |
) { | |
log.error('TransientTransactionError, retrying transaction ...'); | |
await runTransactionWithRetry(txnFunc); | |
} else { | |
throw error; | |
} | |
} | |
} | |
export const wrapInTransaction = (client, txnFunc) => async db => { | |
const session = client.startSession(); | |
const innerFunc = () => txnFunc(db); | |
try { | |
await runTransactionWithRetry(innerFunc, session); | |
} finally { | |
await session.endSession(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment