/
SnapshotStore.cs
259 lines (245 loc) · 11 KB
/
SnapshotStore.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
//-----------------------------------------------------------------------
// <copyright file="SnapshotStore.cs" company="Akka.NET Project">
// Copyright (C) 2009-2023 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2023 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Pattern;
namespace Akka.Persistence.Snapshot
{
/// <summary>
/// Abstract snapshot store.
/// </summary>
public abstract class SnapshotStore : ActorBase
{
private readonly TaskContinuationOptions _continuationOptions = TaskContinuationOptions.ExecuteSynchronously;
private readonly bool _publish;
private readonly CircuitBreaker _breaker;
/// <summary>
/// Initializes a new instance of the <see cref="SnapshotStore"/> class.
/// </summary>
/// <exception cref="ArgumentException">
/// This exception is thrown when the associated Persistence extension has not been used in current actor system context.
/// </exception>
protected SnapshotStore()
{
var extension = Persistence.Instance.Apply(Context.System);
if (extension == null)
{
throw new ArgumentException("Couldn't initialize SnapshotStore instance, because associated Persistence extension has not been used in current actor system context.");
}
_publish = extension.Settings.Internal.PublishPluginCommands;
var config = extension.ConfigFor(Self);
_breaker = CircuitBreaker.Create(
Context.System.Scheduler,
config.GetInt("circuit-breaker.max-failures", 10),
config.GetTimeSpan("circuit-breaker.call-timeout", TimeSpan.FromSeconds(10)),
config.GetTimeSpan("circuit-breaker.reset-timeout", TimeSpan.FromSeconds(30)));
}
/// <inheritdoc/>
protected sealed override bool Receive(object message)
{
return ReceiveSnapshotStore(message) || ReceivePluginInternal(message);
}
private bool ReceiveSnapshotStore(object message)
{
var senderPersistentActor = Sender; // Sender is PersistentActor
var self = Self; //Self MUST BE CLOSED OVER here, or the code below will be subject to race conditions
if (message is LoadSnapshot loadSnapshot)
{
if (loadSnapshot.Criteria == SnapshotSelectionCriteria.None)
{
senderPersistentActor.Tell(new LoadSnapshotResult(null, loadSnapshot.ToSequenceNr));
}
else
{
_breaker.WithCircuitBreaker(() => LoadAsync(loadSnapshot.PersistenceId, loadSnapshot.Criteria.Limit(loadSnapshot.ToSequenceNr)))
.ContinueWith(t => (!t.IsFaulted && !t.IsCanceled)
? new LoadSnapshotResult(t.Result, loadSnapshot.ToSequenceNr) as ISnapshotResponse
: new LoadSnapshotFailed(t.IsFaulted
? TryUnwrapException(t.Exception)
: new OperationCanceledException("LoadAsync canceled, possibly due to timing out.")),
_continuationOptions)
.PipeTo(senderPersistentActor);
}
}
else if (message is SaveSnapshot saveSnapshot)
{
var metadata = new SnapshotMetadata(saveSnapshot.Metadata.PersistenceId, saveSnapshot.Metadata.SequenceNr, DateTime.UtcNow);
_breaker.WithCircuitBreaker(() => SaveAsync(metadata, saveSnapshot.Snapshot))
.ContinueWith(t => (!t.IsFaulted && !t.IsCanceled)
? new SaveSnapshotSuccess(metadata) as ISnapshotResponse
: new SaveSnapshotFailure(saveSnapshot.Metadata,
t.IsFaulted
? TryUnwrapException(t.Exception)
: new OperationCanceledException("SaveAsync canceled, possibly due to timing out.")),
_continuationOptions)
.PipeTo(self, senderPersistentActor);
}
else if (message is SaveSnapshotSuccess)
{
try
{
ReceivePluginInternal(message);
}
finally
{
senderPersistentActor.Tell(message);
}
}
else if (message is SaveSnapshotFailure saveSnapshotFailure)
{
try
{
ReceivePluginInternal(message);
_breaker.WithCircuitBreaker(() => DeleteAsync(saveSnapshotFailure.Metadata));
}
finally
{
senderPersistentActor.Tell(message);
}
}
else if (message is DeleteSnapshot deleteSnapshot)
{
var eventStream = Context.System.EventStream;
_breaker.WithCircuitBreaker(() => DeleteAsync(deleteSnapshot.Metadata))
.ContinueWith(t => (!t.IsFaulted && !t.IsCanceled)
? new DeleteSnapshotSuccess(deleteSnapshot.Metadata) as ISnapshotResponse
: new DeleteSnapshotFailure(deleteSnapshot.Metadata,
t.IsFaulted
? TryUnwrapException(t.Exception)
: new OperationCanceledException("DeleteAsync canceled, possibly due to timing out.")),
_continuationOptions)
.PipeTo(self, senderPersistentActor)
.ContinueWith(_ =>
{
if (_publish)
eventStream.Publish(message);
}, _continuationOptions);
}
else if (message is DeleteSnapshotSuccess)
{
try
{
ReceivePluginInternal(message);
}
finally
{
senderPersistentActor.Tell(message);
}
}
else if (message is DeleteSnapshotFailure)
{
try
{
ReceivePluginInternal(message);
}
finally
{
senderPersistentActor.Tell(message);
}
}
else if (message is DeleteSnapshots deleteSnapshots)
{
var eventStream = Context.System.EventStream;
_breaker.WithCircuitBreaker(() => DeleteAsync(deleteSnapshots.PersistenceId, deleteSnapshots.Criteria))
.ContinueWith(t => (!t.IsFaulted && !t.IsCanceled)
? new DeleteSnapshotsSuccess(deleteSnapshots.Criteria) as ISnapshotResponse
: new DeleteSnapshotsFailure(deleteSnapshots.Criteria,
t.IsFaulted
? TryUnwrapException(t.Exception)
: new OperationCanceledException("DeleteAsync canceled, possibly due to timing out.")),
_continuationOptions)
.PipeTo(self, senderPersistentActor)
.ContinueWith(_ =>
{
if (_publish)
eventStream.Publish(message);
}, _continuationOptions);
}
else if (message is DeleteSnapshotsSuccess)
{
try
{
ReceivePluginInternal(message);
}
finally
{
senderPersistentActor.Tell(message);
}
}
else if (message is DeleteSnapshotsFailure)
{
try
{
ReceivePluginInternal(message);
}
finally
{
senderPersistentActor.Tell(message);
}
}
else return false;
return true;
}
private Exception TryUnwrapException(Exception e)
{
var aggregateException = e as AggregateException;
if (aggregateException != null)
{
aggregateException = aggregateException.Flatten();
if (aggregateException.InnerExceptions.Count == 1)
return aggregateException.InnerExceptions[0];
}
return e;
}
/// <summary>
/// Plugin API: Asynchronously loads a snapshot.
///
/// This call is protected with a circuit-breaker
/// </summary>
/// <param name="persistenceId">Id of the persistent actor.</param>
/// <param name="criteria">Selection criteria for loading.</param>
/// <returns>TBD</returns>
protected abstract Task<SelectedSnapshot> LoadAsync(string persistenceId, SnapshotSelectionCriteria criteria);
/// <summary>
/// Plugin API: Asynchronously saves a snapshot.
///
/// This call is protected with a circuit-breaker
/// </summary>
/// <param name="metadata">Snapshot metadata.</param>
/// <param name="snapshot">Snapshot.</param>
/// <returns>TBD</returns>
protected abstract Task SaveAsync(SnapshotMetadata metadata, object snapshot);
/// <summary>
/// Plugin API: Deletes the snapshot identified by <paramref name="metadata"/>.
///
/// This call is protected with a circuit-breaker
/// </summary>
/// <param name="metadata">Snapshot metadata.</param>
/// <returns>TBD</returns>
protected abstract Task DeleteAsync(SnapshotMetadata metadata);
/// <summary>
/// Plugin API: Deletes all snapshots matching provided <paramref name="criteria"/>.
///
/// This call is protected with a circuit-breaker
/// </summary>
/// <param name="persistenceId">Id of the persistent actor.</param>
/// <param name="criteria">Selection criteria for deleting.</param>
/// <returns>TBD</returns>
protected abstract Task DeleteAsync(string persistenceId, SnapshotSelectionCriteria criteria);
/// <summary>
/// Plugin API: Allows plugin implementers to use f.PipeTo(Self)
/// and handle additional messages for implementing advanced features
/// </summary>
/// <param name="message">TBD</param>
/// <returns>TBD</returns>
protected virtual bool ReceivePluginInternal(object message)
{
return false;
}
}
}