GroupByUntil.cs 13 KB

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