-
Notifications
You must be signed in to change notification settings - Fork 11
/
PersistenceSupervisor.cs
332 lines (301 loc) · 13.8 KB
/
PersistenceSupervisor.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
// -----------------------------------------------------------------------
// <copyright file="PersistenceSupervisor.cs" company="Petabridge, LLC">
// Copyright (C) 2015 - 2019 Petabridge, LLC <https://petabridge.com>
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using Akka.Event;
using Akka.Pattern;
using Akka.Util;
namespace Akka.Persistence.Extras
{
/// <inheritdoc />
/// <summary>
/// <see cref="T:Akka.Pattern.BackoffSupervisor" /> implementation that buffers un-delivered and un-persisted
/// messages down to a <see cref="T:Akka.Persistence.PersistentActor" /> child.
/// </summary>
public class PersistenceSupervisor : ActorBase
{
private readonly Queue<Envelope> _allMsgBuffer = new Queue<Envelope>();
private readonly IPersistenceSupervisionConfig _config;
private readonly Dictionary<long, PersistentEvent> _eventBuffer = new Dictionary<long, PersistentEvent>();
private readonly SupervisorStrategy _strategy;
protected readonly ILoggingAdapter Log = Context.GetLogger();
private long _currentDeliveryId;
public PersistenceSupervisor(Props childProps, string childName,
IPersistenceSupervisionConfig config, SupervisorStrategy strategy = null)
: this(i => childProps, childName, config, strategy) { }
public PersistenceSupervisor(Func<IActorRef, Props> childProps, string childName,
IPersistenceSupervisionConfig config, SupervisorStrategy strategy = null)
{
ChildProps = childProps;
ChildName = childName;
_config = config;
_strategy = strategy ?? Actor.SupervisorStrategy.StoppingStrategy;
// use built-in defaults if unavailable
IsEvent = _config.IsEvent ?? PersistenceSupervisionConfig.DefaultIsEvent;
MakeEventConfirmable = _config.MakeEventConfirmable ??
PersistenceSupervisionConfig.DefaultMakeEventConfirmable(childName);
}
protected Func<IActorRef, Props> ChildProps { get; }
protected string ChildName { get; }
protected IBackoffReset Reset => _config.Reset;
protected IActorRef Child { get; set; }
protected int RestartCountN { get; set; }
protected bool FinalStopMessageReceived { get; set; }
protected Func<object, bool> FinalStopMessage => _config.FinalStopMessage;
protected Func<object, bool> IsEvent { get; }
protected Func<object, long, IConfirmableMessage> MakeEventConfirmable { get; }
protected override SupervisorStrategy SupervisorStrategy()
{
return _strategy;
}
protected override void PreStart()
{
StartChild();
}
private void StartChild()
{
if (Child == null)
Child = Context.Watch(Context.ActorOf(ChildProps(Context.Self), ChildName));
}
protected virtual void OnChildRecreate()
{
/*
* Drain all internal buffers and try to get the child actor back
* into the state it would have been if there were no issues with recovery
* or writing to the Akka.Persistence journal.
*/
foreach (var e in _eventBuffer.OrderBy(x => x.Key))
Child.Tell(e.Value.Msg, e.Value.Sender);
// Drain the normal operational buffer
foreach (var m in _allMsgBuffer)
HandleMsg(m.Message, m.Sender);
_allMsgBuffer.Clear();
}
protected override bool Receive(object message)
{
return OnTerminated(message) || HandleBackoff(message);
}
protected virtual bool CheckIsEvent(object message)
{
return IsEvent(message);
}
protected virtual IConfirmableMessage DoMakeEventConfirmable(object message, long deliveryId)
{
return MakeEventConfirmable(message, deliveryId);
}
protected void HandleMsg(object message, IActorRef sender = null)
{
sender = sender ?? Sender;
if (CheckIsEvent(message))
{
var confirmable = DoMakeEventConfirmable(message, ++_currentDeliveryId);
_eventBuffer[confirmable.ConfirmationId] = new PersistentEvent(confirmable, Sender);
Child.Tell(confirmable, sender);
}
else if (message is Confirmation confirmation)
{
if (Log.IsDebugEnabled)
Log.Debug("Confirming delivery of event [{0}] from [{1}]", confirmation.ConfirmationId,
confirmation.SenderId);
if (!_eventBuffer.Remove(confirmation.ConfirmationId))
Log.Warning("Received confirmation for unknown event [{0}] from persistent entity [{1}]",
confirmation.ConfirmationId, confirmation.SenderId);
}
else if (sender.Equals(Child))
{
// use the BackoffSupervisor as sender
Context.Parent.Tell(message);
}
else
{
Child.Tell(message, sender);
if (!FinalStopMessageReceived && FinalStopMessage != null)
FinalStopMessageReceived = FinalStopMessage(message);
}
}
protected bool HandleBackoff(object message)
{
switch (message)
{
case BackoffSupervisor.StartChild _:
{
StartChild();
OnChildRecreate(); // replay all messages
if (Reset is AutoReset auto)
Context.System.Scheduler.ScheduleTellOnce(auto.ResetBackoff, Self,
new BackoffSupervisor.ResetRestartCount(RestartCountN), Self);
break;
}
case BackoffSupervisor.ResetRestartCount count:
{
if (count.Current == RestartCountN)
RestartCountN = 0;
break;
}
case BackoffSupervisor.GetRestartCount _:
Sender.Tell(new BackoffSupervisor.RestartCount(RestartCountN));
break;
case BackoffSupervisor.GetCurrentChild _:
Sender.Tell(new BackoffSupervisor.CurrentChild(Child));
break;
default:
{
if (Child != null)
{
HandleMsg(message);
}
else
{
if (FinalStopMessage != null && FinalStopMessage(message))
{
Context.System.DeadLetters.Forward(message);
Context.Stop(Self);
}
else
{
// buffer the messages while we recreate the actor
_allMsgBuffer.Enqueue(new Envelope(message, Sender));
}
}
break;
}
}
return true;
}
private bool OnTerminated(object message)
{
if (message is Terminated terminated && terminated.ActorRef.Equals(Child))
{
Child = null;
if (FinalStopMessageReceived)
{
Context.Stop(Self);
}
else
{
var maxNrOfRetries = _strategy is OneForOneStrategy oneForOne ? oneForOne.MaxNumberOfRetries : -1;
var nextRestartCount = RestartCountN + 1;
if (maxNrOfRetries == -1 || nextRestartCount <= maxNrOfRetries)
{
var restartDelay = CalculateDelay(RestartCountN, _config.MinBackoff, _config.MaxBackoff,
_config.RandomFactor);
Context.System.Scheduler.ScheduleTellOnce(restartDelay, Self,
BackoffSupervisor.StartChild.Instance, Self);
RestartCountN = nextRestartCount;
}
else
{
Log.Debug(
$"Terminating on restart #{nextRestartCount} which exceeds max allowed restarts ({maxNrOfRetries})");
Context.Stop(Self);
}
}
return true;
}
return false;
}
/// <summary>
/// Calculates an exponential back off delay.
/// </summary>
internal static TimeSpan CalculateDelay(
int restartCount,
TimeSpan minBackoff,
TimeSpan maxBackoff,
double randomFactor)
{
var rand = 1.0 + ThreadLocalRandom.Current.NextDouble() * randomFactor;
var calculateDuration = Math.Min(maxBackoff.Ticks, minBackoff.Ticks * Math.Pow(2, restartCount)) * rand;
return calculateDuration < 0d || calculateDuration >= long.MaxValue
? maxBackoff
: new TimeSpan((long) calculateDuration);
}
public static Props PropsFor(Func<object, long, IConfirmableMessage> makeConfirmable,
Func<object, bool> isEvent,
Func<IActorRef, Props> childPropsFactory, string childName, IBackoffReset reset = null, Func<object, bool> finalStopMsg = null,
SupervisorStrategy strategy = null)
{
var config =
new PersistenceSupervisionConfig(isEvent, makeConfirmable, reset, finalStopMessage: finalStopMsg);
return Props.Create(() => new PersistenceSupervisor(childPropsFactory, childName, config,
strategy ?? Actor.SupervisorStrategy.StoppingStrategy));
}
public static Props PropsFor(Func<object, long, IConfirmableMessage> makeConfirmable,
Func<object, bool> isEvent,
Props childProps, string childName, IBackoffReset reset = null, Func<object, bool> finalStopMsg = null,
SupervisorStrategy strategy = null)
{
var config =
new PersistenceSupervisionConfig(isEvent, makeConfirmable, reset, finalStopMessage: finalStopMsg);
return Props.Create(() => new PersistenceSupervisor(childProps, childName, config,
strategy ?? Actor.SupervisorStrategy.StoppingStrategy));
}
/// <summary>
/// Overload for users who ARE ALREADY USING <see cref="IConfirmableMessage"/> by the time the message
/// is received by the <see cref="PersistenceSupervisor"/>.
///
/// If a message is received by the <see cref="PersistenceSupervisor"/> without being decorated by <see cref="IConfirmableMessage"/>,
/// under this configuration we will automatically package your message inside a <see cref="ConfirmableMessageEnvelope"/>.
/// </summary>
/// <param name="childProps"></param>
/// <param name="childName"></param>
/// <param name="reset"></param>
/// <param name="finalStopMsg"></param>
/// <param name="strategy"></param>
/// <remarks>
/// Read the manual. Seriously.
/// </remarks>
/// <returns></returns>
public static Props PropsFor(Props childProps, string childName, IBackoffReset reset = null,
Func<object, bool> finalStopMsg = null,
SupervisorStrategy strategy = null)
{
var config =
new PersistenceSupervisionConfig(null, null, reset, finalStopMessage: finalStopMsg);
return Props.Create(() => new PersistenceSupervisor(childProps, childName, config,
strategy ?? Actor.SupervisorStrategy.StoppingStrategy));
}
/// <summary>
/// Overload for users who ARE ALREADY USING <see cref="IConfirmableMessage"/> by the time the message
/// is received by the <see cref="PersistenceSupervisor"/>.
///
/// If a message is received by the <see cref="PersistenceSupervisor"/> without being decorated by <see cref="IConfirmableMessage"/>,
/// under this configuration we will automatically package your message inside a <see cref="ConfirmableMessageEnvelope"/>.
/// </summary>
/// <param name="childPropsFactory"></param>
/// <param name="childName"></param>
/// <param name="reset"></param>
/// <param name="finalStopMsg"></param>
/// <param name="strategy"></param>
/// <remarks>
/// Read the manual. Seriously.
/// </remarks>
/// <returns></returns>
public static Props PropsFor(Func<IActorRef, Props> childPropsFactory, string childName, IBackoffReset reset = null,
Func<object, bool> finalStopMsg = null,
SupervisorStrategy strategy = null)
{
var config =
new PersistenceSupervisionConfig(null, null, reset, finalStopMessage: finalStopMsg);
return Props.Create(() => new PersistenceSupervisor(childPropsFactory, childName, config,
strategy ?? Actor.SupervisorStrategy.StoppingStrategy));
}
/// <summary>
/// In-memory state representation of an un-ACKed message
/// </summary>
internal struct PersistentEvent
{
public PersistentEvent(IConfirmableMessage msg, IActorRef sender)
{
Msg = msg;
Sender = sender;
}
public IConfirmableMessage Msg { get; }
public IActorRef Sender { get; }
}
}
}