Repository navigation
fix: Await transaction snapshot reads to preserve linked cancellation tokens - #15963
robertvoinescu-work merged 2 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request refactors several snapshot retrieval methods in Transaction.cs to be asynchronous, ensuring that the linked CancellationTokenSource is not prematurely disposed before the underlying task completes. It also introduces comprehensive unit tests to validate in-flight cancellation propagation. The review feedback suggests optimizing these methods by avoiding CancellationTokenSource allocations when linking is unnecessary, and recommends disposing of the CancellationTokenRegistration in the test helper to prevent potential resource leaks.
| using var cts = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken, cancellationToken); | ||
| return await documentReference.GetSnapshotAsync(TransactionId, cts.Token).ConfigureAwait(false); |
There was a problem hiding this comment.
To avoid unnecessary allocations of CancellationTokenSource and registration overhead when neither or only one of the cancellation tokens is active, we can conditionally create the linked token source only when both tokens are cancelable.
bool link = CancellationToken.CanBeCanceled && cancellationToken.CanBeCanceled;
using var cts = link ? CancellationTokenSource.CreateLinkedTokenSource(CancellationToken, cancellationToken) : null;
var token = link ? cts.Token : (cancellationToken.CanBeCanceled ? cancellationToken : CancellationToken);
return await documentReference.GetSnapshotAsync(TransactionId, token).ConfigureAwait(false);There was a problem hiding this comment.
Good point I've done this with a helper method in a seperate perf commit.
| { | ||
| return documentReference.GetSnapshotAsync(TransactionId, cts.Token); | ||
| } | ||
| using var cts = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken, cancellationToken); |
There was a problem hiding this comment.
For consistency I removed the parentheses blocks for the using, but I can go the other way if you prefer.
2376cce to
1f04849
Compare
amanda-tarafa
left a comment
There was a problem hiding this comment.
Great fix, thanks!
Fixes premature disposal of linked cancellation tokens during in-flight reads as described in #15958.
b/570764830