mongo-dart / mongo_db_driver

Driver for connecting to MongoDb in Dart
BSD 3-Clause "New" or "Revised" License
2 stars 1 forks source link

How can i add retryWrites parameter in commitTransaction #4

Open Omar-IDOUDAOUD opened 2 months ago

Omar-IDOUDAOUD commented 2 months ago

void testTransaction() async {
  final client = MongoClient(url);
  await client.connect();
  final db = client.db(dbName: 'productsDatabase');
  final collection = db.collection('products');
  final session = client.startSession(
    clientSessionOptions: SessionOptions()..retryWrites = true, // not works
  );

  try {
    session.startTransaction(transactionOptions: TransactionOptions());
    final doc = await collection.findOne(
      filter: where..id(ObjectId.fromHexString('6695333eb09758b641618fbb')),
      session: session,
    );
    final currentViews = doc!['views'];

    print(
        'Wating 20 seconds'); // At this moment, I am changing the views value in MongoDB Compass, just for the first time to test transaction
    await Future.delayed(Duration(seconds: 20));

    await collection.updateOne(
      where..id(ObjectId.fromHexString('6695333eb09758b641618fbb')),
      UpdateExpression()..$set('views', currentViews + 1),
      session: session,
    );

    final transactionResult = await session.commitTransaction();
    print('Transaction finished: ');
    print(transactionResult);
  } catch (e) {
    session.abortTransaction();
    session.endSession();
    print('Transaction aborted, error: ');
    print(e);
  }
}

Output: (The transaction failed because I changed the value in mongodb compass):

Wating 20 seconds
Transaction finished: 
{errorLabels: [TransientTransactionError], ok: 0.0, errmsg: Transaction with { txnNumber: 1 } has been aborted., code: 251, codeName: NoSuchTransaction, $clusterTime: {clusterTime: Timestamp(1721056852, 18), signature: {hash: BsonBinary(cba714f505b169f45b207657231b620e5c577d99), keyId: 7340666272180338703}}, operationTime: Timestamp(1721056852, 18)}

Is there any way to automate a transaction retry until it succeeds, like Firebase Firestore transactions ?

giorgiofran commented 2 months ago

Hi, there is not the management of the retry writes in the driver at the moment. It is in my list, but, as I develop in my free time, it will take a while. The retryWrites option will be available only at client level, but will be defaulted to true.

This in an excerpt from the specs:

retryWrites

This boolean option determines whether retryable behavior will be applied to all supported write operations executed within the MongoClient. This option MUST default to true.

This option MUST NOT be configurable at the level of a database object, collection object, or at the level of an individual write operation.