Repository navigation
Expand file tree
/
Copy pathNativeRequestWorkOwner.cs
More file actions
189 lines (160 loc) · 6.53 KB
/
Copy pathNativeRequestWorkOwner.cs
File metadata and controls
189 lines (160 loc) · 6.53 KB
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
using Microsoft.Extensions.Options;
namespace KeyLoad.Orleans;
/// <summary>Owns bounded active native request producers and verified capability frames for one silo.</summary>
public sealed class NativeRequestWorkOwner : IAsyncDisposable
{
private const int GetIsJoinedEmptyRead = 0;
private readonly Lock gate = new();
private readonly CancellationTokenSource shutdown = new();
private readonly CancellationToken shutdownToken;
private readonly Dictionary<(Guid RequestId, NativeRequestWorkKind Kind), NativeRequestWorkLease> active = [];
private TaskCompletionSource? zeroFrames;
private Task? drainTask;
private Task? disposeTask;
private int requestProducers;
private bool admissionClosed;
private int isJoined;
private readonly GrainRoutingOptions settings;
/// <summary>Creates an empty silo-local work registry.</summary>
/// <param name="options">The centrally validated request and capability admission limits.</param>
public NativeRequestWorkOwner(IOptions<GrainRoutingOptions> options)
{
ArgumentNullException.ThrowIfNull(options);
settings = options.Value;
shutdownToken = shutdown.Token;
}
/// <summary>Gets the owner cancellation token linked by admitted work.</summary>
internal CancellationToken ShutdownToken => shutdownToken;
/// <summary>Gets whether cancellation and every originally admitted frame have settled.</summary>
internal bool IsJoined => Volatile.Read(ref isJoined) != GetIsJoinedEmptyRead;
/// <summary>Admits one unique request frame while the owner is open.</summary>
/// <param name="requestId">The native request identity.</param>
/// <param name="kind">The closed frame class.</param>
/// <returns>The lease which releases this exact admission.</returns>
internal NativeRequestWorkLease Acquire(Guid requestId, NativeRequestWorkKind kind)
{
const int EmptyActiveCount = 0;
if (requestId == Guid.Empty || !Enum.IsDefined(kind))
{
throw Errors.Fail(ErrorCode.Validation, NativeRequestWorkLimits.InvalidIdentityMessage);
}
lock (gate)
{
if (admissionClosed)
{
throw Errors.Fail(ErrorCode.OwnershipLost, NativeRequestWorkLimits.AdmissionClosedMessage);
}
var key = (requestId, kind);
if (active.ContainsKey(key) || active.Count >= settings.MaximumTotalFrames
|| kind == NativeRequestWorkKind.RequestProducer
&& requestProducers >= settings.MaximumRequestProducers)
{
throw Errors.Fail(ErrorCode.ResourceExhausted, NativeRequestWorkLimits.CapacityMessage);
}
if (active.Count == EmptyActiveCount)
{
zeroFrames = new(TaskCreationOptions.RunContinuationsAsynchronously);
}
var lease = new NativeRequestWorkLease(this, requestId, kind);
active.Add(key, lease);
if (kind == NativeRequestWorkKind.RequestProducer)
{
requestProducers++;
}
return lease;
}
}
/// <summary>Closes admission, cancels work, and returns the shared original drain task.</summary>
/// <returns>The same task to every caller.</returns>
internal Task DrainAsync()
{
TaskCompletionSource start;
Task task;
lock (gate)
{
if (drainTask is not null)
{
return drainTask;
}
admissionClosed = true;
var frames = zeroFrames?.Task ?? Task.CompletedTask;
start = new(TaskCreationOptions.RunContinuationsAsynchronously);
task = CompleteDrainAsync(start.Task, frames);
drainTask = task;
}
start.TrySetResult();
return task;
}
/// <summary>Returns the one disposal task through the asynchronous-disposal contract.</summary>
public ValueTask DisposeAsync() => new(GetDisposeTask());
private Task GetDisposeTask()
{
TaskCompletionSource start;
Task task;
lock (gate)
{
if (disposeTask is not null)
{
return disposeTask;
}
start = new(TaskCreationOptions.RunContinuationsAsynchronously);
task = CompleteDisposeAsync(start.Task);
disposeTask = task;
}
start.TrySetResult();
return task;
}
private async Task CompleteDrainAsync(Task start, Task frames)
{
const int ValueSingleItemCount = 1;
await start.ConfigureAwait(false);
var cancelFailure = await NativeRequestWorkSettlement.CancelAsync(shutdown).ConfigureAwait(false);
var frameFailure = await NativeRequestWorkSettlement.JoinAsync(frames).ConfigureAwait(false);
Volatile.Write(ref isJoined, ValueSingleItemCount);
NativeRequestWorkSettlement.Rethrow(NativeRequestWorkSettlement.Preserve(cancelFailure, frameFailure));
}
private async Task CompleteDisposeAsync(Task start)
{
await start.ConfigureAwait(false);
var drainFailure = await NativeRequestWorkSettlement.JoinAsync(DrainAsync()).ConfigureAwait(false);
Exception? disposeFailure = null;
try
{
shutdown.Dispose();
}
catch (Exception error) when (NativeCqrsBoundaryErrors.IsNonFatal(error))
{
disposeFailure = error;
}
catch (Exception error) when (!NativeCqrsBoundaryErrors.IsNonFatal(error))
{
disposeFailure = error;
}
NativeRequestWorkSettlement.Rethrow(NativeRequestWorkSettlement.Preserve(drainFailure, disposeFailure));
}
internal void Release(NativeRequestWorkLease lease)
{
const int EmptyActiveCount = 0;
ArgumentNullException.ThrowIfNull(lease);
TaskCompletionSource? drained = null;
lock (gate)
{
var key = (lease.RequestId, lease.Kind);
if (!active.TryGetValue(key, out var registered) || !ReferenceEquals(registered, lease))
{
throw Errors.Fail(ErrorCode.Corruption, NativeRequestWorkLimits.LeaseIdentityMessage);
}
active.Remove(key);
if (lease.Kind == NativeRequestWorkKind.RequestProducer)
{
requestProducers--;
}
if (active.Count == EmptyActiveCount)
{
drained = zeroFrames;
zeroFrames = null;
}
}
drained?.TrySetResult();
}
}