Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Linq/Observable/GroupByUntil.cs

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