-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathBatchingSqlJournal.cs
1295 lines (1130 loc) · 56.5 KB
/
BatchingSqlJournal.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------
// <copyright file="BatchingSqlJournal.cs" company="Akka.NET Project">
// Copyright (C) 2009-2018 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2018 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Configuration;
using Akka.Event;
using Akka.Pattern;
using Akka.Persistence.Journal;
using Akka.Serialization;
using Akka.Util;
namespace Akka.Persistence.Sql.Common.Journal
{
/// <summary>
/// Settings used for managing filter rules during event replay.
/// </summary>
public sealed class ReplayFilterSettings
{
/// <summary>
/// Mode used when detecting invalid events.
/// </summary>
public readonly ReplayFilterMode Mode;
/// <summary>
/// Size (in number of events) of the look ahead buffer used for analyzing the events.
/// </summary>
public readonly int WindowSize;
/// <summary>
/// Maximum number of writerUuid to remember.
/// </summary>
public readonly int MaxOldWriters;
/// <summary>
/// Determine if the debug logging is enabled for each replayed event.
/// </summary>
public readonly bool IsDebug;
/// <summary>
/// Determine if the replay filter feature is enabled
/// </summary>
public bool IsEnabled => Mode != ReplayFilterMode.Disabled;
/// <summary>
/// Initializes a new instance of the <see cref="ReplayFilterSettings" /> class.
/// </summary>
/// <param name="config">The configuration used to configure the replay filter.</param>
/// <exception cref="Akka.Configuration.ConfigurationException">
/// This exception is thrown when an invalid <c>replay-filter.mode</c> is read from the specified <paramref name="config"/>.
/// Acceptable <c>replay-filter.mode</c> values include: off | repair-by-discard-old | fail | warn
/// </exception>
/// <exception cref="ArgumentNullException">
/// This exception is thrown when the specified <paramref name="config"/> is undefined.
/// </exception>
public ReplayFilterSettings(Config config)
{
if (config == null) throw new ArgumentNullException(nameof(config), "No HOCON config was provided for replay filter settings");
ReplayFilterMode mode;
var replayModeString = config.GetString("mode", "off");
switch (replayModeString)
{
case "off": mode = ReplayFilterMode.Disabled; break;
case "repair-by-discard-old": mode = ReplayFilterMode.RepairByDiscardOld; break;
case "fail": mode = ReplayFilterMode.Fail; break;
case "warn": mode = ReplayFilterMode.Warn; break;
default: throw new Akka.Configuration.ConfigurationException($"Invalid replay-filter.mode [{replayModeString}], supported values [off, repair-by-discard-old, fail, warn]");
}
Mode = mode;
WindowSize = config.GetInt("window-size", 100);
MaxOldWriters = config.GetInt("max-old-writers", 10);
IsDebug = config.GetBoolean("debug", false);
}
/// <summary>
/// Initializes a new instance of the <see cref="ReplayFilterSettings" /> class.
/// </summary>
/// <param name="mode">The mode used when detecting invalid events.</param>
/// <param name="windowSize">The size of the replay filter's buffer.</param>
/// <param name="maxOldWriters">The maximum number of writerUuid to remember.</param>
/// <param name="isDebug">If set to <c>true</c>, debug logging is enabled for each replayed event.</param>
public ReplayFilterSettings(ReplayFilterMode mode, int windowSize, int maxOldWriters, bool isDebug)
{
Mode = mode;
WindowSize = windowSize;
MaxOldWriters = maxOldWriters;
IsDebug = isDebug;
}
}
/// <summary>
/// Settings used by <see cref="CircuitBreaker"/> used internally by
/// the batching journal when executing event batches.
/// </summary>
public sealed class CircuitBreakerSettings
{
/// <summary>
/// Maximum number of failures that can happen before the circuit opens.
/// </summary>
public int MaxFailures { get; }
/// <summary>
/// Maximum time available for operation to execute before
/// <see cref="CircuitBreaker"/> considers it a failure.
/// </summary>
public TimeSpan CallTimeout { get; }
/// <summary>
/// Timeout that has to pass before <see cref="CircuitBreaker"/>
/// moves into half-closed state, trying to eventually close
/// after sampling an operation.
/// </summary>
public TimeSpan ResetTimeout { get; }
/// <summary>
/// Creates a new instance of the <see cref="CircuitBreakerSettings"/> from provided HOCON <paramref name="config"/>.
/// </summary>
/// <param name="config">The configuration used to configure the circuit breaker.</param>
/// <exception cref="ArgumentNullException">
/// This exception is thrown when the specified <paramref name="config"/> is undefined.
/// </exception>
public CircuitBreakerSettings(Config config)
{
if (config == null) throw new ArgumentNullException(nameof(config));
MaxFailures = config.GetInt("max-failures", 5);
CallTimeout = config.GetTimeSpan("call-timeout", TimeSpan.FromSeconds(20));
ResetTimeout = config.GetTimeSpan("reset-timeout", TimeSpan.FromSeconds(60));
}
/// <summary>
/// Initializes a new instance of the <see cref="CircuitBreakerSettings" /> class.
/// </summary>
/// <param name="maxFailures">The maximum number of failures that can happen before the circuit opens.</param>
/// <param name="callTimeout">
/// The maximum time available for operation to execute before <see cref="CircuitBreaker"/> considers it a failure.
/// </param>
/// <param name="resetTimeout">
/// The amount of time before <see cref="CircuitBreaker"/> moves into the half-closed state.
/// </param>
public CircuitBreakerSettings(int maxFailures, TimeSpan callTimeout, TimeSpan resetTimeout)
{
MaxFailures = maxFailures;
CallTimeout = callTimeout;
ResetTimeout = resetTimeout;
}
}
/// <summary>
/// All settings that can be used by implementations of
/// <see cref="BatchingSqlJournal{TConnection,TCommand}"/>.
/// </summary>
public abstract class BatchingSqlJournalSetup
{
/// <summary>
/// Connection string to a SQL database.
/// </summary>
public string ConnectionString { get; }
/// <summary>
/// Maximum number of batch operations allowed to be executed at the same time.
/// Each batch operation must acquire a <see cref="DbConnection"/>, so this setting
/// can be effectively used to limit the usage of ADO.NET connection pool by current journal.
/// </summary>
public int MaxConcurrentOperations { get; }
/// <summary>
/// Maximum size of single batch of operations to be executed over a single <see cref="DbConnection"/>.
/// </summary>
public int MaxBatchSize { get; }
/// <summary>
/// Maximum size of requests stored in journal buffer. Once buffer will be surpassed, it will start
/// to apply <see cref="BatchingSqlJournal{TConnection,TCommand}.OnBufferOverflow"/> method to incoming requests.
/// </summary>
public int MaxBufferSize { get; }
/// <summary>
/// If true, once created, journal will run all SQL scripts stored under
/// <see cref="BatchingSqlJournal{TConnection,TCommand}.Initializers"/> collection
/// prior to starting executing any requests. In most implementation this is used
/// to initialize necessary tables.
/// </summary>
public bool AutoInitialize { get; }
/// <summary>
/// Maximum time given for executed <see cref="DbCommand"/> to complete.
/// </summary>
public TimeSpan ConnectionTimeout { get; }
/// <summary>
/// Isolation level of transactions used during query execution.
/// </summary>
public IsolationLevel IsolationLevel { get; }
/// <summary>
/// Settings specific to <see cref="CircuitBreaker"/>, which is used internally
/// for executing request batches.
/// </summary>
public CircuitBreakerSettings CircuitBreakerSettings { get; }
/// <summary>
/// Settings specific to replay filter rules used when replaying events from database
/// back to the persistent actors.
/// </summary>
public ReplayFilterSettings ReplayFilterSettings { get; }
/// <summary>
/// Database specific naming conventions (table and column names) used to construct valid SQL statements.
/// </summary>
public QueryConfiguration NamingConventions { get; }
/// <summary>
/// The default serializer used when not type override matching is found
/// </summary>
public string DefaultSerializer { get; }
/// <summary>
/// Initializes a new instance of the <see cref="BatchingSqlJournalSetup" /> class.
/// </summary>
/// <param name="config">The configuration used to configure the journal.</param>
/// <param name="namingConventions">The naming conventions used by the database to construct valid SQL statements.</param>
/// <exception cref="Akka.Configuration.ConfigurationException">
/// This exception is thrown for a couple of reasons.
/// <ul>
/// <li>A connection string for the SQL event journal was not specified.</li>
/// <li>
/// An unknown <c>isolation-level</c> value was specified. Acceptable <c>isolation-level</c> values include:
/// chaos | read-committed | read-uncommitted | repeatable-read | serializable | snapshot | unspecified
/// </li>
/// </ul>
/// </exception>
/// <exception cref="ArgumentNullException">
/// This exception is thrown when the specified <paramref name="config"/> is undefined.
/// </exception>
protected BatchingSqlJournalSetup(Config config, QueryConfiguration namingConventions)
{
if (config == null) throw new ArgumentNullException(nameof(config), "Sql journal settings cannot be initialized, because required HOCON section couldn't been found");
var connectionString = config.GetString("connection-string");
#if CONFIGURATION
if (string.IsNullOrWhiteSpace(connectionString))
{
connectionString = System.Configuration.ConfigurationManager
.ConnectionStrings[config.GetString("connection-string-name", "DefaultConnection")]
.ConnectionString;
}
#endif
if (string.IsNullOrWhiteSpace(connectionString))
throw new Akka.Configuration.ConfigurationException("No connection string for Sql Event Journal was specified");
IsolationLevel level;
switch (config.GetString("isolation-level", "unspecified"))
{
case "chaos": level = IsolationLevel.Chaos; break;
case "read-committed": level = IsolationLevel.ReadCommitted; break;
case "read-uncommitted": level = IsolationLevel.ReadUncommitted; break;
case "repeatable-read": level = IsolationLevel.RepeatableRead; break;
case "serializable": level = IsolationLevel.Serializable; break;
case "snapshot": level = IsolationLevel.Snapshot; break;
case "unspecified": level = IsolationLevel.Unspecified; break;
default: throw new Akka.Configuration.ConfigurationException("Unknown isolation-level value. Should be one of: chaos | read-committed | read-uncommitted | repeatable-read | serializable | snapshot | unspecified");
}
ConnectionString = connectionString;
MaxConcurrentOperations = config.GetInt("max-concurrent-operations", 64);
MaxBatchSize = config.GetInt("max-batch-size", 100);
MaxBufferSize = config.GetInt("max-buffer-size", 500000);
AutoInitialize = config.GetBoolean("auto-initialize", false);
ConnectionTimeout = config.GetTimeSpan("connection-timeout", TimeSpan.FromSeconds(30));
IsolationLevel = level;
CircuitBreakerSettings = new CircuitBreakerSettings(config.GetConfig("circuit-breaker"));
ReplayFilterSettings = new ReplayFilterSettings(config.GetConfig("replay-filter"));
NamingConventions = namingConventions;
DefaultSerializer = config.GetString("serializer");
}
/// <summary>
/// Initializes a new instance of the <see cref="BatchingSqlJournalSetup" /> class.
/// </summary>
/// <param name="connectionString">The connection string used to connect to the database.</param>
/// <param name="maxConcurrentOperations">The maximum number of batch operations allowed to be executed at the same time.</param>
/// <param name="maxBatchSize">The maximum size of single batch of operations to be executed over a single <see cref="DbConnection"/>.</param>
/// <param name="maxBufferSize">The maximum size of requests stored in journal buffer.</param>
/// <param name="autoInitialize">
/// If set to <c>true</c>, the journal executes all SQL scripts stored under the
/// <see cref="BatchingSqlJournal{TConnection,TCommand}.Initializers"/> collection prior
/// to starting executing any requests.
/// </param>
/// <param name="connectionTimeout">The maximum time given for executed <see cref="DbCommand"/> to complete.</param>
/// <param name="isolationLevel">The isolation level of transactions used during query execution.</param>
/// <param name="circuitBreakerSettings">
/// The settings used by the <see cref="CircuitBreaker"/> when for executing request batches.
/// </param>
/// <param name="replayFilterSettings">The settings used when replaying events from database back to the persistent actors.</param>
/// <param name="namingConventions">The naming conventions used by the database to construct valid SQL statements.</param>
/// <param name="defaultSerializer">The serializer used when no specific type matching can be found.</param>
protected BatchingSqlJournalSetup(string connectionString, int maxConcurrentOperations, int maxBatchSize, int maxBufferSize, bool autoInitialize, TimeSpan connectionTimeout, IsolationLevel isolationLevel, CircuitBreakerSettings circuitBreakerSettings, ReplayFilterSettings replayFilterSettings, QueryConfiguration namingConventions, string defaultSerializer)
{
ConnectionString = connectionString;
MaxConcurrentOperations = maxConcurrentOperations;
MaxBatchSize = maxBatchSize;
MaxBufferSize = maxBufferSize;
AutoInitialize = autoInitialize;
ConnectionTimeout = connectionTimeout;
IsolationLevel = isolationLevel;
CircuitBreakerSettings = circuitBreakerSettings;
ReplayFilterSettings = replayFilterSettings;
NamingConventions = namingConventions;
DefaultSerializer = defaultSerializer;
}
}
/// <summary>
/// An abstract journal used by <see cref="PersistentActor"/>s to read/write events to a database.
///
/// This implementation uses horizontal batching to recycle usage of the <see cref="DbConnection"/>
/// and to optimize writes made to a database. Batching journal is not going to acquire a new DB
/// connection on every request. Instead it will batch incoming requests and execute them only when
/// a previous operation batch has been completed. This means that requests coming from many
/// actors at the same time will be executed in one batch.
///
/// Maximum number of batches executed at the same time is defined by
/// <see cref="BatchingSqlJournalSetup.MaxConcurrentOperations"/> setting, while max allowed batch
/// size is defined by <see cref="BatchingSqlJournalSetup.MaxBatchSize"/> setting.
///
/// Batching journal also defines <see cref="BatchingSqlJournalSetup.MaxBufferSize"/>, which defines
/// a maximum number of all requests stored at once in memory. Once that value is surpassed, journal
/// will start to apply <see cref="OnBufferOverflow"/> logic on each incoming requests, until a
/// buffer gets freed again. This may be used for overflow strategies, request denials or backpressure.
/// </summary>
/// <typeparam name="TConnection">A concrete implementation of <see cref="DbConnection"/> for targeted database provider.</typeparam>
/// <typeparam name="TCommand">A concrete implementation of <see cref="DbCommand"/> for targeted database provider.</typeparam>
public abstract class BatchingSqlJournal<TConnection, TCommand> : WriteJournalBase
where TConnection : DbConnection
where TCommand : DbCommand
{
#region internal classes
private sealed class BatchComplete
{
public readonly int ChunkId;
public readonly int OperationCount;
public readonly TimeSpan TimeSpent;
public readonly Exception Cause;
public BatchComplete(int chunkId, int operationCount, TimeSpan timeSpent, Exception cause = null)
{
ChunkId = chunkId;
TimeSpent = timeSpent;
OperationCount = operationCount;
Cause = cause;
}
}
// this little guy will be called only once, only by the current journal
private sealed class GetCurrentPersistenceIds
{
public static readonly GetCurrentPersistenceIds Instance = new GetCurrentPersistenceIds();
private GetCurrentPersistenceIds() { }
}
private struct RequestChunk
{
public readonly int ChunkId;
public readonly IJournalRequest[] Requests;
public RequestChunk(int chunkId, IJournalRequest[] requests)
{
ChunkId = chunkId;
Requests = requests;
}
}
#endregion
/// <summary>
/// Default index of <see cref="IPersistentRepresentation.PersistenceId"/>
/// column get from <see cref="ByPersistenceIdSql"/> query.
/// </summary>
protected const int PersistenceIdIndex = 0;
/// <summary>
/// Default index of <see cref="IPersistentRepresentation.SequenceNr"/>
/// column get from <see cref="ByPersistenceIdSql"/> query.
/// </summary>
protected const int SequenceNrIndex = 1;
//protected const int TimestampIndex = 2;
/// <summary>
/// Default index of <see cref="IPersistentRepresentation.IsDeleted"/>
/// column get from <see cref="ByPersistenceIdSql"/> query.
/// </summary>
protected const int IsDeletedIndex = 3;
/// <summary>
/// Default index of <see cref="IPersistentRepresentation.Manifest"/>
/// column get from <see cref="ByPersistenceIdSql"/> query.
/// </summary>
protected const int ManifestIndex = 4;
/// <summary>
/// Default index of <see cref="IPersistentRepresentation.Payload"/>
/// column get from <see cref="ByPersistenceIdSql"/> query.
/// </summary>
protected const int PayloadIndex = 5;
/// <summary>
/// Default index of <see cref="Serializer.Identifier"/>
/// </summary>
protected const int SerializerIdIndex = 6;
/// <summary>
/// Default index of tags column get from <see cref="ByTagSql"/> query.
/// </summary>
protected const int OrderingIndex = 7;
/// <summary>
/// SQL query executed as result of <see cref="DeleteMessagesTo"/> request to journal.
/// </summary>
protected virtual string DeleteBatchSql { get; }
/// <summary>
/// SQL query executed as result of <see cref="ReadHighestSequenceNr"/> request to journal.
/// Also used under some conditions, when storing metadata upon <see cref="DeleteMessagesTo"/> request.
/// </summary>
protected virtual string HighestSequenceNrSql { get; }
/// <summary>
/// SQL statement executed as result of <see cref="WriteMessages"/> request to journal.
/// </summary>
protected virtual string InsertEventSql { get; }
/// <summary>
/// SQL query executed as result of <see cref="GetCurrentPersistenceIds"/> request to journal.
/// It's a part of persistence query protocol.
/// </summary>
protected virtual string AllPersistenceIdsSql { get; }
/// <summary>
/// SQL statement executed as result of writing metadata, which is
/// a possible effect of <see cref="DeleteMessagesTo"/> request.
/// </summary>
protected virtual string UpdateSequenceNrSql { get; }
/// <summary>
/// SQL query executed as result of <see cref="ReplayMessages"/> request to journal.
/// It's also part of persistence query protocol.
/// </summary>
protected virtual string ByPersistenceIdSql { get; }
/// <summary>
/// SQL query executed as result of <see cref="ReplayTaggedMessages"/> request to journal.
/// It's a part of persistence query protocol.
/// </summary>
protected virtual string ByTagSql { get; }
/// <summary>
/// A named collection of SQL statements to be executed once journal actor gets initialized
/// and the <see cref="BatchingSqlJournalSetup.AutoInitialize"/> flag is set.
/// </summary>
protected abstract ImmutableDictionary<string, string> Initializers { get; }
/// <summary>
/// All configurable settings defined for a current batching journal.
/// </summary>
protected BatchingSqlJournalSetup Setup { get; }
/// <summary>
/// Flag determining if current journal has any subscribers for <see cref="EventAppended"/> events.
/// </summary>
protected bool HasPersistenceIdSubscribers => _persistenceIdSubscribers.Count != 0;
/// <summary>
/// Flag determining if current journal has any subscribers for <see cref="TaggedEventAppended"/> events.
/// </summary>
protected bool HasTagSubscribers => _tagSubscribers.Count != 0;
/// <summary>
/// Flag determining if current journal has any subscribers for <see cref="GetCurrentPersistenceIds"/> and
/// <see cref="PersistenceIdAdded"/> messages.
/// </summary>
protected bool HasAllIdsSubscribers => _allIdsSubscribers.Count != 0;
/// <summary>
/// Flag determining if incoming journal requests should be published in current actor system event stream.
/// Useful mostly for tests.
/// </summary>
protected readonly bool CanPublish;
/// <summary>
/// Logging adapter for current journal actor .
/// </summary>
protected readonly ILoggingAdapter Log;
/// <summary>
/// Buffer for requests that are waiting to be served when next DB connection will be released.
/// This object access is NOT thread safe.
/// </summary>
protected readonly Queue<IJournalRequest> Buffer;
private readonly Dictionary<string, HashSet<IActorRef>> _persistenceIdSubscribers;
private readonly Dictionary<string, HashSet<IActorRef>> _tagSubscribers;
private readonly HashSet<IActorRef> _allIdsSubscribers;
private readonly HashSet<string> _allPersistenceIds;
private readonly Akka.Serialization.Serialization _serialization;
private readonly CircuitBreaker _circuitBreaker;
private int _remainingOperations;
/// <summary>
/// Initializes a new instance of the <see cref="BatchingSqlJournal{TConnection, TCommand}" /> class.
/// </summary>
/// <param name="setup">The settings used to configure the journal.</param>
protected BatchingSqlJournal(BatchingSqlJournalSetup setup)
{
Setup = setup;
CanPublish = Persistence.Instance.Apply(Context.System).Settings.Internal.PublishPluginCommands;
_persistenceIdSubscribers = new Dictionary<string, HashSet<IActorRef>>();
_tagSubscribers = new Dictionary<string, HashSet<IActorRef>>();
_allIdsSubscribers = new HashSet<IActorRef>();
_allPersistenceIds = new HashSet<string>();
_remainingOperations = Setup.MaxConcurrentOperations;
Buffer = new Queue<IJournalRequest>(Setup.MaxBatchSize);
_serialization = Context.System.Serialization;
Log = Context.GetLogger();
_circuitBreaker = CircuitBreaker.Create(
maxFailures: Setup.CircuitBreakerSettings.MaxFailures,
callTimeout: Setup.CircuitBreakerSettings.CallTimeout,
resetTimeout: Setup.CircuitBreakerSettings.ResetTimeout);
var conventions = Setup.NamingConventions;
var allEventColumnNames = $@"
e.{conventions.PersistenceIdColumnName} as PersistenceId,
e.{conventions.SequenceNrColumnName} as SequenceNr,
e.{conventions.TimestampColumnName} as Timestamp,
e.{conventions.IsDeletedColumnName} as IsDeleted,
e.{conventions.ManifestColumnName} as Manifest,
e.{conventions.PayloadColumnName} as Payload,
e.{conventions.SerializerIdColumnName} as SerializerId";
AllPersistenceIdsSql = $@"
SELECT DISTINCT e.{conventions.PersistenceIdColumnName} as PersistenceId
FROM {conventions.FullJournalTableName} e;";
HighestSequenceNrSql = $@"
SELECT MAX(u.SeqNr) as SequenceNr
FROM (
SELECT e.{conventions.SequenceNrColumnName} as SeqNr FROM {conventions.FullJournalTableName} e WHERE e.{conventions.PersistenceIdColumnName} = @PersistenceId
UNION
SELECT m.{conventions.SequenceNrColumnName} as SeqNr FROM {conventions.FullMetaTableName} m WHERE m.{conventions.PersistenceIdColumnName} = @PersistenceId) as u";
DeleteBatchSql = $@"
DELETE FROM {conventions.FullJournalTableName}
WHERE {conventions.PersistenceIdColumnName} = @PersistenceId AND {conventions.SequenceNrColumnName} <= @ToSequenceNr;
DELETE FROM {conventions.FullMetaTableName}
WHERE {conventions.PersistenceIdColumnName} = @PersistenceId AND {conventions.SequenceNrColumnName} <= @ToSequenceNr;";
UpdateSequenceNrSql = $@"
INSERT INTO {conventions.FullMetaTableName} ({conventions.PersistenceIdColumnName}, {conventions.SequenceNrColumnName})
VALUES (@PersistenceId, @SequenceNr);";
ByPersistenceIdSql =
$@"
SELECT {allEventColumnNames}
FROM {conventions.FullJournalTableName} e
WHERE e.{conventions.PersistenceIdColumnName} = @PersistenceId
AND e.{conventions.SequenceNrColumnName} BETWEEN @FromSequenceNr AND @ToSequenceNr
ORDER BY e.{conventions.SequenceNrColumnName} ASC;";
ByTagSql =
$@"
SELECT {allEventColumnNames}, e.{conventions.OrderingColumnName} as Ordering
FROM {conventions.FullJournalTableName} e
WHERE e.{conventions.OrderingColumnName} > @Ordering AND e.{conventions.TagsColumnName} LIKE @Tag
ORDER BY {conventions.OrderingColumnName} ASC";
InsertEventSql = $@"
INSERT INTO {conventions.FullJournalTableName} (
{conventions.PersistenceIdColumnName},
{conventions.SequenceNrColumnName},
{conventions.TimestampColumnName},
{conventions.IsDeletedColumnName},
{conventions.ManifestColumnName},
{conventions.PayloadColumnName},
{conventions.TagsColumnName},
{conventions.SerializerIdColumnName}
) VALUES (
@PersistenceId,
@SequenceNr,
@Timestamp,
@IsDeleted,
@Manifest,
@Payload,
@Tag,
@SerializerId
)";
}
/// <summary>
/// TBD
/// </summary>
protected override void PreStart()
{
if (Setup.AutoInitialize)
{
using (var connection = CreateConnection(Setup.ConnectionString))
using (var command = connection.CreateCommand())
{
connection.Open();
foreach (var entry in Initializers)
{
Log.Debug("Executing initialization script: {0}", entry.Key);
command.CommandText = entry.Value;
command.ExecuteNonQuery();
}
}
}
base.PreStart();
}
/// <summary>
/// TBD
/// </summary>
/// <param name="message">TBD</param>
/// <returns>TBD</returns>
protected sealed override bool Receive(object message)
{
if (message is WriteMessages) BatchRequest((IJournalRequest)message);
else if (message is ReplayMessages) BatchRequest((IJournalRequest)message);
else if (message is BatchComplete) CompleteBatch((BatchComplete)message);
else if (message is DeleteMessagesTo) BatchRequest((IJournalRequest)message);
else if (message is ReplayTaggedMessages) BatchRequest((IJournalRequest)message);
else if (message is SubscribePersistenceId) AddPersistenceIdSubscriber((SubscribePersistenceId)message);
else if (message is SubscribeAllPersistenceIds) AddAllSubscriber((SubscribeAllPersistenceIds)message);
else if (message is SubscribeTag) AddTagSubscriber((SubscribeTag)message);
else if (message is Terminated) RemoveSubscriber(((Terminated)message).ActorRef);
else if (message is GetCurrentPersistenceIds) InitializePersistenceIds();
else if (message is CurrentPersistenceIds) SendCurrentPersistenceIds((CurrentPersistenceIds)message);
else return false;
return true;
}
private void SendCurrentPersistenceIds(CurrentPersistenceIds message)
{
foreach (var persistenceId in message.AllPersistenceIds)
{
_allPersistenceIds.Add(persistenceId);
}
foreach (var subscriber in _allIdsSubscribers)
{
subscriber.Tell(message);
}
}
#region subscriptions
private void InitializePersistenceIds()
{
var self = Self;
GetAllPersistenceIdsAsync()
.ContinueWith(task =>
{
if (task.IsCanceled || task.IsFaulted)
{
var cause = (Exception)task.Exception ?? new OperationCanceledException("Cancellation occurred while trying to retrieve current persistence ids");
Log.Error(cause, "Couldn't retrieve current persistence ids");
}
else
{
self.Tell(new CurrentPersistenceIds(task.Result));
}
});
}
private async Task<IEnumerable<string>> GetAllPersistenceIdsAsync()
{
var result = new List<string>(256);
using (var connection = CreateConnection(Setup.ConnectionString))
{
await connection.OpenAsync();
using (var command = connection.CreateCommand())
{
command.CommandText = AllPersistenceIdsSql;
var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
result.Add(reader.GetString(0));
}
}
}
return result;
}
private void RemoveSubscriber(IActorRef subscriberRef)
{
_allIdsSubscribers.Remove(subscriberRef);
_persistenceIdSubscribers.RemoveItem(subscriberRef);
_tagSubscribers.RemoveItem(subscriberRef);
}
private void AddTagSubscriber(SubscribeTag message)
{
var subscriber = Sender;
_tagSubscribers.AddItem(message.Tag, subscriber);
Context.Watch(subscriber);
}
private void AddAllSubscriber(SubscribeAllPersistenceIds message)
{
if (!HasAllIdsSubscribers)
{
Self.Tell(GetCurrentPersistenceIds.Instance);
}
var subscriber = Sender;
_allIdsSubscribers.Add(subscriber);
Context.Watch(subscriber);
}
private void AddPersistenceIdSubscriber(SubscribePersistenceId message)
{
var subscriber = Sender;
_persistenceIdSubscribers.AddItem(message.PersistenceId, subscriber);
Context.Watch(subscriber);
}
private void NotifyTagChanged(string tag)
{
if (_tagSubscribers.TryGetValue(tag, out var bucket))
{
var changed = new TaggedEventAppended(tag);
foreach (var subscriber in bucket)
subscriber.Tell(changed);
}
}
private void NotifyPersistenceIdChanged(string persistenceId)
{
if (_persistenceIdSubscribers.TryGetValue(persistenceId, out var bucket))
{
var changed = new EventAppended(persistenceId);
foreach (var subscriber in bucket)
subscriber.Tell(changed);
}
}
protected void NotifyNewPersistenceIdAdded(string persistenceId)
{
if (_allPersistenceIds.Add(persistenceId) && HasAllIdsSubscribers)
{
var added = new PersistenceIdAdded(persistenceId);
foreach (var subscriber in _allIdsSubscribers)
{
subscriber.Tell(added, ActorRefs.NoSender);
}
}
}
#endregion
/// <summary>
/// Tries to add incoming <paramref name="message"/> to <see cref="Buffer"/>.
/// Also checks if any DB connection has been released and next batch can be processed.
/// </summary>
/// <param name="message">TBD</param>
protected void BatchRequest(IJournalRequest message)
{
if (Buffer.Count > Setup.MaxBufferSize)
OnBufferOverflow(message);
else
Buffer.Enqueue(message);
TryProcess();
}
/// <summary>
/// Method called, once given <paramref name="request"/> couldn't be added to <see cref="Buffer"/>
/// due to buffer overflow. Overflow is controlled by max buffer size and can be set using
/// <see cref="BatchingSqlJournalSetup.MaxBufferSize"/> setting.
/// </summary>
/// <param name="request">TBD</param>
protected virtual void OnBufferOverflow(IJournalMessage request)
{
Log.Warning("Batching journal buffer limit has been reached. Denying a request [{0}].", request);
if (request is WriteMessages)
{
var r = (WriteMessages)request;
r.PersistentActor.Tell(new WriteMessagesFailed(JournalBufferOverflowException.Instance), ActorRefs.NoSender);
}
else if (request is ReplayMessages)
{
var r = (ReplayMessages)request;
r.PersistentActor.Tell(new ReplayMessagesFailure(JournalBufferOverflowException.Instance), ActorRefs.NoSender);
}
else if (request is DeleteMessagesTo)
{
var r = (DeleteMessagesTo)request;
r.PersistentActor.Tell(new DeleteMessagesFailure(JournalBufferOverflowException.Instance, r.ToSequenceNr), ActorRefs.NoSender);
}
else if (request is ReplayTaggedMessages)
{
var r = (ReplayTaggedMessages) request;
r.ReplyTo.Tell(new ReplayMessagesFailure(JournalBufferOverflowException.Instance), ActorRefs.NoSender);
}
}
private void TryProcess()
{
if (_remainingOperations > 0 && Buffer.Count > 0)
{
_remainingOperations--;
var chunk = DequeueChunk(_remainingOperations);
var context = Context;
_circuitBreaker.WithCircuitBreaker(() => ExecuteChunk(chunk, context)).PipeTo(Self);
}
}
private async Task<BatchComplete> ExecuteChunk(RequestChunk chunk, IActorContext context)
{
Exception cause = null;
var stopwatch = new Stopwatch();
using (var connection = CreateConnection(Setup.ConnectionString))
{
await connection.OpenAsync();
using (var tx = connection.BeginTransaction(Setup.IsolationLevel))
using (var command = (TCommand)connection.CreateCommand())
{
command.CommandTimeout = (int) Setup.ConnectionTimeout.TotalMilliseconds;
command.Transaction = tx;
try
{
stopwatch.Start();
for (int i = 0; i < chunk.Requests.Length; i++)
{
var req = chunk.Requests[i];
if (req is WriteMessages)
await HandleWriteMessages((WriteMessages)req, command);
else if (req is ReplayMessages)
await HandleReplayMessages((ReplayMessages)req, command, context);
else if (req is DeleteMessagesTo)
await HandleDeleteMessagesTo((DeleteMessagesTo)req, command);
else if (req is ReplayTaggedMessages)
await HandleReplayTaggedMessages((ReplayTaggedMessages)req, command);
else Unhandled(req);
}
tx.Commit();
if (CanPublish)
{
for (int i = 0; i < chunk.Requests.Length; i++)
{
context.System.EventStream.Publish(chunk.Requests[i]);
}
}
}
catch (Exception e)
{
cause = e;
tx.Rollback();
}
finally
{
stopwatch.Stop();
}
}
}
return new BatchComplete(chunk.ChunkId, chunk.Requests.Length, stopwatch.Elapsed, cause);
}
protected virtual async Task HandleDeleteMessagesTo(DeleteMessagesTo req, TCommand command)
{
var toSequenceNr = req.ToSequenceNr;
var persistenceId = req.PersistenceId;
NotifyNewPersistenceIdAdded(persistenceId);
try
{
var highestSequenceNr = await ReadHighestSequenceNr(persistenceId, command);
command.CommandText = DeleteBatchSql;
command.Parameters.Clear();
AddParameter(command, "@PersistenceId", DbType.String, persistenceId);
AddParameter(command, "@ToSequenceNr", DbType.Int64, toSequenceNr);
await command.ExecuteNonQueryAsync();
if (highestSequenceNr <= toSequenceNr)
{
command.CommandText = UpdateSequenceNrSql;
command.Parameters.Clear();
AddParameter(command, "@PersistenceId", DbType.String, persistenceId);
AddParameter(command, "@SequenceNr", DbType.Int64, highestSequenceNr);
await command.ExecuteNonQueryAsync();
}
var response = new DeleteMessagesSuccess(toSequenceNr);
req.PersistentActor.Tell(response);
}
catch (Exception cause)
{
var response = new DeleteMessagesFailure(cause, toSequenceNr);
req.PersistentActor.Tell(response, ActorRefs.NoSender);
}
}
protected virtual async Task<long> ReadHighestSequenceNr(string persistenceId, TCommand command)
{
command.CommandText = HighestSequenceNrSql;
command.Parameters.Clear();
AddParameter(command, "PersistenceId", DbType.String, persistenceId);
var result = await command.ExecuteScalarAsync();
var highestSequenceNr = result is long ? Convert.ToInt64(result) : 0L;
return highestSequenceNr;
}
protected virtual async Task HandleReplayTaggedMessages(ReplayTaggedMessages req, TCommand command)
{
var replyTo = req.ReplyTo;
try
{
var maxSequenceNr = 0L;
var tag = req.Tag;
var toOffset = req.ToOffset;
var fromOffset = req.FromOffset;
var take = Math.Min(toOffset - fromOffset, req.Max);
command.CommandText = ByTagSql;
command.Parameters.Clear();
AddParameter(command, "@Tag", DbType.String, "%;" + tag + ";%");
AddParameter(command, "@Ordering", DbType.Int64, fromOffset);
AddParameter(command, "@Take", DbType.Int64, take);
using (var reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
var persistent = ReadEvent(reader);
var ordering = reader.GetInt64(OrderingIndex);
maxSequenceNr = Math.Max(maxSequenceNr, persistent.SequenceNr);
foreach (var adapted in AdaptFromJournal(persistent))
{
replyTo.Tell(new ReplayedTaggedMessage(adapted, tag, ordering), ActorRefs.NoSender);
}
}
}
replyTo.Tell(new RecoverySuccess(maxSequenceNr));
}
catch (Exception cause)
{
replyTo.Tell(new ReplayMessagesFailure(cause));
}
}
protected virtual async Task HandleReplayMessages(ReplayMessages req, TCommand command, IActorContext context)
{
var replaySettings = Setup.ReplayFilterSettings;
var replyTo = replaySettings.IsEnabled
? context.ActorOf(ReplayFilter.Props(
persistentActor: req.PersistentActor,
mode: replaySettings.Mode,
windowSize: replaySettings.WindowSize,