GroupByUntil.cs 14 KB

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