Skip to content

Instantly share code, notes, and snippets.

@coagmano
Last active July 1, 2020 00:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coagmano/61cd143ca06adf4961da5fe6e14d3f39 to your computer and use it in GitHub Desktop.
Save coagmano/61cd143ca06adf4961da5fe6e14d3f39 to your computer and use it in GitHub Desktop.
Mongo Transaction Wrappers
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