GroupByUntil.cs 15 KB

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