GroupByUntil.cs 14 KB

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