Skip to content

Commit 819fde3

Browse files
committed
feat: add transactionAsyncLocalStorage option to opt in to automatically setting session on all transactions
Fix #13889
1 parent 11c754c commit 819fde3

10 files changed

+121
-11
lines changed

docs/transactions.md

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
# Transactions in Mongoose
22

3-
[Transactions](https://www.mongodb.com/transactions) are new in MongoDB
4-
4.0 and Mongoose 5.2.0. Transactions let you execute multiple operations
5-
in isolation and potentially undo all the operations if one of them fails.
3+
[Transactions](https://www.mongodb.com/transactions) let you execute multiple operations in isolation and potentially undo all the operations if one of them fails.
64
This guide will get you started using transactions with Mongoose.
75

86
<h2 id="getting-started-with-transactions"><a href="#getting-started-with-transactions">Getting Started with Transactions</a></h2>
@@ -86,6 +84,33 @@ Below is an example of executing an aggregation within a transaction.
8684
[require:transactions.*aggregate]
8785
```
8886

87+
<h2 id="asynclocalstorage"><a href="#asynclocalstorage">Using AsyncLocalStorage</a></h2>
88+
89+
One major pain point with transactions in Mongoose is that you need to remember to set the `session` option on every operation.
90+
If you don't, your operation will execute outside of the transaction.
91+
Mongoose 8.4 is able to set the `session` operation on all operations within a `Connection.prototype.transaction()` executor function using Node's [AsyncLocalStorage API](https://nodejs.org/api/async_context.html#class-asynclocalstorage).
92+
Set the `transactionAsyncLocalStorage` option using `mongoose.set('transactionAsyncLocalStorage', true)` to enable this feature.
93+
94+
```javascript
95+
mongoose.set('transactionAsyncLocalStorage', true);
96+
97+
const Test = mongoose.model('Test', mongoose.Schema({ name: String }));
98+
99+
const doc = new Test({ name: 'test' });
100+
101+
// Save a new doc in a transaction that aborts
102+
await connection.transaction(async() => {
103+
await doc.save(); // Notice no session here
104+
throw new Error('Oops');
105+
});
106+
107+
// false, `save()` was rolled back
108+
await Test.exists({ _id: doc._id });
109+
```
110+
111+
With `transactionAsyncLocalStorage`, you no longer need to pass sessions to every operation.
112+
Mongoose will add the session by default under the hood.
113+
89114
<h2 id="advanced-usage"><a href="#advanced-usage">Advanced Usage</a></h2>
90115

91116
Advanced users who want more fine-grained control over when they commit or abort transactions

lib/aggregate.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1022,6 +1022,11 @@ Aggregate.prototype.exec = async function exec() {
10221022
applyGlobalMaxTimeMS(this.options, model.db.options, model.base.options);
10231023
applyGlobalDiskUse(this.options, model.db.options, model.base.options);
10241024

1025+
const asyncLocalStorage = this.model?.db?.base.transactionAsyncLocalStorage?.getStore();
1026+
if (!this.options.hasOwnProperty('session') && asyncLocalStorage?.session != null) {
1027+
this.options.session = asyncLocalStorage.session;
1028+
}
1029+
10251030
if (this.options && this.options.cursor) {
10261031
return new AggregationCursor(this);
10271032
}

lib/connection.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -539,7 +539,7 @@ Connection.prototype.startSession = async function startSession(options) {
539539
Connection.prototype.transaction = function transaction(fn, options) {
540540
return this.startSession().then(session => {
541541
session[sessionNewDocuments] = new Map();
542-
return session.withTransaction(() => _wrapUserTransaction(fn, session), options).
542+
return session.withTransaction(() => _wrapUserTransaction(fn, session, this.base), options).
543543
then(res => {
544544
delete session[sessionNewDocuments];
545545
return res;
@@ -558,9 +558,16 @@ Connection.prototype.transaction = function transaction(fn, options) {
558558
* Reset document state in between transaction retries re: gh-13698
559559
*/
560560

561-
async function _wrapUserTransaction(fn, session) {
561+
async function _wrapUserTransaction(fn, session, mongoose) {
562562
try {
563-
const res = await fn(session);
563+
const res = mongoose.transactionAsyncLocalStorage == null
564+
? await fn(session)
565+
: await new Promise(resolve => {
566+
mongoose.transactionAsyncLocalStorage.run(
567+
{ session },
568+
() => resolve(fn(session))
569+
);
570+
});
564571
return res;
565572
} catch (err) {
566573
_resetSessionDocuments(session);

lib/model.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,8 +296,11 @@ Model.prototype.$__handleSave = function(options, callback) {
296296
}
297297

298298
const session = this.$session();
299+
const asyncLocalStorage = this.db.base.transactionAsyncLocalStorage?.getStore();
299300
if (!saveOptions.hasOwnProperty('session') && session != null) {
300301
saveOptions.session = session;
302+
} else if (asyncLocalStorage?.session != null) {
303+
saveOptions.session = asyncLocalStorage.session;
301304
}
302305
if (this.$isNew) {
303306
// send entire doc
@@ -3533,6 +3536,10 @@ Model.bulkWrite = async function bulkWrite(ops, options) {
35333536
}
35343537

35353538
const validations = ops.map(op => castBulkWrite(this, op, options));
3539+
const asyncLocalStorage = this.db.base.transactionAsyncLocalStorage?.getStore();
3540+
if (!options.hasOwnProperty('session') && asyncLocalStorage.session != null) {
3541+
options = { ...options, session: asyncLocalStorage.session };
3542+
}
35363543

35373544
let res = null;
35383545
if (ordered) {

lib/mongoose.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ require('./helpers/printJestWarning');
3838

3939
const objectIdHexRegexp = /^[0-9A-Fa-f]{24}$/;
4040

41+
const { AsyncLocalStorage } = require('node:async_hooks');
42+
4143
/**
4244
* Mongoose constructor.
4345
*
@@ -101,6 +103,10 @@ function Mongoose(options) {
101103
}
102104
this.Schema.prototype.base = this;
103105

106+
if (options?.transactionAsyncLocalStorage) {
107+
this.transactionAsyncLocalStorage = new AsyncLocalStorage();
108+
}
109+
104110
Object.defineProperty(this, 'plugins', {
105111
configurable: false,
106112
enumerable: true,
@@ -267,15 +273,21 @@ Mongoose.prototype.set = function(key, value) {
267273

268274
if (optionKey === 'objectIdGetter') {
269275
if (optionValue) {
270-
Object.defineProperty(mongoose.Types.ObjectId.prototype, '_id', {
276+
Object.defineProperty(_mongoose.Types.ObjectId.prototype, '_id', {
271277
enumerable: false,
272278
configurable: true,
273279
get: function() {
274280
return this;
275281
}
276282
});
277283
} else {
278-
delete mongoose.Types.ObjectId.prototype._id;
284+
delete _mongoose.Types.ObjectId.prototype._id;
285+
}
286+
} else if (optionKey === 'transactionAsyncLocalStorage') {
287+
if (optionValue && !_mongoose.transactionAsyncLocalStorage) {
288+
_mongoose.transactionAsyncLocalStorage = new AsyncLocalStorage();
289+
} else if (!optionValue && _mongoose.transactionAsyncLocalStorage) {
290+
delete _mongoose.transactionAsyncLocalStorage;
279291
}
280292
}
281293
}

lib/query.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1947,6 +1947,11 @@ Query.prototype._optionsForExec = function(model) {
19471947
// Apply schema-level `writeConcern` option
19481948
applyWriteConcern(model.schema, options);
19491949

1950+
const asyncLocalStorage = this.model.db.base.transactionAsyncLocalStorage?.getStore();
1951+
if (!this.options.hasOwnProperty('session') && asyncLocalStorage?.session != null) {
1952+
options.session = asyncLocalStorage.session;
1953+
}
1954+
19501955
const readPreference = model &&
19511956
model.schema &&
19521957
model.schema.options &&

lib/validOptions.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ const VALID_OPTIONS = Object.freeze([
3232
'strictQuery',
3333
'toJSON',
3434
'toObject',
35+
'transactionAsyncLocalStorage',
3536
'translateAliases'
3637
]);
3738

test/docs/transactions.test.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,50 @@ describe('transactions', function() {
351351
await session.endSession();
352352
});
353353

354+
describe('transactionAsyncLocalStorage option', function() {
355+
let m;
356+
before(async function() {
357+
m = new mongoose.Mongoose();
358+
m.set('transactionAsyncLocalStorage', true);
359+
360+
await m.connect(start.uri);
361+
});
362+
363+
after(async function() {
364+
await m.disconnect();
365+
});
366+
367+
it('transaction() sets `session` by default if transactionAsyncLocalStorage option is set', async function() {
368+
const Test = m.model('Test', m.Schema({ name: String }));
369+
370+
await Test.createCollection();
371+
await Test.deleteMany({});
372+
373+
const doc = new Test({ name: 'test' });
374+
await assert.rejects(
375+
() => m.connection.transaction(async() => {
376+
await doc.save();
377+
378+
await Test.updateOne({ name: 'foo' }, { name: 'foo' }, { upsert: true });
379+
380+
let docs = await Test.aggregate([{ $match: { _id: doc._id } }]);
381+
assert.equal(docs.length, 1);
382+
383+
const docs = await Test.find({ _id: doc._id });
384+
assert.equal(docs.length, 1);
385+
386+
throw new Error('Oops!');
387+
}),
388+
/Oops!/
389+
);
390+
let exists = await Test.exists({ _id: doc._id });
391+
assert.ok(!exists);
392+
393+
exists = await Test.exists({ name: 'foo' });
394+
assert.ok(!exists);
395+
});
396+
});
397+
354398
it('transaction() resets $isNew on error', async function() {
355399
db.deleteModel(/Test/);
356400
const Test = db.model('Test', Schema({ name: String }));

test/model.findByIdAndUpdate.test.js

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,6 @@ describe('model: findByIdAndUpdate:', function() {
5353
'shape.side': 4,
5454
'shape.color': 'white'
5555
}, { new: true });
56-
console.log('doc');
57-
console.log(doc);
58-
console.log('doc');
5956

6057
assert.equal(doc.shape.kind, 'gh8378_Square');
6158
assert.equal(doc.shape.name, 'after');

types/mongooseoptions.d.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,13 @@ declare module 'mongoose' {
203203
*/
204204
toObject?: ToObjectOptions;
205205

206+
/**
207+
* Set to true to make Mongoose use Node.js' built-in AsyncLocalStorage (Node >= 16.0.0)
208+
* to set `session` option on all operations within a `connection.transaction(fn)` call
209+
* by default. Defaults to false.
210+
*/
211+
transactionAsyncLocalStorage?: boolean;
212+
206213
/**
207214
* If `true`, convert any aliases in filter, projection, update, and distinct
208215
* to their database property names. Defaults to false.

0 commit comments

Comments
 (0)