forked from Aaronontheweb/InMemoryCQRSReplication
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOrderBookActor.cs
187 lines (165 loc) · 7.7 KB
/
OrderBookActor.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
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using Akka.CQRS.Commands;
using Akka.CQRS.Events;
using Akka.CQRS.Matching;
using Akka.CQRS.Subscriptions;
using Akka.CQRS.Subscriptions.DistributedPubSub;
using Akka.CQRS.Subscriptions.NoOp;
using Akka.Event;
using Akka.Persistence;
using Akka.Persistence.Extras;
using Akka.Util.Internal;
namespace Akka.CQRS.TradeProcessor.Actors
{
/// <summary>
/// Actor responsible for processing orders for a specific ticker symbol.
/// </summary>
public class OrderBookActor : ReceivePersistentActor
{
public static Props PropsFor(string tickerSymbol)
{
return Props.Create(() => new OrderBookActor(tickerSymbol));
}
/// <summary>
/// Take a snapshot every N messages persisted.
/// </summary>
public const int SnapshotInterval = 100;
private MatchingEngine _matchingEngine;
private readonly ITradeEventPublisher _publisher;
private readonly ITradeEventSubscriptionManager _subscriptionManager;
private readonly IActorRef _confirmationActor;
private readonly ILoggingAdapter _log = Context.GetLogger();
public OrderBookActor(string tickerSymbol) : this(tickerSymbol, null, DistributedPubSubTradeEventPublisher.For(Context.System), NoOpTradeEventSubscriptionManager.Instance, Context.Parent) { }
public OrderBookActor(string tickerSymbol, IActorRef confirmationActor) : this(tickerSymbol, null, DistributedPubSubTradeEventPublisher.For(Context.System), NoOpTradeEventSubscriptionManager.Instance, confirmationActor) { }
public OrderBookActor(string tickerSymbol, MatchingEngine matchingEngine, ITradeEventPublisher publisher, ITradeEventSubscriptionManager subscriptionManager, IActorRef confirmationActor)
{
TickerSymbol = tickerSymbol;
PersistenceId = $"{TickerSymbol}-orderBook";
_matchingEngine = matchingEngine ?? CreateDefaultMatchingEngine(tickerSymbol, _log);
_publisher = publisher;
_confirmationActor = confirmationActor;
_subscriptionManager = subscriptionManager;
Recovers();
Commands();
}
private static MatchingEngine CreateDefaultMatchingEngine(string tickerSymbol, ILoggingAdapter logger)
{
return new MatchingEngine(tickerSymbol, logger);
}
public string TickerSymbol { get; }
public override string PersistenceId { get; }
private void Recovers()
{
Recover<SnapshotOffer>(offer =>
{
if (offer.Snapshot is OrderbookSnapshot orderBook)
{
_matchingEngine = MatchingEngine.FromSnapshot(orderBook, _log);
}
});
Recover<Bid>(b => { _matchingEngine.WithBid(b); });
Recover<Ask>(a => { _matchingEngine.WithAsk(a); });
// Fill and Match can't modify the state of the MatchingEngine.
Recover<Match>(m => { });
Recover<Fill>(f => { });
}
private void Commands()
{
Command<ConfirmableMessage<Ask>>(a =>
{
// For the sake of efficiency - update orderbook and then persist all events
var events = _matchingEngine.WithAsk(a.Message);
var persistableEvents = new ITradeEvent[] { a.Message }.Concat<ITradeEvent>(events); // ask needs to go before Fill / Match
PersistAll(persistableEvents, @event =>
{
_log.Info("[{0}][{1}] - {2} units @ {3} per unit", TickerSymbol, @event.ToTradeEventType(), a.Message.AskQuantity, a.Message.AskPrice);
if (@event is Ask)
{
// need to use the ID of the original sender to satisfy the PersistenceSupervisor
//_confirmationActor.Tell(new Confirmation(a.ConfirmationId, a.SenderId));
}
_publisher.Publish(TickerSymbol, @event);
// Take a snapshot every N messages to optimize recovery time
if (LastSequenceNr % SnapshotInterval == 0)
{
SaveSnapshot(_matchingEngine.GetSnapshot());
}
});
});
Command<ConfirmableMessage<Bid>>(b =>
{
// For the sake of efficiency -update orderbook and then persist all events
var events = _matchingEngine.WithBid(b.Message);
var persistableEvents = new ITradeEvent[] { b.Message }.Concat<ITradeEvent>(events); // bid needs to go before Fill / Match
PersistAll(persistableEvents, @event =>
{
_log.Info("[{0}][{1}] - {2} units @ {3} per unit", TickerSymbol, @event.ToTradeEventType(), b.Message.BidQuantity, b.Message.BidPrice);
if (@event is Bid)
{
//_confirmationActor.Tell(new Confirmation(b.ConfirmationId, PersistenceId));
}
_publisher.Publish(TickerSymbol, @event);
// Take a snapshot every N messages to optimize recovery time
if (LastSequenceNr % SnapshotInterval == 0)
{
SaveSnapshot(_matchingEngine.GetSnapshot());
}
});
});
Command<SaveSnapshotSuccess>(success =>
{
//DeleteMessages(success.Metadata.SequenceNr);
DeleteSnapshots(new SnapshotSelectionCriteria(success.Metadata.SequenceNr));
});
/*
* Handle subscriptions directly in case we're using in-memory, local pub-sub.
*/
CommandAsync<TradeSubscribe>(async sub =>
{
try
{
var ack = await _subscriptionManager.Subscribe(sub.TickerSymbol, sub.Events, sub.Subscriber);
Context.Watch(sub.Subscriber);
sub.Subscriber.Tell(ack);
}
catch (Exception ex)
{
_log.Error(ex, "Error while processing subscription {0}", sub);
sub.Subscriber.Tell(new TradeSubscribeNack(sub.TickerSymbol, sub.Events, ex.Message));
}
});
CommandAsync<TradeUnsubscribe>(async unsub =>
{
try
{
var ack = await _subscriptionManager.Unsubscribe(unsub.TickerSymbol, unsub.Events, unsub.Subscriber);
// leave DeathWatch intact, in case actor is still subscribed to additional topics
unsub.Subscriber.Tell(ack);
}
catch (Exception ex)
{
_log.Error(ex, "Error while processing unsubscribe {0}", unsub);
unsub.Subscriber.Tell(new TradeUnsubscribeNack(unsub.TickerSymbol, unsub.Events, ex.Message));
}
});
CommandAsync<Terminated>(async t =>
{
try
{
var ack = await _subscriptionManager.Unsubscribe(TickerSymbol, t.ActorRef);
}
catch (Exception ex)
{
_log.Error(ex, "Error while processing unsubscribe for terminated subscriber {0} for symbol {1}", t.ActorRef, TickerSymbol);
}
});
Command<GetOrderBookSnapshot>(s =>
{
Sender.Tell(_matchingEngine.GetSnapshot());
});
}
}
}