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