-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBeastClient.cs
More file actions
145 lines (126 loc) · 6.03 KB
/
Copy pathBeastClient.cs
File metadata and controls
145 lines (126 loc) · 6.03 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
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SnD.ApiClient.Base;
using SnD.ApiClient.Base.Models;
using SnD.ApiClient.Beast.Base;
using SnD.ApiClient.Beast.Models;
using SnD.ApiClient.Boxer.Base;
using SnD.ApiClient.Config;
using SnD.ApiClient.Exceptions;
namespace SnD.ApiClient.Beast;
public class BeastClient : SndApiClient, IBeastClient
{
private readonly Uri baseUri;
private readonly HashSet<BeastRequestLifeCycleStage> completedStages = new()
{
BeastRequestLifeCycleStage.COMPLETED,
BeastRequestLifeCycleStage.FAILED,
BeastRequestLifeCycleStage.STALE,
BeastRequestLifeCycleStage.SCHEDULING_FAILED,
BeastRequestLifeCycleStage.SUBMISSION_FAILED
};
public BeastClient(IOptions<BeastClientOptions> beastClientOptions, HttpClient httpClient,
IJwtTokenExchangeProvider boxerConnector, ILogger<BeastClient> logger) : base(httpClient, boxerConnector,
logger)
{
baseUri = new Uri(beastClientOptions.Value.BaseUri
?? throw new ArgumentNullException(nameof(BeastClientOptions.BaseUri)));
}
/// <inheritdoc />
public async Task<RequestState> SubmitJobAsync(JobRequest jobParams, string submissionConfigurationName,
CancellationToken cancellationToken = default, ConcurrencyStrategy? concurrencyStrategy= null)
{
cancellationToken.ThrowIfCancellationRequested();
concurrencyStrategy ??= ConcurrencyStrategy.IGNORE;
if (concurrencyStrategy != ConcurrencyStrategy.IGNORE)
{
if (string.IsNullOrEmpty(jobParams.ClientTag))
{
throw new ArgumentException("You must supply a client tag when using a concurrency strategy");
}
var existingJobIds = await GetJobIdsByTagAsync(jobParams.ClientTag, cancellationToken);
var incompleteJobs = (await Task.WhenAll(existingJobIds
.Select(async id => await GetJobStateAsync(id, cancellationToken))))
.Where(state => !completedStages.Contains(state.LifeCycleStage)).ToArray();
if (incompleteJobs.Any())
{
switch (concurrencyStrategy)
{
case ConcurrencyStrategy.SKIP:
throw new ConcurrencyError(concurrencyStrategy.Value, incompleteJobs.First().Id,
jobParams.ClientTag);
case ConcurrencyStrategy.AWAIT:
await Task.WhenAll(incompleteJobs
.Select(job => AwaitRunAsync(job.Id, TimeSpan.FromSeconds(5), cancellationToken)));
break;
case ConcurrencyStrategy.REPLACE:
throw new NotImplementedException("ConcurrencyStrategy.REPLACE not implemented for BEAST");
}
}
}
if(Regex.IsMatch(jobParams.ClientTag ?? "", @"[^\w\d\-\._~]"))
{
throw new ArgumentException("ClientTag can only contain alphanumeric characters, hyphens, periods, underscores, and tildes");
}
var requestUri = new Uri(baseUri, new Uri($"job/submit/{submissionConfigurationName}", UriKind.Relative));
var request = new HttpRequestMessage(HttpMethod.Post, requestUri)
{
Content = new StringContent(JsonSerializer.Serialize(jobParams), Encoding.UTF8, "application/json")
};
var response = await SendAuthenticatedRequestAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
return JsonSerializer.Deserialize<RequestState>(
await response.Content.ReadAsStringAsync(cancellationToken),
JsonSerializerOptions);
}
/// <inheritdoc />
public async Task<RequestState> AwaitRunAsync(string requestId, TimeSpan pollInterval,
CancellationToken cancellationToken)
{
RequestState result = null;
if (cancellationToken == CancellationToken.None)
{
throw new ArgumentException("Cancellation token None is not allowed.");
}
cancellationToken.ThrowIfCancellationRequested();
do
{
await Task.Delay(pollInterval, cancellationToken);
result = await GetRequestState(requestId, cancellationToken);
if (completedStages.Contains(result.LifeCycleStage))
{
return result;
}
} while (!cancellationToken.IsCancellationRequested);
return result;
}
/// <inheritdoc />
public Task<RequestState> GetJobStateAsync(string requestId, CancellationToken cancellationToken = default)
{
return GetRequestState(requestId, cancellationToken);
}
private async Task<string[]> GetJobIdsByTagAsync(string clientTag, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var requestUri = new Uri(baseUri, new Uri($"job/requests/tags/{clientTag}", UriKind.Relative));
var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
var response = await SendAuthenticatedRequestAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
return JsonSerializer.Deserialize<string[]>(await response.Content.ReadAsStringAsync(cancellationToken),
JsonSerializerOptions);
}
private async Task<RequestState> GetRequestState(string requestId, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var requestUri = new Uri(baseUri, new Uri($"job/requests/{requestId}", UriKind.Relative));
var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
var response = await SendAuthenticatedRequestAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
return JsonSerializer.Deserialize<RequestState>(
await response.Content.ReadAsStringAsync(cancellationToken),
JsonSerializerOptions);
}
}