/
AtomicComposition.cs
346 lines (304 loc) · 12.8 KB
/
AtomicComposition.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Hosting
{
/// <summary>
/// AtomicComposition provides lightweight atomicCompositional semantics to enable temporary
/// state to be managed for a series of nested atomicCompositions. Each atomicComposition maintains
/// queryable state along with a sequence of actions necessary to complete the state when
/// the atomicComposition is no longer in danger of being rolled back. State is completed or
/// rolled back when the atomicComposition is disposed, depending on the state of the
/// CompleteOnDispose property which defaults to false. The using(...) pattern in C# is a
/// convenient mechanism for defining atomicComposition scopes.
///
/// The least obvious aspects of AtomicComposition deal with nesting.
///
/// Firstly, no complete actions are actually performed until the outermost atomicComposition is
/// completed. Completeting or rolling back nested atomicCompositions serves only to change which
/// actions would be completed the outer atomicComposition.
///
/// Secondly, state is added in the form of queries associated with an object key. The
/// key represents a unique object the state is being held on behalf of. The quieries are
/// accessed through the Query methods which provide automatic chaining to execute queries
/// across the target atomicComposition and its inner atomicComposition as appropriate.
///
/// Lastly, when a nested atomicComposition is created for a given outer the outer atomicComposition is locked.
/// It remains locked until the inner atomicComposition is disposed or completeed preventing the addition of
/// state, actions or other inner atomicCompositions.
/// </summary>
public class AtomicComposition : IDisposable
{
private readonly AtomicComposition? _outerAtomicComposition;
private KeyValuePair<object, object?>[]? _values;
private int _valueCount;
private List<Action>? _completeActionList;
private List<Action>? _revertActionList;
private bool _isDisposed;
private bool _isCompleted;
private bool _containsInnerAtomicComposition;
public AtomicComposition()
: this(null)
{
}
public AtomicComposition(AtomicComposition? outerAtomicComposition)
{
// Lock the inner atomicComposition so that we can assume nothing changes except on
// the innermost scope, and thereby optimize the query path
if (outerAtomicComposition != null)
{
_outerAtomicComposition = outerAtomicComposition;
_outerAtomicComposition.ContainsInnerAtomicComposition = true;
}
}
public void SetValue(object key, object? value)
{
ThrowIfDisposed();
ThrowIfCompleted();
ThrowIfContainsInnerAtomicComposition();
Requires.NotNull(key, nameof(key));
SetValueInternal(key, value);
}
public bool TryGetValue<T>(object key, [MaybeNullWhen(false)] out T value)
{
return TryGetValue(key, false, out value);
}
public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, [MaybeNullWhen(false)] out T value)
{
ThrowIfDisposed();
ThrowIfCompleted();
Requires.NotNull(key, nameof(key));
return TryGetValueInternal(key, localAtomicCompositionOnly, out value);
}
public void AddCompleteAction(Action completeAction)
{
ThrowIfDisposed();
ThrowIfCompleted();
ThrowIfContainsInnerAtomicComposition();
Requires.NotNull(completeAction, nameof(completeAction));
_completeActionList ??= new List<Action>();
_completeActionList.Add(completeAction);
}
public void AddRevertAction(Action revertAction)
{
ThrowIfDisposed();
ThrowIfCompleted();
ThrowIfContainsInnerAtomicComposition();
Requires.NotNull(revertAction, nameof(revertAction));
_revertActionList ??= new List<Action>();
_revertActionList.Add(revertAction);
}
public void Complete()
{
ThrowIfDisposed();
ThrowIfCompleted();
if (_outerAtomicComposition == null)
{ // Execute all the complete actions
FinalComplete();
}
else
{ // Copy the actions and state to the outer atomicComposition
CopyComplete();
}
_isCompleted = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
ThrowIfDisposed();
_isDisposed = true;
if (_outerAtomicComposition != null)
{
_outerAtomicComposition.ContainsInnerAtomicComposition = false;
}
// Revert is always immediate and involves forgetting information and
// exceuting any appropriate revert actions
if (!_isCompleted)
{
if (_revertActionList != null)
{
List<Exception>? exceptions = null;
// Execute the revert actions in reverse order to ensure
// everything incrementally rollsback its state.
for (int i = _revertActionList.Count - 1; i >= 0; i--)
{
Action action = _revertActionList[i];
try
{
action();
}
catch (CompositionException)
{
// This can only happen after preview is completed, so ... abandon remainder of events is correct
throw;
}
catch (Exception e)
{
//If any exceptions leak through the actions we will swallow them for now
// complete processing the list
// and we will throw InvalidOperationException with an AggregateException as it's innerException
exceptions ??= new List<Exception>();
exceptions.Add(e);
}
}
_revertActionList = null;
if (exceptions != null)
{
throw new InvalidOperationException(SR.InvalidOperation_RevertAndCompleteActionsMustNotThrow, new AggregateException(exceptions));
}
}
}
}
private void FinalComplete()
{
// Completeting the outer most scope is easy, just execute all the actions
if (_completeActionList != null)
{
List<Exception>? exceptions = null;
foreach (Action action in _completeActionList)
{
try
{
action();
}
catch (CompositionException)
{
// This can only happen after preview is completed, so ... abandon remainder of events is correct
throw;
}
catch (Exception e)
{
//If any exceptions leak through the actions we will swallow them for now complete processing the list
// and we will throw InvalidOperationException with an AggregateException as it's innerException
exceptions ??= new List<Exception>();
exceptions.Add(e);
}
}
_completeActionList = null;
if (exceptions != null)
{
throw new InvalidOperationException(SR.InvalidOperation_RevertAndCompleteActionsMustNotThrow, new AggregateException(exceptions));
}
}
}
private void CopyComplete()
{
if (_outerAtomicComposition == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
_outerAtomicComposition.ContainsInnerAtomicComposition = false;
// Inner scopes are much odder, because completeting them means coalescing them into the
// outer scope - the complete or revert actions are deferred until the outermost scope completes
// or any intermediate rolls back
if (_completeActionList != null)
{
foreach (Action action in _completeActionList)
{
_outerAtomicComposition.AddCompleteAction(action);
}
}
if (_revertActionList != null)
{
foreach (Action action in _revertActionList)
{
_outerAtomicComposition.AddRevertAction(action);
}
}
// We can copy over existing atomicComposition entries because they're either already chained or
// overwrite by design and can now be completed or rolled back together
for (var index = 0; index < _valueCount; index++)
{
_outerAtomicComposition.SetValueInternal(
_values![index].Key, _values[index].Value);
}
}
private bool ContainsInnerAtomicComposition
{
set
{
if (value && _containsInnerAtomicComposition)
{
throw new InvalidOperationException(SR.AtomicComposition_AlreadyNested);
}
_containsInnerAtomicComposition = value;
}
}
private bool TryGetValueInternal<T>(object key, bool localAtomicCompositionOnly, [MaybeNullWhen(false)] out T value)
{
for (var index = 0; index < _valueCount; index++)
{
if (_values![index].Key == key)
{
value = (T)_values[index].Value!;
return true;
}
}
// If there's no atomicComposition available then recurse until we hit the outermost
// scope, where upon we go ahead and return null
if (!localAtomicCompositionOnly && _outerAtomicComposition != null)
{
return _outerAtomicComposition.TryGetValueInternal<T>(key, localAtomicCompositionOnly, out value);
}
value = default;
return false;
}
private void SetValueInternal(object key, object? value)
{
// Handle overwrites quickly
for (var index = 0; index < _valueCount; index++)
{
if (_values![index].Key == key)
{
_values[index] = new KeyValuePair<object, object?>(key, value);
return;
}
}
// Expand storage when needed
if (_values == null || _valueCount == _values.Length)
{
var newQueries = new KeyValuePair<object, object?>[_valueCount == 0 ? 5 : _valueCount * 2];
if (_values != null)
{
Array.Copy(_values, newQueries, _valueCount);
}
_values = newQueries;
}
// Store a new entry
_values[_valueCount] = new KeyValuePair<object, object?>(key, value);
_valueCount++;
return;
}
[DebuggerStepThrough]
private void ThrowIfContainsInnerAtomicComposition()
{
if (_containsInnerAtomicComposition)
{
throw new InvalidOperationException(SR.AtomicComposition_PartOfAnotherAtomicComposition);
}
}
[DebuggerStepThrough]
private void ThrowIfCompleted()
{
if (_isCompleted)
{
throw new InvalidOperationException(SR.AtomicComposition_AlreadyCompleted);
}
}
[DebuggerStepThrough]
private void ThrowIfDisposed()
{
if (_isDisposed)
{
throw ExceptionBuilder.CreateObjectDisposed(this);
}
}
}
}