-
Notifications
You must be signed in to change notification settings - Fork 1k
/
AsyncWriteProxyEx.cs
348 lines (311 loc) · 12.6 KB
/
AsyncWriteProxyEx.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
//-----------------------------------------------------------------------
// <copyright file="AsyncWriteProxyEx.cs" company="Akka.NET Project">
// Copyright (C) 2009-2022 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2022 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Actor.Internal;
using Akka.Persistence;
using Akka.Persistence.Journal;
namespace Akka.Cluster.Sharding.Tests
{
/// <summary>
/// This exception is thrown when the replay inactivity exceeds a specified timeout.
/// </summary>
[Serializable]
public class AsyncReplayTimeoutException : AkkaException
{
/// <summary>
/// Initializes a new instance of the <see cref="AsyncReplayTimeoutException"/> class.
/// </summary>
public AsyncReplayTimeoutException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncReplayTimeoutException"/> class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public AsyncReplayTimeoutException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncReplayTimeoutException"/> class.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
protected AsyncReplayTimeoutException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
/// <summary>
/// TBD
/// </summary>
[Serializable]
public sealed class SetStore
{
/// <summary>
/// TBD
/// </summary>
/// <param name="store">TBD</param>
/// <exception cref="ArgumentNullException">
/// This exception is thrown when the specified <paramref name="store"/> is undefined.
/// </exception>
public SetStore(IActorRef store)
{
if (store == null)
throw new ArgumentNullException(nameof(store), "SetStore requires non-null reference to store actor");
Store = store;
}
/// <summary>
/// TBD
/// </summary>
public readonly IActorRef Store;
}
/// <summary>
/// A journal that delegates actual storage to a target actor. For testing only.
/// </summary>
public abstract class AsyncWriteProxyEx : AsyncWriteJournal, IWithUnboundedStash
{
private class InitTimeout
{
public static readonly InitTimeout Instance = new InitTimeout();
private InitTimeout() { }
}
private bool _isInitialized;
private bool _isInitTimedOut;
private IActorRef _store;
/// <summary>
/// TBD
/// </summary>
protected AsyncWriteProxyEx()
{
_isInitialized = false;
_isInitTimedOut = false;
_store = null;
}
/// <summary>
/// TBD
/// </summary>
public abstract TimeSpan Timeout { get; }
/// <summary>
/// TBD
/// </summary>
public override void AroundPreStart()
{
Context.System.Scheduler.ScheduleTellOnce(Timeout, Self, InitTimeout.Instance, Self);
base.AroundPreStart();
}
/// <summary>
/// TBD
/// </summary>
/// <param name="receive">TBD</param>
/// <param name="message">TBD</param>
/// <returns>TBD</returns>
protected override bool AroundReceive(Receive receive, object message)
{
if (_isInitialized)
{
if (message is not InitTimeout)
return base.AroundReceive(receive, message);
}
else switch (message)
{
case SetStore msg:
_store = msg.Store;
Stash.UnstashAll();
_isInitialized = true;
break;
case InitTimeout:
_isInitTimedOut = true;
Stash.UnstashAll(); // will trigger appropriate failures
break;
default:
{
if (_isInitTimedOut)
{
return base.AroundReceive(receive, message);
}
else Stash.Stash();
break;
}
}
return true;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="messages">TBD</param>
/// <exception cref="TimeoutException">
/// This exception is thrown when the store has not been initialized.
/// </exception>
/// <returns>TBD</returns>
protected override Task<IImmutableList<Exception>> WriteMessagesAsync(IEnumerable<AtomicWrite> messages)
{
var trueMsgs = messages.ToArray();
if (_store == null)
return StoreNotInitialized<IImmutableList<Exception>>();
return _store.Ask<object>(sender => new WriteMessages(trueMsgs, sender, 1), Timeout, CancellationToken.None)
.ContinueWith(r =>
{
if (r.IsCanceled)
return (IImmutableList<Exception>)trueMsgs.Select(i => (Exception)new TimeoutException()).ToImmutableList();
if (r.IsFaulted)
return trueMsgs.Select(i => (Exception)r.Exception).ToImmutableList();
return r.Result switch
{
WriteMessageSuccess wms => trueMsgs.Select(i => (Exception)null).ToImmutableList(),
WriteMessageFailure wmf => trueMsgs.Select(i => wmf.Cause).ToImmutableList(),
_ => null
};
}, TaskContinuationOptions.ExecuteSynchronously);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="persistenceId">TBD</param>
/// <param name="toSequenceNr">TBD</param>
/// <exception cref="TimeoutException">
/// This exception is thrown when the store has not been initialized.
/// </exception>
/// <returns>TBD</returns>
protected override Task DeleteMessagesToAsync(string persistenceId, long toSequenceNr)
{
if (_store == null)
return StoreNotInitialized<object>();
var result = new TaskCompletionSource<object>();
_store.Ask<object>(sender => new DeleteMessagesTo(persistenceId, toSequenceNr, sender), Timeout, CancellationToken.None).ContinueWith(r =>
{
if (r.IsFaulted)
result.TrySetException(r.Exception);
else if (r.IsCanceled)
result.TrySetException(new TimeoutException());
else
result.TrySetResult(true);
}, TaskContinuationOptions.ExecuteSynchronously);
return result.Task;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="context">TBD</param>
/// <param name="persistenceId">TBD</param>
/// <param name="fromSequenceNr">TBD</param>
/// <param name="toSequenceNr">TBD</param>
/// <param name="max">TBD</param>
/// <param name="recoveryCallback">TBD</param>
/// <exception cref="TimeoutException">
/// This exception is thrown when the store has not been initialized.
/// </exception>
/// <returns>TBD</returns>
public override Task ReplayMessagesAsync(IActorContext context, string persistenceId, long fromSequenceNr, long toSequenceNr, long max, Action<IPersistentRepresentation> recoveryCallback)
{
if (_store == null)
return StoreNotInitialized<object>();
var replayCompletionPromise = new TaskCompletionSource<object>();
var mediator = context.ActorOf(Props.Create(() => new ReplayMediator(recoveryCallback, replayCompletionPromise, Timeout)).WithDeploy(Deploy.Local));
_store.Tell(new ReplayMessages(fromSequenceNr, toSequenceNr, max, persistenceId, mediator), mediator);
return replayCompletionPromise.Task;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="persistenceId">TBD</param>
/// <param name="fromSequenceNr">TBD</param>
/// <exception cref="TimeoutException">
/// This exception is thrown when the store has not been initialized.
/// </exception>
/// <returns>TBD</returns>
public override Task<long> ReadHighestSequenceNrAsync(string persistenceId, long fromSequenceNr)
{
if (_store == null)
return StoreNotInitialized<long>();
var result = new TaskCompletionSource<long>();
_store.Ask<object>(sender => new ReplayMessages(0, 0, 0, persistenceId, sender), Timeout, CancellationToken.None)
.ContinueWith(t =>
{
if (t.IsFaulted)
result.TrySetException(t.Exception);
else if (t.IsCanceled)
result.TrySetException(new TimeoutException());
else if (t.Result is RecoverySuccess rs)
result.TrySetResult(rs.HighestSequenceNr);
else
result.TrySetException(new InvalidOperationException());
}, TaskContinuationOptions.ExecuteSynchronously);
return result.Task;
}
private Task<T> StoreNotInitialized<T>()
{
var promise = new TaskCompletionSource<T>();
promise.SetException(new TimeoutException("Store not intialized."));
return promise.Task;
}
/// <summary>
/// TBD
/// </summary>
public IStash Stash { get; set; }
}
/// <summary>
/// TBD
/// </summary>
internal class ReplayMediator : ActorBase
{
private readonly Action<IPersistentRepresentation> _replayCallback;
private readonly TaskCompletionSource<object> _replayCompletionPromise;
private readonly TimeSpan _replayTimeout;
/// <summary>
/// TBD
/// </summary>
/// <param name="replayCallback">TBD</param>
/// <param name="replayCompletionPromise">TBD</param>
/// <param name="replayTimeout">TBD</param>
public ReplayMediator(Action<IPersistentRepresentation> replayCallback, TaskCompletionSource<object> replayCompletionPromise, TimeSpan replayTimeout)
{
_replayCallback = replayCallback;
_replayCompletionPromise = replayCompletionPromise;
_replayTimeout = replayTimeout;
Context.SetReceiveTimeout(replayTimeout);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="message">TBD</param>
/// <exception cref="AsyncReplayTimeoutException">
/// This exception is thrown when the replay timed out due to inactivity.
/// </exception>
/// <returns>TBD</returns>
protected override bool Receive(object message)
{
switch (message)
{
case ReplayedMessage rm:
_replayCallback(rm.Persistent);
return true;
case RecoverySuccess _:
_replayCompletionPromise.SetResult(new object());
Context.Stop(Self);
return true;
case ReplayMessagesFailure failure:
_replayCompletionPromise.SetException(failure.Cause);
Context.Stop(Self);
return true;
case ReceiveTimeout _:
var timeoutException = new AsyncReplayTimeoutException($"Replay timed out after {_replayTimeout.TotalSeconds}s of inactivity");
_replayCompletionPromise.SetException(timeoutException);
Context.Stop(Self);
return true;
}
return false;
}
}
}