CombineCommunity / CombineExt

CombineExt provides a collection of operators, publishers and utilities for Combine, that are not provided by Apple themselves, but are common in other Reactive Frameworks and standards.
https://combine.community
MIT License
1.72k stars 151 forks source link

Fix ReplaySubject race condition #138

Closed mruston-heb closed 2 years ago

mruston-heb commented 2 years ago

The ReplaySubject currently adds a new subscription before replaying the buffer. Since these two steps are not synchronized by the lock, it is possible that a new value is sent to the new subscription before the new subscription finishes replaying the buffer. This can result in a new subscription to a ReplaySubject receiving values out of order.

To fix this, it should be safe to have the new subscription replay the buffer before being added to the collection of subscriptions. The new subscription's DemandBuffer will have no requested demand at this point, so it will hold onto the replayed values until demand is requested. Once the lock is unlocked, any new values will be sent to all the subscriptions, which will always be added to the demand buffer after the replayed values.

I tried to keep the footprint of the new test minimal, but let me know if additional comments or helper methods could make it more clear.

codecov[bot] commented 2 years ago

Codecov Report

Merging #138 (3651dd5) into main (5818492) will increase coverage by 0.02%. The diff coverage is 100.00%.

@@            Coverage Diff             @@
##             main     #138      +/-   ##
==========================================
+ Coverage   95.53%   95.55%   +0.02%     
==========================================
  Files          68       68              
  Lines        3833     3851      +18     
==========================================
+ Hits         3662     3680      +18     
  Misses        171      171              
Impacted Files Coverage Δ
Sources/Subjects/ReplaySubject.swift 100.00% <100.00%> (ø)
Tests/ReplaySubjectTests.swift 99.64% <100.00%> (+0.03%) :arrow_up:

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update 5818492...3651dd5. Read the comment docs.