-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathRestApiSource.cs
517 lines (466 loc) · 22.5 KB
/
RestApiSource.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
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Event;
using Akka.Streams;
using Akka.Streams.Stage;
using Akka.Util;
using Akka.Util.Extensions;
using Arcane.Framework.Contracts;
using Arcane.Framework.Sinks.Parquet;
using Arcane.Framework.Sources.Base;
using Arcane.Framework.Sources.Extensions;
using Arcane.Framework.Sources.RestApi.Extensions;
using Arcane.Framework.Sources.RestApi.Services.AuthenticatedMessageProviders;
using Arcane.Framework.Sources.RestApi.Services.AuthenticatedMessageProviders.Base;
using Arcane.Framework.Sources.RestApi.Services.UriProviders;
using Arcane.Framework.Sources.RestApi.Services.UriProviders.Base;
using Microsoft.OpenApi.Models;
using Parquet.Data;
using Polly.RateLimit;
using Snd.Sdk.Tasks;
namespace Arcane.Framework.Sources.RestApi;
/// <summary>
/// Source for reading data from a REST API.
/// </summary>
public class RestApiSource : GraphStage<SourceShape<JsonElement>>, IParquetSource, ITaggedSource
{
private readonly IRestApiAuthenticatedMessageProvider authenticatedMessageProvider;
private readonly OpenApiSchema apiSchema;
private readonly TimeSpan changeCaptureInterval;
private readonly bool isBackfilling;
private readonly HttpClient httpClient;
private readonly TimeSpan httpRequestTimeout;
private readonly TimeSpan lookBackInterval;
private readonly AsyncRateLimitPolicy rateLimitPolicy;
private readonly string[] responsePropertyKeyChain;
private readonly bool stopAfterBackfill;
private readonly IRestApiUriProvider uriProvider;
private RestApiSource(
IRestApiUriProvider uriProvider,
IRestApiAuthenticatedMessageProvider authenticatedMessageProvider,
bool isBackfilling,
TimeSpan changeCaptureInterval,
TimeSpan lookBackInterval,
bool stopAfterBackfill,
AsyncRateLimitPolicy rateLimitPolicy,
OpenApiSchema apiSchema,
string[] responsePropertyKeyChain = null)
{
this.uriProvider = uriProvider;
this.stopAfterBackfill = stopAfterBackfill;
this.changeCaptureInterval = changeCaptureInterval;
this.isBackfilling = isBackfilling;
this.authenticatedMessageProvider = authenticatedMessageProvider;
this.lookBackInterval = lookBackInterval;
this.rateLimitPolicy = rateLimitPolicy;
this.responsePropertyKeyChain = responsePropertyKeyChain;
this.apiSchema = apiSchema;
this.Shape = new SourceShape<JsonElement>(this.Out);
}
private RestApiSource(
IRestApiUriProvider uriProvider,
IRestApiAuthenticatedMessageProvider authenticatedMessageProvider,
bool isBackfilling,
TimeSpan changeCaptureInterval,
TimeSpan lookBackInterval,
TimeSpan httpRequestTimeout,
bool stopAfterBackfill,
AsyncRateLimitPolicy rateLimitPolicy,
OpenApiSchema apiSchema,
string[] responsePropertyKeyChain = null) : this(uriProvider, authenticatedMessageProvider, isBackfilling,
changeCaptureInterval, lookBackInterval, stopAfterBackfill, rateLimitPolicy, apiSchema,
responsePropertyKeyChain)
{
this.httpRequestTimeout = httpRequestTimeout;
}
/// <summary>
/// Only use this constructor for unit tests to mock http calls.
/// </summary>
/// <param name="uriProvider">URI provider</param>
/// <param name="authenticatedMessageProvider">Authenticated message provider</param>
/// <param name="changeCaptureInterval">How often to track changes.</param>
/// <param name="lookBackInterval">Look back interval</param>
/// <param name="httpClient">Http client for making requests</param>
/// <param name="apiSchema">Api Schema</param>
/// <param name="responsePropertyKeyChain">Response property key chain</param>
/// <param name="rateLimitPolicy">Rate limiting policy instance</param>
/// <param name="isBackfilling">Set to true to stream full current version of the table first.</param>
/// <param name="stopAfterBackfill">Set to true if stream should stop after full load is finished</param>
private RestApiSource(
IRestApiUriProvider uriProvider,
IRestApiAuthenticatedMessageProvider authenticatedMessageProvider,
bool isBackfilling,
TimeSpan changeCaptureInterval,
TimeSpan lookBackInterval,
HttpClient httpClient,
bool stopAfterBackfill,
AsyncRateLimitPolicy rateLimitPolicy,
OpenApiSchema apiSchema,
string[] responsePropertyKeyChain = null) : this(uriProvider, authenticatedMessageProvider, isBackfilling,
changeCaptureInterval, lookBackInterval, stopAfterBackfill, rateLimitPolicy, apiSchema,
responsePropertyKeyChain)
{
this.httpClient = httpClient;
}
/// <inheritdoc cref="GraphStageWithMaterializedValue{TShape,TMaterialized}.InitialAttributes"/>
protected override Attributes InitialAttributes { get; } = Attributes.CreateName(nameof(RestApiSource));
/// <summary>
/// Source outlet
/// </summary>
public Outlet<JsonElement> Out { get; } = new($"{nameof(RestApiSource)}.Out");
/// <inheritdoc cref="GraphStageWithMaterializedValue{TShape,TMaterialized}.Shape"/>
public override SourceShape<JsonElement> Shape { get; }
/// <inheritdoc cref="IParquetSource.GetParquetSchema"/>
public Schema GetParquetSchema() => this.apiSchema.ToParquetSchema();
/// <inheritdoc cref="ITaggedSource.GetDefaultTags"/>
public SourceTags GetDefaultTags()
{
return new SourceTags
{
SourceEntity = this.uriProvider.BaseUri.AbsolutePath,
SourceLocation = this.uriProvider.BaseUri.Host,
};
}
/// <summary>
/// Creates new instance of <see cref="RestApiSource"/>
/// </summary>
/// <param name="uriProvider">URI provider</param>
/// <param name="changeCaptureInterval">How often to track changes.</param>
/// <param name="lookBackInterval">Look back interval</param>
/// <param name="httpRequestTimeout">Http request rimeout</param>
/// <param name="apiSchema">Api Schema</param>
/// <param name="rateLimitPolicy">Rate limiting policy instance</param>
/// <param name="isBackfilling">Set to true to stream full current version of the table first.</param>
/// <param name="stopAfterBackfill">Set to true if stream should stop after full load is finished</param>
/// <param name="headerAuthenticatedMessageProvider">Authenticated message provider</param>
/// <param name="responsePropertyKeyChain">Response property key chain</param>
[ExcludeFromCodeCoverage(Justification = "Factory method")]
public static RestApiSource Create(
SimpleUriProvider uriProvider,
FixedHeaderAuthenticatedMessageProvider headerAuthenticatedMessageProvider,
bool isBackfilling,
TimeSpan changeCaptureInterval,
TimeSpan lookBackInterval,
TimeSpan httpRequestTimeout,
bool stopAfterBackfill,
AsyncRateLimitPolicy rateLimitPolicy,
OpenApiSchema apiSchema,
string[] responsePropertyKeyChain = null)
{
return new RestApiSource(uriProvider, headerAuthenticatedMessageProvider, isBackfilling,
changeCaptureInterval,
lookBackInterval, httpRequestTimeout, stopAfterBackfill, rateLimitPolicy, apiSchema,
responsePropertyKeyChain);
}
/// <summary>
/// Creates new instance of <see cref="RestApiSource"/>
/// </summary>
/// <param name="uriProvider">URI provider</param>
/// <param name="changeCaptureInterval">How often to track changes.</param>
/// <param name="lookBackInterval">Look back interval</param>
/// <param name="httpRequestTimeout">Http request rimeout</param>
/// <param name="apiSchema">Api Schema</param>
/// <param name="rateLimitPolicy">Rate limiting policy instance</param>
/// <param name="isBackfilling">Set to true to stream full current version of the table first.</param>
/// <param name="stopAfterBackfill">Set to true if stream should stop after full load is finished</param>
/// <param name="headerAuthenticatedMessageProvider">Authenticated message provider</param>
/// <param name="responsePropertyKeyChain">Response property key chain</param>
[ExcludeFromCodeCoverage(Justification = "Factory method")]
public static RestApiSource Create(
SimpleUriProvider uriProvider,
DynamicBearerAuthenticatedMessageProvider headerAuthenticatedMessageProvider,
bool isBackfilling,
TimeSpan changeCaptureInterval,
TimeSpan lookBackInterval,
TimeSpan httpRequestTimeout,
bool stopAfterBackfill,
AsyncRateLimitPolicy rateLimitPolicy,
OpenApiSchema apiSchema,
string[] responsePropertyKeyChain = null)
{
return new RestApiSource(uriProvider, headerAuthenticatedMessageProvider, isBackfilling,
changeCaptureInterval,
lookBackInterval, httpRequestTimeout, stopAfterBackfill, rateLimitPolicy, apiSchema,
responsePropertyKeyChain);
}
/// <summary>
/// Creates new instance of <see cref="RestApiSource"/>
/// </summary>
/// <param name="uriProvider">URI provider</param>
/// <param name="changeCaptureInterval">How often to track changes.</param>
/// <param name="lookBackInterval">Look back interval</param>
/// <param name="httpClient">Http Client</param>
/// <param name="apiSchema">Api Schema</param>
/// <param name="rateLimitPolicy">Rate limiting policy instance</param>
/// <param name="isBackfilling">Set to true to stream full current version of the table first.</param>
/// <param name="stopAfterBackfill">Set to true if stream should stop after full load is finished</param>
/// <param name="headerAuthenticatedMessageProvider">Authenticated message provider</param>
[ExcludeFromCodeCoverage(Justification = "Factory method")]
public static RestApiSource Create(
SimpleUriProvider uriProvider,
FixedHeaderAuthenticatedMessageProvider headerAuthenticatedMessageProvider,
bool isBackfilling,
TimeSpan changeCaptureInterval,
TimeSpan lookBackInterval,
HttpClient httpClient,
bool stopAfterBackfill,
AsyncRateLimitPolicy rateLimitPolicy,
OpenApiSchema apiSchema)
{
return new RestApiSource(uriProvider, headerAuthenticatedMessageProvider, isBackfilling,
changeCaptureInterval,
lookBackInterval, httpClient, stopAfterBackfill, rateLimitPolicy, apiSchema);
}
/// <summary>
/// Creates new instance of <see cref="RestApiSource"/>
/// </summary>
/// <param name="uriProvider">URI provider</param>
/// <param name="changeCaptureInterval">How often to track changes.</param>
/// <param name="lookBackInterval">Look back interval</param>
/// <param name="httpRequestTimeout">Http request timeout</param>
/// <param name="apiSchema">Api Schema</param>
/// <param name="rateLimitPolicy">Rate limiting policy instance</param>
/// <param name="isBackfilling">Set to true to stream full current version of the table first.</param>
/// <param name="stopAfterBackfill">Set to true if stream should stop after full load is finished</param>
/// <param name="authHeaderAuthenticatedMessageProvider">Authenticated message provider</param>
/// <param name="responsePropertyKeyChain">Response property key chain</param>
[ExcludeFromCodeCoverage(Justification = "Factory method")]
public static RestApiSource Create(
IPaginatedApiUriProvider uriProvider,
DynamicBearerAuthenticatedMessageProvider authHeaderAuthenticatedMessageProvider,
bool isBackfilling,
TimeSpan changeCaptureInterval,
TimeSpan lookBackInterval,
TimeSpan httpRequestTimeout,
bool stopAfterBackfill,
AsyncRateLimitPolicy rateLimitPolicy,
OpenApiSchema apiSchema,
string[] responsePropertyKeyChain = null)
{
return new RestApiSource(uriProvider, authHeaderAuthenticatedMessageProvider, isBackfilling,
changeCaptureInterval,
lookBackInterval, httpRequestTimeout, stopAfterBackfill, rateLimitPolicy, apiSchema,
responsePropertyKeyChain);
}
/// <summary>
/// Creates new instance of <see cref="RestApiSource"/>
/// </summary>
/// <param name="uriProvider">URI provider</param>
/// <param name="changeCaptureInterval">How often to track changes.</param>
/// <param name="lookBackInterval">Look back interval</param>
/// <param name="httpRequestTimeout">Http request timeout</param>
/// <param name="apiSchema">Api Schema</param>
/// <param name="rateLimitPolicy">Rate limiting policy instance</param>
/// <param name="isBackfilling">Set to true to stream full current version of the table first.</param>
/// <param name="stopAfterBackfill">Set to true if stream should stop after full load is finished</param>
/// <param name="headerAuthenticatedMessageProvider">Authenticated message provider</param>
/// <param name="responsePropertyKeyChain">Response property key chain</param>
[ExcludeFromCodeCoverage(Justification = "Factory method")]
public static RestApiSource Create(
IPaginatedApiUriProvider uriProvider,
FixedHeaderAuthenticatedMessageProvider headerAuthenticatedMessageProvider,
bool isBackfilling,
TimeSpan changeCaptureInterval,
TimeSpan lookBackInterval,
TimeSpan httpRequestTimeout,
bool stopAfterBackfill,
AsyncRateLimitPolicy rateLimitPolicy,
OpenApiSchema apiSchema,
string[] responsePropertyKeyChain = null)
{
return new RestApiSource(uriProvider, headerAuthenticatedMessageProvider, isBackfilling,
changeCaptureInterval,
lookBackInterval, httpRequestTimeout, stopAfterBackfill, rateLimitPolicy, apiSchema,
responsePropertyKeyChain);
}
/// <summary>
/// Creates new instance of <see cref="RestApiSource"/>
/// </summary>
/// <param name="uriProvider">URI provider</param>
/// <param name="changeCaptureInterval">How often to track changes.</param>
/// <param name="lookBackInterval">Look back interval</param>
/// <param name="httpClient">Http request timeout</param>
/// <param name="apiSchema">Api Schema</param>
/// <param name="rateLimitPolicy">Rate limiting policy instance</param>
/// <param name="isBackfilling">Set to true to stream full current version of the table first.</param>
/// <param name="stopAfterBackfill">Set to true if stream should stop after full load is finished</param>
/// <param name="authHeaderAuthenticatedMessageProvider">Authenticated message provider</param>
/// <param name="responsePropertyKeyChain">Response property key chain</param>
[ExcludeFromCodeCoverage(Justification = "Factory method")]
public static RestApiSource Create(
IPaginatedApiUriProvider uriProvider,
DynamicBearerAuthenticatedMessageProvider authHeaderAuthenticatedMessageProvider,
bool isBackfilling,
TimeSpan changeCaptureInterval,
TimeSpan lookBackInterval,
HttpClient httpClient,
bool stopAfterBackfill,
AsyncRateLimitPolicy rateLimitPolicy,
OpenApiSchema apiSchema,
string[] responsePropertyKeyChain = null)
{
return new RestApiSource(uriProvider, authHeaderAuthenticatedMessageProvider, isBackfilling,
changeCaptureInterval,
lookBackInterval, httpClient, stopAfterBackfill, rateLimitPolicy, apiSchema,
responsePropertyKeyChain);
}
/// <inheritdoc cref="GraphStage{TShape}.CreateLogic"/>
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new SourceLogic(this);
private sealed class SourceLogic : PollingSourceLogic, IStopAfterBackfill
{
private const string TimerKey = nameof(RestApiSource);
private readonly LocalOnlyDecider decider;
private readonly HttpClient httpClient;
private readonly RestApiSource source;
private HttpResponseMessage currentResponse;
private Action<Task<Option<JsonElement>>> responseReceived;
public SourceLogic(RestApiSource source) : base(source.changeCaptureInterval, source.Shape)
{
this.source = source;
this.httpClient = this.source.httpClient ?? new HttpClient
{
Timeout = this.source.httpRequestTimeout
};
this.decider = Decider.From(ex => ex switch
{
IOException => Directive.Restart,
TimeoutException => Directive.Restart,
HttpRequestException => Directive.Restart,
_ => Directive.Stop
});
this.SetHandler(source.Out, this.PullChanges, this.Finish);
}
/// <inheritdoc cref="IStopAfterBackfill.IsRunningInBackfillMode"/>
public bool IsRunningInBackfillMode { get; set; }
/// <inheritdoc cref="IStopAfterBackfill.StopAfterBackfill"/>
public bool StopAfterBackfill => this.source.stopAfterBackfill;
private void Finish(Exception cause)
{
if (cause is not null && cause is not SubscriptionWithCancelException.NonFailureCancellation)
{
this.FailStage(cause);
}
this.httpClient.Dispose();
}
public override void PreStart()
{
base.PreStart();
this.responseReceived = this.GetAsyncCallback<Task<Option<JsonElement>>>(this.OnRecordReceived);
if (this.source.isBackfilling)
{
this.IsRunningInBackfillMode = true;
}
}
protected override void OnTimer(object timerKey)
{
this.PullChanges();
}
private void OnRecordReceived(Task<Option<JsonElement>> readTask)
{
if (readTask.IsFaulted || readTask.IsCanceled)
{
switch (this.decider.Decide(readTask.Exception))
{
case Directive.Stop:
this.Finish(readTask.Exception);
break;
default:
this.ScheduleOnce(TimerKey, TimeSpan.FromSeconds(1));
break;
}
return;
}
var taskResult = readTask.Result
.GetOrElse(JsonSerializer.Deserialize<JsonElement>(
(this.source.responsePropertyKeyChain ?? Array.Empty<string>()).Any() ? "{}" : "[]"))
.ParseResponse(this.source.responsePropertyKeyChain).ToList();
// Current batch has ended, start a new one
if (!taskResult.Any())
{
if (((this.source.uriProvider as IPaginatedApiUriProvider)?.HasReadAllPages())
.GetValueOrDefault(true) &&
this.CompleteStageAfterFullLoad(this.Finish))
{
this.Log.Info("No data returned by latest call and all pages have been downloaded");
return;
}
this.Log.Info(
$"No data returned by latest call, next check in {this.ChangeCaptureInterval.TotalSeconds} seconds");
this.ScheduleOnce(TimerKey, this.source.changeCaptureInterval);
}
else
{
this.EmitMultiple(this.source.Out, taskResult);
}
}
private void PullChanges() =>
this.source.rateLimitPolicy.ExecuteAsync(this.SendRequestOnce)
.TryMap(result => result, HandleException)
.ContinueWith(this.responseReceived);
private Task<Option<JsonElement>> SendRequestOnce() => this.source
.authenticatedMessageProvider
.GetAuthenticatedMessage(this.httpClient)
.Map(this.SendRequest)
.Flatten();
private Task<Option<JsonElement>> SendRequest(HttpRequestMessage msg)
{
this.Log.Debug("Successfully authenticated");
var (maybeNextUri, requestMethod, maybePayload) = this.source.uriProvider.GetNextResultUri(
this.currentResponse, this.IsRunningInBackfillMode, this.source.lookBackInterval,
this.ChangeCaptureInterval);
if (maybeNextUri.IsEmpty)
{
return Task.FromResult(Option<JsonElement>.None);
}
msg.RequestUri = maybeNextUri.Value;
msg.Method = requestMethod;
if (maybePayload.HasValue)
{
msg.Content = new StringContent(maybePayload.Value);
if (!string.IsNullOrEmpty(maybePayload.Value))
{
this.Log.Info($"Request payload for next result: {maybePayload.Value}");
}
}
this.Log.Info($"Requesting next result from {msg.RequestUri}");
return this.httpClient.SendAsync(msg, default(CancellationToken))
.Map(response =>
{
if (response.IsSuccessStatusCode)
{
this.currentResponse = response;
return response.Content.ReadAsStringAsync().Map(value =>
{
this.Log.Debug($"Got response: {value}");
return JsonSerializer.Deserialize<JsonElement>(value).AsOption();
});
}
var errorMsg =
$"API request to {msg.RequestUri} failed with {response.StatusCode}, reason: {response.ReasonPhrase}, content: {response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult()}";
this.Log.Warning(errorMsg);
throw new HttpRequestException(errorMsg, null, response.StatusCode);
}).Flatten();
}
private static Option<JsonElement> HandleException(Exception exception) => exception switch
{
RateLimitRejectedException => Option<JsonElement>.None, // configured rate limit
HttpRequestException
{
StatusCode: HttpStatusCode.TooManyRequests
} => Option<JsonElement>.None, // API rate limit, in case configured rate limit is not good enough
HttpRequestException
{
StatusCode: HttpStatusCode.RequestTimeout
} => Option<JsonElement>.None, // Potential server-side timeout due to overload
_ => throw exception
};
}
}