-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathExternalIntegrationRequestsDataStore.cs
More file actions
211 lines (176 loc) · 7.07 KB
/
ExternalIntegrationRequestsDataStore.cs
File metadata and controls
211 lines (176 loc) · 7.07 KB
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
namespace ServiceControl.Persistence.RavenDB
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using ExternalIntegrations;
using Microsoft.Extensions.Hosting;
using NServiceBus;
using NServiceBus.Logging;
using Raven.Client.Documents;
using Raven.Client.Documents.Changes;
using ServiceControl.Infrastructure;
class ExternalIntegrationRequestsDataStore
: IExternalIntegrationRequestsDataStore
, IHostedService
, IAsyncDisposable
{
public ExternalIntegrationRequestsDataStore(RavenPersisterSettings settings, IRavenSessionProvider sessionProvider, IRavenDocumentStoreProvider documentStoreProvider, CriticalError criticalError)
{
this.settings = settings;
this.sessionProvider = sessionProvider;
this.documentStoreProvider = documentStoreProvider;
var timeToWait = TimeSpan.FromMinutes(5);
var delayAfterFailure = TimeSpan.FromSeconds(20);
circuitBreaker = new RepeatedFailuresOverTimeCircuitBreaker(
"EventDispatcher",
timeToWait,
ex => criticalError.Raise("Repeated failures when dispatching external integration events.", ex),
timeToWaitWhenArmed: delayAfterFailure
);
}
const string KeyPrefix = "ExternalIntegrationDispatchRequests";
public async Task StoreDispatchRequest(IEnumerable<ExternalIntegrationDispatchRequest> dispatchRequests)
{
using var session = await sessionProvider.OpenSession();
foreach (var dispatchRequest in dispatchRequests)
{
if (dispatchRequest.Id != null)
{
throw new ArgumentException("Items cannot have their Id property set");
}
dispatchRequest.Id = KeyPrefix + "/" + Guid.NewGuid();
await session.StoreAsync(dispatchRequest);
}
await session.SaveChangesAsync();
}
public void Subscribe(Func<object[], Task> callback)
{
if (this.callback != null)
{
throw new InvalidOperationException("Subscription already exists.");
}
this.callback = callback ?? throw new ArgumentNullException(nameof(callback));
StartDispatcher();
}
void StartDispatcher() => task = StartDispatcherTask(tokenSource.Token);
async Task StartDispatcherTask(CancellationToken cancellationToken)
{
try
{
await DispatchEvents(cancellationToken);
do
{
try
{
await signal.WaitHandle.WaitOneAsync(cancellationToken);
signal.Reset();
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
break;
}
await DispatchEvents(cancellationToken);
}
while (!cancellationToken.IsCancellationRequested);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// ignore
}
catch (Exception ex)
{
Logger.Error("An exception occurred when dispatching external integration events", ex);
await circuitBreaker.Failure(ex, cancellationToken);
if (!tokenSource.IsCancellationRequested)
{
StartDispatcher();
}
}
}
async Task DispatchEvents(CancellationToken cancellationToken)
{
bool more;
do
{
more = await TryDispatchEventBatch();
circuitBreaker.Success();
if (more && !cancellationToken.IsCancellationRequested)
{
//if there is more events to dispatch we sleep for a bit and then we go again
await Task.Delay(1000, CancellationToken.None);
}
}
while (!cancellationToken.IsCancellationRequested && more);
}
async Task<bool> TryDispatchEventBatch()
{
using var session = await sessionProvider.OpenSession();
var awaitingDispatching = await session
.Query<ExternalIntegrationDispatchRequest>()
.Statistics(out var stats)
.Take(settings.ExternalIntegrationsDispatchingBatchSize)
.ToListAsync();
if (awaitingDispatching.Count == 0)
{
// Should ensure we query again if the result is potentially stale
// If ☝️ is not true we will need to use/parse the ChangeVector when document is written and compare to ResultEtag
return stats.IsStale;
}
var allContexts = awaitingDispatching.Select(r => r.DispatchContext).ToArray();
if (Logger.IsDebugEnabled)
{
Logger.Debug($"Dispatching {allContexts.Length} events.");
}
await callback(allContexts);
foreach (var dispatchedEvent in awaitingDispatching)
{
session.Delete(dispatchedEvent);
}
await session.SaveChangesAsync();
return true;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
var documentStore = await documentStoreProvider.GetDocumentStore(cancellationToken);
subscription = documentStore
.Changes()
.ForDocumentsStartingWith(KeyPrefix)
.Where(c => c.Type == DocumentChangeTypes.Put)
.Subscribe(d =>
{
signal.Set();
});
}
public async Task StopAsync(CancellationToken cancellationToken) => await DisposeAsync();
public async ValueTask DisposeAsync()
{
if (isDisposed)
{
return;
}
isDisposed = true;
subscription?.Dispose();
await tokenSource?.CancelAsync();
if (task != null)
{
await task;
}
tokenSource?.Dispose();
}
readonly RavenPersisterSettings settings;
readonly IRavenSessionProvider sessionProvider;
readonly IRavenDocumentStoreProvider documentStoreProvider;
readonly CancellationTokenSource tokenSource = new();
readonly RepeatedFailuresOverTimeCircuitBreaker circuitBreaker;
IDisposable subscription;
Task task;
ManualResetEventSlim signal = new();
Func<object[], Task> callback;
bool isDisposed;
static ILog Logger = LogManager.GetLogger(typeof(ExternalIntegrationRequestsDataStore));
}
}