-
Notifications
You must be signed in to change notification settings - Fork 14
/
OrderProviderReplicaGrain.cs
198 lines (156 loc) · 5.56 KB
/
OrderProviderReplicaGrain.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
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Orleans.Concurrency;
using Outcompute.Trader.Data;
namespace Outcompute.Trader.Trading.Providers.Orders;
[Reentrant]
[StatelessWorker(1)]
internal class OrderProviderReplicaGrain : Grain, IOrderProviderReplicaGrain
{
private readonly ReactiveOptions _reactive;
private readonly IGrainFactory _factory;
private readonly IHostApplicationLifetime _lifetime;
private readonly ITradingRepository _repository;
public OrderProviderReplicaGrain(IOptions<ReactiveOptions> reactive, IGrainFactory factory, IHostApplicationLifetime lifetime, ITradingRepository repository)
{
_reactive = reactive.Value;
_factory = factory;
_lifetime = lifetime;
_repository = repository;
}
/// <summary>
/// The symbol that this grain holds orders for.
/// </summary>
private string _symbol = null!;
/// <summary>
/// The serial version of this grain.
/// Helps detect serial resets from the source grain.
/// </summary>
private Guid _version;
/// <summary>
/// The last known change serial.
/// </summary>
private int _serial;
/// <summary>
/// Holds the order cache in a form that is mutable but still convertible to immutable upon request with low overhead.
/// </summary>
private readonly ImmutableSortedSet<OrderQueryResult>.Builder _orders = ImmutableSortedSet.CreateBuilder(OrderQueryResult.KeyComparer);
/// <summary>
/// Indexes orders by order id to speed up requests for a single order.
/// </summary>
private readonly Dictionary<long, OrderQueryResult> _orderByOrderId = new();
public override async Task OnActivateAsync()
{
_symbol = this.GetPrimaryKeyString();
await LoadAsync();
RegisterTimer(_ => PollAsync(), null, _reactive.ReactiveRecoveryDelay, _reactive.ReactiveRecoveryDelay);
await base.OnActivateAsync();
}
public ValueTask<OrderQueryResult?> TryGetOrderAsync(long orderId)
{
var order = _orderByOrderId.TryGetValue(orderId, out var current) ? current : null;
return ValueTask.FromResult(order);
}
public ValueTask<ImmutableSortedSet<OrderQueryResult>> GetOrdersAsync()
{
return ValueTask.FromResult(_orders.ToImmutable());
}
// todo: optimize this with specific filters for each used combination
public ValueTask<ImmutableSortedSet<OrderQueryResult>> GetOrdersByFilterAsync(OrderSide? side, bool? transient, bool? significant)
{
var query = _orders.AsEnumerable();
if (side.HasValue)
{
query = query.Where(x => x.Side == side.Value);
}
if (transient.HasValue)
{
query = query.Where(x => x.Status.IsTransientStatus() == transient.Value);
}
if (significant.HasValue)
{
query = query.Where(x => (x.ExecutedQuantity > 0) == significant.Value);
}
var result = query.ToImmutableSortedSet(OrderQueryResult.KeyComparer);
return ValueTask.FromResult(result);
}
public async Task SetOrderAsync(OrderQueryResult item)
{
Guard.IsNotNull(item, nameof(item));
await _repository.SetOrderAsync(item, _lifetime.ApplicationStopping);
await _factory.GetOrderProviderGrain(_symbol).SetOrderAsync(item);
Apply(item);
}
public async Task SetOrdersAsync(IEnumerable<OrderQueryResult> items)
{
Guard.IsNotNull(items, nameof(items));
await _repository.SetOrdersAsync(items, _lifetime.ApplicationStopping);
await _factory.GetOrderProviderGrain(_symbol).SetOrdersAsync(items);
foreach (var item in items)
{
Apply(item);
}
}
private async Task LoadAsync()
{
var result = await _factory.GetOrderProviderGrain(_symbol).GetOrdersAsync();
_version = result.Version;
_serial = result.Serial;
foreach (var item in result.Items)
{
Apply(item);
}
}
private void Apply(OrderQueryResult item)
{
// validate
Guard.IsEqualTo(item.Symbol, _symbol, nameof(item.Symbol));
// remove old item to allow an update
Remove(item);
// add new or updated item
_orders.Add(item);
// index the item
Index(item);
}
private void Remove(OrderQueryResult item)
{
if (_orders.Remove(item) && !Unindex(item))
{
throw new InvalidOperationException($"Failed to unindex order ('{item.Symbol}','{item.OrderId}')");
}
}
private void Index(OrderQueryResult item)
{
_orderByOrderId[item.OrderId] = item;
}
private bool Unindex(OrderQueryResult item)
{
return _orderByOrderId.Remove(item.OrderId);
}
private async Task PollAsync()
{
while (!_lifetime.ApplicationStopping.IsCancellationRequested)
{
try
{
var result = await _factory
.GetOrderProviderGrain(_symbol)
.TryWaitForOrdersAsync(_version, _serial + 1);
if (result.HasValue)
{
_version = result.Value.Version;
_serial = result.Value.Serial;
foreach (var item in result.Value.Items)
{
Apply(item);
}
}
}
catch (OperationCanceledException)
{
// throw on target shutdown
return;
}
}
}
}