Skip to content

Commit

Permalink
Commit transactions from callback
Browse files Browse the repository at this point in the history
  • Loading branch information
stefanw committed Oct 4, 2023
1 parent 4bad082 commit b0b2f07
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/y_doc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,16 @@ impl YDocInner {
txn
}

pub fn commit_transaction(&mut self) {
if let Some(weak_txn) = &self.txn {
if let Some(txn) = weak_txn.upgrade() {
let mut txn = txn.borrow_mut();
txn.commit();
}
}
self.txn = None;
}

pub fn transact_mut<F, R>(&self, f: F) -> R
where
F: FnOnce(&mut YTransactionInner) -> R,
Expand Down Expand Up @@ -200,7 +210,9 @@ impl YDoc {
let args = PyTuple::new(py, vec![txn.into_py(py)]);
callback.call(py, args, None)
});
self.0.borrow_mut().txn = None;
// Make transaction commit after callback returns
let mut doc = self.0.borrow_mut();
doc.commit_transaction();
result
}

Expand Down
8 changes: 8 additions & 0 deletions tests/test_y_transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ def test_transaction_already_committed():
txn.commit()
assert str(excinfo.value) == "Transaction already committed!"

# Try smuggling transaction out of callback and reusing it
smuggle = {}
doc.transact(lambda txn: smuggle.update({"txn": txn}))
with pytest.raises(AssertionError) as excinfo:
text.extend(smuggle["txn"], "Bug")
assert str(excinfo.value) == "Transaction already committed!"
assert str(text) == "HelloBug"


def test_document_modification_during_transaction():
doc = Y.YDoc()
Expand Down

0 comments on commit b0b2f07

Please sign in to comment.