forked from akkadotnet/akka.net
-
Notifications
You must be signed in to change notification settings - Fork 4
/
SqlSnapshotStore.cs
184 lines (157 loc) · 6.69 KB
/
SqlSnapshotStore.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
//-----------------------------------------------------------------------
// <copyright file="SqlSnapshotStore.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Configuration;
using Akka.Event;
using Akka.Persistence.Snapshot;
namespace Akka.Persistence.Sql.Common.Snapshot
{
/// <summary>
/// Abstract snapshot store implementation, customized to work with SQL-based persistence providers.
/// </summary>
public abstract class SqlSnapshotStore : SnapshotStore, IWithUnboundedStash
{
#region messages
private sealed class Initialized
{
public static readonly Initialized Instance = new Initialized();
private Initialized() { }
}
#endregion
/// <summary>
/// List of cancellation tokens for all pending asynchronous database operations.
/// </summary>
private readonly CancellationTokenSource _pendingRequestsCancellation;
private readonly SnapshotStoreSettings _settings;
protected SqlSnapshotStore(Config config)
{
_settings = new SnapshotStoreSettings(config);
_pendingRequestsCancellation = new CancellationTokenSource();
}
private ILoggingAdapter _log;
protected ILoggingAdapter Log => _log ?? (_log ?? Context.GetLogger());
public IStash Stash { get; set; }
/// <summary>
/// Query executor used to convert snapshot store related operations into corresponding SQL queries.
/// </summary>
public abstract ISnapshotQueryExecutor QueryExecutor { get; }
/// <summary>
/// Returns a new instance of database connection.
/// </summary>
protected abstract DbConnection CreateDbConnection(string connectionString);
/// <summary>
/// Returns a new instance of database connection.
/// </summary>
public DbConnection CreateDbConnection()
{
return CreateDbConnection(GetConnectionString());
}
protected override void PreStart()
{
base.PreStart();
if (_settings.AutoInitialize)
{
Initialize().PipeTo(Self);
BecomeStacked(WaitingForInitialization);
}
}
protected override void PostStop()
{
base.PostStop();
// stop all operations executed in the background
_pendingRequestsCancellation.Cancel();
}
private async Task<Initialized> Initialize()
{
using (var connection = CreateDbConnection())
{
await connection.OpenAsync(_pendingRequestsCancellation.Token);
await QueryExecutor.CreateTableAsync(connection, _pendingRequestsCancellation.Token);
return Initialized.Instance;
}
}
private bool WaitingForInitialization(object message) => message.Match()
.With<Initialized>(_ =>
{
UnbecomeStacked();
Stash.UnstashAll();
})
.With<Failure>(failure =>
{
_log.Error(failure.Exception, "Error during snapshot store intiialization");
Context.Stop(Self);
})
.Default(_ => Stash.Stash())
.WasHandled;
protected virtual string GetConnectionString()
{
var connectionString = _settings.ConnectionString;
#if CONFIGURATION
if (string.IsNullOrEmpty(connectionString))
{
return System.Configuration.ConfigurationManager.ConnectionStrings[_settings.ConnectionStringName].ConnectionString;
}
#endif
return connectionString;
}
/// <summary>
/// Asynchronously loads snapshot with the highest sequence number for a persistent actor/view matching specified criteria.
/// </summary>
protected override async Task<SelectedSnapshot> LoadAsync(string persistenceId, SnapshotSelectionCriteria criteria)
{
using (var connection = CreateDbConnection())
{
await connection.OpenAsync(_pendingRequestsCancellation.Token);
return await QueryExecutor.SelectSnapshotAsync(connection, _pendingRequestsCancellation.Token, persistenceId, criteria.MaxSequenceNr, criteria.MaxTimeStamp);
}
}
/// <summary>
/// Asynchronously stores a snapshot with metadata as record in SQL table.
/// </summary>
protected override async Task SaveAsync(SnapshotMetadata metadata, object snapshot)
{
using (var connection = CreateDbConnection())
{
await connection.OpenAsync();
await QueryExecutor.InsertAsync(connection, _pendingRequestsCancellation.Token, snapshot, metadata);
}
}
protected override async Task DeleteAsync(SnapshotMetadata metadata)
{
using (var connection = CreateDbConnection())
{
await connection.OpenAsync();
DateTime? timestamp = metadata.Timestamp != DateTime.MinValue ? metadata.Timestamp : default(DateTime?);
await QueryExecutor.DeleteAsync(connection, _pendingRequestsCancellation.Token, metadata.PersistenceId, metadata.SequenceNr, timestamp);
}
}
protected override async Task DeleteAsync(string persistenceId, SnapshotSelectionCriteria criteria)
{
using (var connection = CreateDbConnection())
{
await connection.OpenAsync();
await QueryExecutor.DeleteBatchAsync(connection, _pendingRequestsCancellation.Token, persistenceId, criteria.MaxSequenceNr, criteria.MaxTimeStamp);
}
}
private SnapshotEntry ToSnapshotEntry(SnapshotMetadata metadata, object snapshot)
{
var snapshotType = snapshot.GetType();
var serializer = Context.System.Serialization.FindSerializerForType(snapshotType);
var binary = serializer.ToBinary(snapshot);
return new SnapshotEntry(
persistenceId: metadata.PersistenceId,
sequenceNr: metadata.SequenceNr,
timestamp: metadata.Timestamp,
manifest: snapshotType.QualifiedTypeName(),
payload: binary);
}
}
}