-
Notifications
You must be signed in to change notification settings - Fork 33
/
MatchAggregator.cs
277 lines (240 loc) · 10.9 KB
/
MatchAggregator.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
using System;
using System.Linq;
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.CQRS.Events;
using Akka.CQRS.Pricing.Commands;
using Akka.CQRS.Pricing.Events;
using Akka.CQRS.Pricing.Subscriptions;
using Akka.CQRS.Pricing.Subscriptions.DistributedPubSub;
using Akka.CQRS.Pricing.Views;
using Akka.CQRS.Subscriptions;
using Akka.CQRS.Subscriptions.DistributedPubSub;
using Akka.CQRS.Util;
using Akka.Event;
using Akka.Persistence;
using Petabridge.Collections;
namespace Akka.CQRS.Pricing.Actors
{
/// <summary>
/// Used to aggregate <see cref="Akka.CQRS.Events.Match"/> events via Akka.Persistence.Query
/// </summary>
public class MatchAggregator : ReceivePersistentActor
{
// Take a snapshot every 10 journal entries
public const int SnapshotEveryN = 10;
private MatchAggregate _matchAggregate;
private readonly ITimestamper _timestamper;
private readonly ILoggingAdapter _log = Context.GetLogger();
private readonly IMarketEventPublisher _marketEventPublisher;
private readonly IMarketEventSubscriptionManager _marketEventSubscriptionManager;
private readonly ITradeEventSubscriptionManager _tradeSubscriptionManager;
private CircularBuffer<IPriceUpdate> _priceUpdates = new CircularBuffer<IPriceUpdate>(MatchAggregate.DefaultSampleSize);
private CircularBuffer<IVolumeUpdate> _volumeUpdates = new CircularBuffer<IVolumeUpdate>(MatchAggregate.DefaultSampleSize);
private ICancelable _publishPricesTask;
public readonly string TickerSymbol;
public override string PersistenceId { get; }
private class PublishEvents
{
public static readonly PublishEvents Instance = new PublishEvents();
private PublishEvents() { }
}
private class DoSubscribe
{
public static readonly DoSubscribe Instance = new DoSubscribe();
private DoSubscribe() { }
}
public MatchAggregator(string tickerSymbol) : this(tickerSymbol, DistributedPubSubTradeEventSubscriptionManager.For(Context.System),
DistributedPubSubMarketEventSubscriptionManager.For(Context.System), DistributedPubSubMarketEventPublisher.For(Context.System))
{ }
public MatchAggregator(string tickerSymbol, ITradeEventSubscriptionManager tradeSubscriptionManager, IMarketEventSubscriptionManager marketEventSubscriptionManager, IMarketEventPublisher marketEventPublisher, ITimestamper timestamper = null)
{
TickerSymbol = tickerSymbol;
_timestamper = timestamper ?? CurrentUtcTimestamper.Instance;
_tradeSubscriptionManager = tradeSubscriptionManager;
_marketEventSubscriptionManager = marketEventSubscriptionManager;
_marketEventPublisher = marketEventPublisher;
PersistenceId = EntityIdHelper.IdForPricing(tickerSymbol);
Recovers();
Commands();
}
private void Recovers()
{
/*
* Can be saved as a snapshot or as an event
*/
Recover<SnapshotOffer>(o =>
{
if (o.Snapshot is MatchAggregatorSnapshot s)
{
RecoverAggregateData(s);
}
});
Recover<MatchAggregatorSnapshot>(s => { RecoverAggregateData(s); });
}
/// <summary>
/// Recovery has completed successfully.
/// </summary>
protected override void OnReplaySuccess()
{
// setup subscription to TradeEventPublisher
Self.Tell(DoSubscribe.Instance);
base.OnReplaySuccess();
}
private void RecoverAggregateData(MatchAggregatorSnapshot s)
{
_matchAggregate = new MatchAggregate(TickerSymbol, s.RecentAvgPrice, s.RecentAvgVolume);
if(s.RecentPriceUpdates != null && s.RecentPriceUpdates.Count > 0)
_priceUpdates.Enqueue(s.RecentPriceUpdates.ToArray());
if(s.RecentVolumeUpdates != null && s.RecentVolumeUpdates.Count > 0)
_volumeUpdates.Enqueue(s.RecentVolumeUpdates.ToArray());
}
private MatchAggregatorSnapshot SaveAggregateData()
{
return new MatchAggregatorSnapshot(_matchAggregate.AvgPrice.CurrentAvg, _matchAggregate.AvgVolume.CurrentAvg, _priceUpdates.Cast<PriceChanged>().ToList(), _volumeUpdates.Cast<VolumeChanged>().ToList());
}
private void AwaitingSubscription()
{
CommandAsync<DoSubscribe>(async _ =>
{
try
{
var ack = await _tradeSubscriptionManager.Subscribe(TickerSymbol, TradeEventType.Match, Self);
_log.Info("Successfully subscribed to MATCH events for {0}", TickerSymbol);
//Become(Commands);
}
catch (Exception ex)
{
_log.Error(ex, "Error while waiting for SubscribeAck for [{0}-{1}] - retrying in 5s.", TickerSymbol, TradeEventType.Match);
Context.System.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(5), Self, DoSubscribe.Instance, ActorRefs.NoSender);
}
});
}
private void Commands()
{
AwaitingSubscription();
Command<Match>(m => TickerSymbol.Equals(m.StockId), m =>
{
_log.Info("Received MATCH for {0} - price: {1} quantity: {2}", TickerSymbol, m.SettlementPrice, m.Quantity);
if (_matchAggregate == null)
{
_matchAggregate = new MatchAggregate(TickerSymbol, m.SettlementPrice, m.Quantity);
return;
}
if (!_matchAggregate.WithMatch(m))
{
// should never get to here
_log.Warning("Received Match for ticker symbol [{0}] - but we only accept symbols for [{1}]", m.StockId, TickerSymbol);
}
});
// Matches for a different ticker symbol
Command<Match>(m =>
{
_log.Warning("Received Match for ticker symbol [{0}] - but we only accept symbols for [{1}]", m.StockId, TickerSymbol);
});
// Command sent to pull down a complete snapshot of active pricing data for this ticker symbol
Command<FetchPriceAndVolume>(f =>
{
// no price data yet
if (_priceUpdates.Count == 0 || _volumeUpdates.Count == 0)
{
Sender.Tell(PriceAndVolumeSnapshot.Empty(TickerSymbol));
}
else
{
Sender.Tell(new PriceAndVolumeSnapshot(TickerSymbol, _priceUpdates.ToArray(), _volumeUpdates.ToArray()));
}
});
Command<PublishEvents>(p =>
{
if (_matchAggregate == null)
return;
var (latestPrice, latestVolume) = _matchAggregate.FetchMetrics(_timestamper);
// Need to update pricing records prior to persisting our state, since this data is included in
// output of SaveAggregateData()
_priceUpdates.Add(latestPrice);
_volumeUpdates.Add(latestVolume);
PersistAsync(SaveAggregateData(), snapshot =>
{
_log.Info("Saved latest price {0} and volume {1}", snapshot.RecentAvgPrice, snapshot.RecentAvgVolume);
if (LastSequenceNr % SnapshotEveryN == 0)
{
SaveSnapshot(snapshot);
}
});
// publish updates to price and volume subscribers
_marketEventPublisher.Publish(TickerSymbol, latestPrice);
_marketEventPublisher.Publish(TickerSymbol, latestVolume);
});
Command<Ping>(p =>
{
if (_log.IsDebugEnabled)
{
_log.Debug("pinged via {0}", Sender);
}
});
Command<SaveSnapshotSuccess>(s =>
{
// clean-up prior snapshots and journal events
DeleteSnapshots(new SnapshotSelectionCriteria(s.Metadata.SequenceNr-1));
DeleteMessages(s.Metadata.SequenceNr);
});
/*
* Handle subscriptions directly in case we're using in-memory, local pub-sub.
*/
CommandAsync<MarketSubscribe>(async sub =>
{
try
{
var ack = await _marketEventSubscriptionManager.Subscribe(TickerSymbol, sub.Events, sub.Subscriber);
Context.Watch(sub.Subscriber);
sub.Subscriber.Tell(ack);
Sender.Tell(ack); // need this for ASK operations.
}
catch (Exception ex)
{
_log.Error(ex, "Error while processing subscription {0}", sub);
sub.Subscriber.Tell(new MarketSubscribeNack(TickerSymbol, sub.Events, ex.Message));
}
});
CommandAsync<MarketUnsubscribe>(async unsub =>
{
try
{
var ack = await _marketEventSubscriptionManager.Unsubscribe(PersistenceId, unsub.Events, unsub.Subscriber);
// leave DeathWatch intact, in case actor is still subscribed to additional topics
unsub.Subscriber.Tell(ack);
Sender.Tell(ack); // need this for ASK operations.
}
catch (Exception ex)
{
_log.Error(ex, "Error while processing unsubscribe {0}", unsub);
unsub.Subscriber.Tell(new MarketUnsubscribeNack(TickerSymbol, unsub.Events, ex.Message));
}
});
CommandAsync<Terminated>(async t =>
{
try
{
var ack = await _marketEventSubscriptionManager.Unsubscribe(TickerSymbol, t.ActorRef);
}
catch (Exception ex)
{
_log.Error(ex, "Error while processing unsubscribe for terminated subscriber {0} for symbol {1}", t.ActorRef, TickerSymbol);
}
});
}
protected override void PreStart()
{
_publishPricesTask = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(10), Self, PublishEvents.Instance, ActorRefs.NoSender);
_log.Info("Starting...");
base.PreStart();
}
protected override void PostStop()
{
_publishPricesTask?.Cancel();
base.PostStop();
}
}
}