-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathRestClient.cs
More file actions
211 lines (183 loc) · 8.01 KB
/
RestClient.cs
File metadata and controls
211 lines (183 loc) · 8.01 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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Serialization;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.Azure.SignalR.Common;
using Microsoft.Extensions.Primitives;
#nullable enable
namespace Microsoft.Azure.SignalR;
internal class RestClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IPayloadContentBuilder _payloadContentBuilder;
private static readonly ObjectSerializer DefaultObjectSerializer = new JsonObjectSerializer();
public RestClient(IHttpClientFactory httpClientFactory, IPayloadContentBuilder contentBuilder)
{
_httpClientFactory = httpClientFactory;
_payloadContentBuilder = contentBuilder;
}
// TODO: Test only, will remove later
internal RestClient(IHttpClientFactory httpClientFactory) : this(httpClientFactory, new JsonPayloadContentBuilder(new JsonObjectSerializer()))
{
}
public Task SendAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
CancellationToken cancellationToken = default) =>
SendAsync(api, httpMethod, (Func<HttpResponseMessage, Task<bool>>?)null, cancellationToken);
public Task SendAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
Func<HttpResponseMessage, bool>? handleExpectedResponse,
CancellationToken cancellationToken = default) =>
SendAsync(api, httpMethod, AsAsync(handleExpectedResponse), cancellationToken);
public Task SendAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
Func<HttpResponseMessage, Task<bool>>? handleExpectedResponseAsync,
CancellationToken cancellationToken = default)
{
return SendAsyncCore(Constants.HttpClientNames.UserDefault, api, httpMethod, null, null, handleExpectedResponseAsync, cancellationToken);
}
public Task SendWithRetryAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
Func<HttpResponseMessage, bool>? handleExpectedResponse = null,
CancellationToken cancellationToken = default)
{
return SendWithRetryAsync(api, httpMethod, AsAsync(handleExpectedResponse), cancellationToken);
}
public Task SendWithRetryAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
Func<HttpResponseMessage, Task<bool>>? handleExpectedResponseAsync = null,
CancellationToken cancellationToken = default)
{
return SendAsyncCore(Constants.HttpClientNames.Resilient, api, httpMethod, null, null, handleExpectedResponseAsync, cancellationToken);
}
public Task SendMessageWithRetryAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
string methodName,
object?[] args,
Func<HttpResponseMessage, Task<bool>>? handleExpectedResponse = null,
CancellationToken cancellationToken = default)
{
return SendAsyncCore(Constants.HttpClientNames.MessageResilient, api, httpMethod, new InvocationMessage(methodName, args), null, handleExpectedResponse, cancellationToken);
}
public Task SendStreamMessageWithRetryAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
string streamId,
object? arg = null,
Type? typeHint = null,
Func<HttpResponseMessage, bool>? handleExpectedResponse = null,
CancellationToken cancellationToken = default)
{
return SendAsyncCore(Constants.HttpClientNames.MessageResilient, api, httpMethod, new StreamItemMessage(streamId, arg), typeHint, AsAsync(handleExpectedResponse), cancellationToken);
}
public ObjectSerializer ObjectSerializer => _payloadContentBuilder.ObjectSerializer ?? DefaultObjectSerializer;
private static Uri GetUri(string url, IDictionary<string, StringValues>? query)
{
if (query == null || query.Count == 0)
{
return new Uri(url);
}
var builder = new UriBuilder(url);
var sb = new StringBuilder(builder.Query);
if (sb.Length == 1 && sb[0] == '?')
{
sb.Clear();
}
else if (sb.Length > 0 && sb[0] != '?')
{
sb.Insert(0, '?');
}
foreach (var item in query)
{
foreach (var value in item.Value)
{
sb.Append(sb.Length > 0 ? '&' : '?');
sb.Append(Uri.EscapeDataString(item.Key));
sb.Append('=');
sb.Append(Uri.EscapeDataString(value!));
}
}
builder.Query = sb.ToString();
return builder.Uri;
}
private static async Task ThrowExceptionOnResponseFailureAsync(HttpRequestMessage request, HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
return;
}
var detail = await response.Content.ReadAsStringAsync();
#if NET5_0_OR_GREATER
var innerException = new HttpRequestException(
$"Response status code does not indicate success: {(int)response.StatusCode} ({response.ReasonPhrase})", null, response.StatusCode);
#else
var innerException = new HttpRequestException(
$"Response status code does not indicate success: {(int)response.StatusCode} ({response.ReasonPhrase})");
#endif
var requestUri = request.RequestUri?.ToString();
var jwtToken = request.Headers.Authorization?.Parameter ?? null;
throw response.StatusCode switch
{
HttpStatusCode.BadRequest => new AzureSignalRInvalidArgumentException(requestUri, innerException, detail),
HttpStatusCode.Unauthorized => new AzureSignalRUnauthorizedException(requestUri, innerException, jwtToken),
HttpStatusCode.NotFound => new AzureSignalRInaccessibleEndpointException(requestUri, innerException),
_ => new AzureSignalRRuntimeException(response.RequestMessage?.RequestUri?.ToString(), innerException, response.StatusCode, detail),
};
}
private async Task SendAsyncCore(
string httpClientName,
RestApiEndpoint api,
HttpMethod httpMethod,
HubMessage? body,
Type? typeHint,
Func<HttpResponseMessage, Task<bool>>? handleExpectedResponseAsync = null,
CancellationToken cancellationToken = default)
{
using var httpClient = _httpClientFactory.CreateClient(httpClientName);
using var request = BuildRequest(api, httpMethod, body, typeHint);
try
{
using var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
if (handleExpectedResponseAsync == null)
{
await ThrowExceptionOnResponseFailureAsync(request, response);
}
else
{
if (!await handleExpectedResponseAsync(response))
{
await ThrowExceptionOnResponseFailureAsync(request, response);
}
}
}
catch (HttpRequestException ex)
{
throw new AzureSignalRException($"An error happened when making request to {request.RequestUri}", ex);
}
}
private HttpRequestMessage BuildRequest(RestApiEndpoint api, HttpMethod httpMethod, HubMessage? body, Type? typeHint)
{
return GenerateHttpRequest(api.Audience, api.Query, httpMethod, body, typeHint);
}
private HttpRequestMessage GenerateHttpRequest(string url, IDictionary<string, StringValues>? query, HttpMethod httpMethod, HubMessage? body, Type? typeHint)
{
var request = new HttpRequestMessage(httpMethod, GetUri(url, query));
request.Content = _payloadContentBuilder.Build(body, typeHint);
return request;
}
private static Func<HttpResponseMessage, Task<bool>>? AsAsync(Func<HttpResponseMessage, bool>? syncFunc) =>
syncFunc == null ? null : (response => Task.FromResult(syncFunc(response)));
}