GroupByUntil.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Reactive.Disposables;
  8. using System.Reactive.Subjects;
  9. namespace System.Reactive.Linq.ObservableImpl
  10. {
  11. internal sealed class GroupByUntil<TSource, TKey, TElement, TDuration> : Producer<IGroupedObservable<TKey, TElement>, GroupByUntil<TSource, TKey, TElement, TDuration>._>
  12. {
  13. private readonly IObservable<TSource> _source;
  14. private readonly Func<TSource, TKey> _keySelector;
  15. private readonly Func<TSource, TElement> _elementSelector;
  16. private readonly Func<IGroupedObservable<TKey, TElement>, IObservable<TDuration>> _durationSelector;
  17. private readonly int? _capacity;
  18. private readonly IEqualityComparer<TKey> _comparer;
  19. public GroupByUntil(IObservable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<IGroupedObservable<TKey, TElement>, IObservable<TDuration>> durationSelector, int? capacity, IEqualityComparer<TKey> comparer)
  20. {
  21. _source = source;
  22. _keySelector = keySelector;
  23. _elementSelector = elementSelector;
  24. _durationSelector = durationSelector;
  25. _capacity = capacity;
  26. _comparer = comparer;
  27. }
  28. protected override _ CreateSink(IObserver<IGroupedObservable<TKey, TElement>> observer) => new _(this, observer);
  29. protected override void Run(_ sink) => sink.Run(_source);
  30. internal sealed class _ : Sink<TSource, IGroupedObservable<TKey, TElement>>
  31. {
  32. private readonly object _gate = new object();
  33. private readonly object _nullGate = new object();
  34. private readonly CompositeDisposable _groupDisposable = new CompositeDisposable();
  35. private readonly RefCountDisposable _refCountDisposable;
  36. private readonly Map<TKey, ISubject<TElement>> _map;
  37. private readonly Func<TSource, TKey> _keySelector;
  38. private readonly Func<TSource, TElement> _elementSelector;
  39. private readonly Func<IGroupedObservable<TKey, TElement>, IObservable<TDuration>> _durationSelector;
  40. private ISubject<TElement> _null;
  41. public _(GroupByUntil<TSource, TKey, TElement, TDuration> parent, IObserver<IGroupedObservable<TKey, TElement>> observer)
  42. : base(observer)
  43. {
  44. _refCountDisposable = new RefCountDisposable(_groupDisposable);
  45. _map = new Map<TKey, ISubject<TElement>>(parent._capacity, parent._comparer);
  46. _keySelector = parent._keySelector;
  47. _elementSelector = parent._elementSelector;
  48. _durationSelector = parent._durationSelector;
  49. }
  50. public override void Run(IObservable<TSource> source)
  51. {
  52. _groupDisposable.Add(source.SubscribeSafe(this));
  53. SetUpstream(_refCountDisposable);
  54. }
  55. private ISubject<TElement> NewSubject()
  56. {
  57. var sub = new Subject<TElement>();
  58. return Subject.Create<TElement>(new AsyncLockObserver<TElement>(sub, new Concurrency.AsyncLock()), sub);
  59. }
  60. public override void OnNext(TSource value)
  61. {
  62. var key = default(TKey);
  63. try
  64. {
  65. key = _keySelector(value);
  66. }
  67. catch (Exception exception)
  68. {
  69. Error(exception);
  70. return;
  71. }
  72. var fireNewMapEntry = false;
  73. var writer = default(ISubject<TElement>);
  74. try
  75. {
  76. //
  77. // Note: The box instruction in the IL will be erased by the JIT in case T is
  78. // a value type. In fact, the whole if block will go away and we'll end
  79. // up with nothing but the GetOrAdd call below.
  80. //
  81. // See GroupBy for more information and confirmation of this fact using
  82. // the SOS debugger extension.
  83. //
  84. if (key == null)
  85. {
  86. lock (_nullGate)
  87. {
  88. if (_null == null)
  89. {
  90. _null = NewSubject();
  91. fireNewMapEntry = true;
  92. }
  93. writer = _null;
  94. }
  95. }
  96. else
  97. {
  98. writer = _map.GetOrAdd(key, NewSubject, out fireNewMapEntry);
  99. }
  100. }
  101. catch (Exception exception)
  102. {
  103. Error(exception);
  104. return;
  105. }
  106. if (fireNewMapEntry)
  107. {
  108. var group = new GroupedObservable<TKey, TElement>(key, writer, _refCountDisposable);
  109. var duration = default(IObservable<TDuration>);
  110. var durationGroup = new GroupedObservable<TKey, TElement>(key, writer);
  111. try
  112. {
  113. duration = _durationSelector(durationGroup);
  114. }
  115. catch (Exception exception)
  116. {
  117. Error(exception);
  118. return;
  119. }
  120. lock (_gate)
  121. {
  122. ForwardOnNext(group);
  123. }
  124. var durationObserver = new DurationObserver(this, key, writer);
  125. _groupDisposable.Add(durationObserver);
  126. durationObserver.SetResource(duration.SubscribeSafe(durationObserver));
  127. }
  128. var element = default(TElement);
  129. try
  130. {
  131. element = _elementSelector(value);
  132. }
  133. catch (Exception exception)
  134. {
  135. Error(exception);
  136. return;
  137. }
  138. //
  139. // ISSUE: Rx v1.x shipped without proper handling of the case where the duration
  140. // sequence fires concurrently with the OnNext code path here. In such a
  141. // case, the subject can be completed before we get a chance to send out
  142. // a new element. However, a resurrected group for the same key won't get
  143. // to see the element either. To guard against this case, we'd have to
  144. // check whether the OnNext call below lost the race, and resurrect a new
  145. // group if needed. Unfortunately, this complicates matters when the
  146. // duration selector triggers synchronously (e.g. Return or Empty), which
  147. // causes the group to terminate immediately. We should not get stuck in
  148. // this case, repeatedly trying to resurrect a group that always ends
  149. // before we can send the element into it. Also, users may expect this
  150. // base case to mean no elements will ever be produced, so sending the
  151. // element into the group before starting the duration sequence may not
  152. // be a good idea either. For the time being, we'll leave this as-is and
  153. // revisit the behavior for vNext. Nonetheless, we'll add synchronization
  154. // to ensure no concurrent calls to the subject are made.
  155. //
  156. writer.OnNext(element);
  157. }
  158. private sealed class DurationObserver : SafeObserver<TDuration>
  159. {
  160. private readonly _ _parent;
  161. private readonly TKey _key;
  162. private readonly ISubject<TElement> _writer;
  163. public DurationObserver(_ parent, TKey key, ISubject<TElement> writer)
  164. {
  165. _parent = parent;
  166. _key = key;
  167. _writer = writer;
  168. }
  169. public override void OnNext(TDuration value)
  170. {
  171. OnCompleted();
  172. }
  173. public override void OnError(Exception error)
  174. {
  175. _parent.Error(error);
  176. Dispose();
  177. }
  178. public override void OnCompleted()
  179. {
  180. if (_key == null)
  181. {
  182. var @null = default(ISubject<TElement>);
  183. lock (_parent._nullGate)
  184. {
  185. @null = _parent._null;
  186. _parent._null = null;
  187. }
  188. @null.OnCompleted();
  189. }
  190. else
  191. {
  192. if (_parent._map.Remove(_key))
  193. {
  194. _writer.OnCompleted();
  195. }
  196. }
  197. _parent._groupDisposable.Remove(this);
  198. }
  199. }
  200. public override void OnError(Exception error)
  201. {
  202. Error(error);
  203. }
  204. public override void OnCompleted()
  205. {
  206. //
  207. // NOTE: A race with OnCompleted triggered by a duration selector is fine when
  208. // using Subject<T>. It will transition into a terminal state, making one
  209. // of the two calls a no-op by swapping in a DoneObserver<T>.
  210. //
  211. var @null = default(ISubject<TElement>);
  212. lock (_nullGate)
  213. {
  214. @null = _null;
  215. }
  216. @null?.OnCompleted();
  217. foreach (var w in _map.Values)
  218. {
  219. w.OnCompleted();
  220. }
  221. lock (_gate)
  222. {
  223. ForwardOnCompleted();
  224. }
  225. }
  226. private void Error(Exception exception)
  227. {
  228. //
  229. // NOTE: A race with OnCompleted triggered by a duration selector is fine when
  230. // using Subject<T>. It will transition into a terminal state, making one
  231. // of the two calls a no-op by swapping in a DoneObserver<T>.
  232. //
  233. var @null = default(ISubject<TElement>);
  234. lock (_nullGate)
  235. {
  236. @null = _null;
  237. }
  238. @null?.OnError(exception);
  239. foreach (var w in _map.Values)
  240. {
  241. w.OnError(exception);
  242. }
  243. lock (_gate)
  244. {
  245. ForwardOnError(exception);
  246. }
  247. }
  248. }
  249. }
  250. internal sealed class Map<TKey, TValue>
  251. {
  252. // Taken from ConcurrentDictionary in the BCL.
  253. // The default concurrency level is DEFAULT_CONCURRENCY_MULTIPLIER * #CPUs. The higher the
  254. // DEFAULT_CONCURRENCY_MULTIPLIER, the more concurrent writes can take place without interference
  255. // and blocking, but also the more expensive operations that require all locks become (e.g. table
  256. // resizing, ToArray, Count, etc). According to brief benchmarks that we ran, 4 seems like a good
  257. // compromise.
  258. private const int DefaultConcurrencyMultiplier = 4;
  259. private static int DefaultConcurrencyLevel => DefaultConcurrencyMultiplier * Environment.ProcessorCount;
  260. private readonly ConcurrentDictionary<TKey, TValue> _map;
  261. public Map(int? capacity, IEqualityComparer<TKey> comparer)
  262. {
  263. if (capacity.HasValue)
  264. {
  265. _map = new ConcurrentDictionary<TKey, TValue>(DefaultConcurrencyLevel, capacity.Value, comparer);
  266. }
  267. else
  268. {
  269. _map = new ConcurrentDictionary<TKey, TValue>(comparer);
  270. }
  271. }
  272. public TValue GetOrAdd(TKey key, Func<TValue> valueFactory, out bool added)
  273. {
  274. added = false;
  275. var value = default(TValue);
  276. var newValue = default(TValue);
  277. var hasNewValue = false;
  278. while (true)
  279. {
  280. if (_map.TryGetValue(key, out value))
  281. {
  282. break;
  283. }
  284. if (!hasNewValue)
  285. {
  286. newValue = valueFactory();
  287. hasNewValue = true;
  288. }
  289. if (_map.TryAdd(key, newValue))
  290. {
  291. added = true;
  292. value = newValue;
  293. break;
  294. }
  295. }
  296. return value;
  297. }
  298. public IEnumerable<TValue> Values => _map.Values.ToArray();
  299. public bool Remove(TKey key)
  300. {
  301. return _map.TryRemove(key, out _);
  302. }
  303. }
  304. }