Skip to content

Commit

Permalink
some code reformat (#2057)
Browse files Browse the repository at this point in the history
  • Loading branch information
terencefan authored Oct 16, 2024
1 parent cbf3a78 commit 5caea7f
Show file tree
Hide file tree
Showing 7 changed files with 560 additions and 568 deletions.
69 changes: 34 additions & 35 deletions src/Microsoft.Azure.SignalR.Common/Auth/AccessKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,42 +7,41 @@
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Azure.SignalR
namespace Microsoft.Azure.SignalR;

internal class AccessKey
{
internal class AccessKey
public string Id => Key?.Item1;

public string Value => Key?.Item2;

public Uri Endpoint { get; }

protected Tuple<string, string> Key { get; set; }

public AccessKey(string uri, string key) : this(new Uri(uri))
{
Key = new Tuple<string, string>(key.GetHashCode().ToString(), key);
}

public AccessKey(Uri uri, string key) : this(uri)
{
Key = new Tuple<string, string>(key.GetHashCode().ToString(), key);
}

protected AccessKey(Uri uri)
{
Endpoint = uri;
}

public virtual Task<string> GenerateAccessTokenAsync(
string audience,
IEnumerable<Claim> claims,
TimeSpan lifetime,
AccessTokenAlgorithm algorithm,
CancellationToken ctoken = default)
{
public string Id => Key?.Item1;

public string Value => Key?.Item2;

public Uri Endpoint { get; }

protected Tuple<string, string> Key { get; set; }

public AccessKey(string uri, string key) : this(new Uri(uri))
{
Key = new Tuple<string, string>(key.GetHashCode().ToString(), key);
}

public AccessKey(Uri uri, string key) : this(uri)
{
Key = new Tuple<string, string>(key.GetHashCode().ToString(), key);
}

protected AccessKey(Uri uri)
{
Endpoint = uri;
}

public virtual Task<string> GenerateAccessTokenAsync(
string audience,
IEnumerable<Claim> claims,
TimeSpan lifetime,
AccessTokenAlgorithm algorithm,
CancellationToken ctoken = default)
{
var token = AuthUtility.GenerateAccessToken(this, audience, claims, lifetime, algorithm);
return Task.FromResult(token);
}
var token = AuthUtility.GenerateAccessToken(this, audience, claims, lifetime, algorithm);
return Task.FromResult(token);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public override async Task<string> GenerateAccessTokenAsync(
{
await task;
return IsAuthorized
? await base.GenerateAccessTokenAsync(audience, claims, lifetime, algorithm)
? await base.GenerateAccessTokenAsync(audience, claims, lifetime, algorithm, ctoken)
: throw new AzureSignalRAccessTokenNotAuthorizedException(TokenCredential.GetType().Name, _lastException);
}
else
Expand Down
263 changes: 130 additions & 133 deletions src/Microsoft.Azure.SignalR.Common/Utilities/RestClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,173 +15,170 @@

#nullable enable

namespace Microsoft.Azure.SignalR
namespace Microsoft.Azure.SignalR;

internal class RestClient
{
internal class RestClient
private readonly IHttpClientFactory _httpClientFactory;

private readonly IPayloadContentBuilder _payloadContentBuilder;

public RestClient(IHttpClientFactory httpClientFactory, IPayloadContentBuilder contentBuilder)
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IPayloadContentBuilder _payloadContentBuilder;
_httpClientFactory = httpClientFactory;
_payloadContentBuilder = contentBuilder;
}

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()))
{
}

// TODO: Test only, will remove later
internal RestClient(IHttpClientFactory httpClientFactory) : this(httpClientFactory, new JsonPayloadContentBuilder(new JsonObjectSerializer()))
{
}
public Task SendAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
string? methodName = null,
object[]? args = null,
Func<HttpResponseMessage, bool>? handleExpectedResponse = null,
CancellationToken cancellationToken = default)
{
return handleExpectedResponse == null
? SendAsync(api, httpMethod, methodName, args, handleExpectedResponseAsync: null, cancellationToken)
: SendAsync(api, httpMethod, methodName, args, response => Task.FromResult(handleExpectedResponse(response)), cancellationToken);
}

public Task SendAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
string? methodName = null,
object[]? args = null,
Func<HttpResponseMessage, bool>? handleExpectedResponse = null,
CancellationToken cancellationToken = default)
{
if (handleExpectedResponse == null)
{
return SendAsync(api, httpMethod, methodName, args, handleExpectedResponseAsync: null, cancellationToken);
}
public Task SendAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
string? methodName = null,
object[]? args = null,
Func<HttpResponseMessage, Task<bool>>? handleExpectedResponseAsync = null,
CancellationToken cancellationToken = default)
{
return SendAsyncCore(Constants.HttpClientNames.UserDefault, api, httpMethod, methodName, args, handleExpectedResponseAsync, cancellationToken);
}

return SendAsync(api, httpMethod, methodName, args, response => Task.FromResult(handleExpectedResponse(response)), cancellationToken);
}
public Task SendWithRetryAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
string? methodName = null,
object[]? args = null,
Func<HttpResponseMessage, bool>? handleExpectedResponse = null,
CancellationToken cancellationToken = default)
{
return SendAsyncCore(Constants.HttpClientNames.Resilient, api, httpMethod, methodName, args, handleExpectedResponse == null ? null : response => Task.FromResult(handleExpectedResponse(response)), cancellationToken);
}

public Task SendAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
string? methodName = null,
object[]? args = null,
Func<HttpResponseMessage, Task<bool>>? handleExpectedResponseAsync = null,
CancellationToken cancellationToken = default)
public Task SendMessageWithRetryAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
string? methodName = null,
object[]? args = null,
Func<HttpResponseMessage, bool>? handleExpectedResponse = null,
CancellationToken cancellationToken = default)
{
return SendAsyncCore(Constants.HttpClientNames.MessageResilient, api, httpMethod, methodName, args, handleExpectedResponse == null ? null : response => Task.FromResult(handleExpectedResponse(response)), cancellationToken);
}

private static Uri GetUri(string url, IDictionary<string, StringValues>? query)
{
if (query == null || query.Count == 0)
{
return SendAsyncCore(Constants.HttpClientNames.UserDefault, api, httpMethod, methodName, args, handleExpectedResponseAsync, cancellationToken);
return new Uri(url);
}

public Task SendWithRetryAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
string? methodName = null,
object[]? args = null,
Func<HttpResponseMessage, bool>? handleExpectedResponse = null,
CancellationToken cancellationToken = default)
var builder = new UriBuilder(url);
var sb = new StringBuilder(builder.Query);
if (sb.Length == 1 && sb[0] == '?')
{
return SendAsyncCore(Constants.HttpClientNames.Resilient, api, httpMethod, methodName, args, handleExpectedResponse == null ? null : response => Task.FromResult(handleExpectedResponse(response)), cancellationToken);
sb.Clear();
}

public Task SendMessageWithRetryAsync(
RestApiEndpoint api,
HttpMethod httpMethod,
string? methodName = null,
object[]? args = null,
Func<HttpResponseMessage, bool>? handleExpectedResponse = null,
CancellationToken cancellationToken = default)
else if (sb.Length > 0 && sb[0] != '?')
{
return SendAsyncCore(Constants.HttpClientNames.MessageResilient, api, httpMethod, methodName, args, handleExpectedResponse == null ? null : response => Task.FromResult(handleExpectedResponse(response)), cancellationToken);
sb.Insert(0, '?');
}

private async Task ThrowExceptionOnResponseFailureAsync(HttpResponseMessage response)
foreach (var item in query)
{
if (response.IsSuccessStatusCode)
foreach (var value in item.Value)
{
return;
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;
}

var detail = await response.Content.ReadAsStringAsync();
private static async Task ThrowExceptionOnResponseFailureAsync(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);
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})");
var innerException = new HttpRequestException(
$"Response status code does not indicate success: {(int)response.StatusCode} ({response.ReasonPhrase})");
#endif
throw response.StatusCode switch
{
HttpStatusCode.BadRequest => new AzureSignalRInvalidArgumentException(response.RequestMessage?.RequestUri?.ToString(), innerException, detail),
HttpStatusCode.Unauthorized => new AzureSignalRUnauthorizedException(response.RequestMessage?.RequestUri?.ToString(), innerException),
HttpStatusCode.NotFound => new AzureSignalRInaccessibleEndpointException(response.RequestMessage?.RequestUri?.ToString(), innerException),
_ => new AzureSignalRRuntimeException(response.RequestMessage?.RequestUri?.ToString(), innerException),
};
}

private async Task SendAsyncCore(
string httpClientName,
RestApiEndpoint api,
HttpMethod httpMethod,
string? methodName = null,
object[]? args = null,
Func<HttpResponseMessage, Task<bool>>? handleExpectedResponseAsync = null,
CancellationToken cancellationToken = default)
throw response.StatusCode switch
{
using var httpClient = _httpClientFactory.CreateClient(httpClientName);
using var request = BuildRequest(api, httpMethod, methodName, args);
HttpStatusCode.BadRequest => new AzureSignalRInvalidArgumentException(response.RequestMessage?.RequestUri?.ToString(), innerException, detail),
HttpStatusCode.Unauthorized => new AzureSignalRUnauthorizedException(response.RequestMessage?.RequestUri?.ToString(), innerException),
HttpStatusCode.NotFound => new AzureSignalRInaccessibleEndpointException(response.RequestMessage?.RequestUri?.ToString(), innerException),
_ => new AzureSignalRRuntimeException(response.RequestMessage?.RequestUri?.ToString(), innerException),
};
}

try
{
using var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
if (handleExpectedResponseAsync == null)
{
await ThrowExceptionOnResponseFailureAsync(response);
}
else
{
if (!await handleExpectedResponseAsync(response))
{
await ThrowExceptionOnResponseFailureAsync(response);
}
}
}
catch (HttpRequestException ex)
{
throw new AzureSignalRException($"An error happened when making request to {request.RequestUri}", ex);
}
}
private async Task SendAsyncCore(
string httpClientName,
RestApiEndpoint api,
HttpMethod httpMethod,
string? methodName = null,
object[]? args = null,
Func<HttpResponseMessage, Task<bool>>? handleExpectedResponseAsync = null,
CancellationToken cancellationToken = default)
{
using var httpClient = _httpClientFactory.CreateClient(httpClientName);
using var request = BuildRequest(api, httpMethod, methodName, args);

private static Uri GetUri(string url, IDictionary<string, StringValues>? query)
try
{
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] == '?')
using var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
if (handleExpectedResponseAsync == null)
{
sb.Clear();
await ThrowExceptionOnResponseFailureAsync(response);
}
else if (sb.Length > 0 && sb[0] != '?')
else
{
sb.Insert(0, '?');
}
foreach (var item in query)
{
foreach (var value in item.Value)
if (!await handleExpectedResponseAsync(response))
{
sb.Append(sb.Length > 0 ? '&' : '?');
sb.Append(Uri.EscapeDataString(item.Key));
sb.Append('=');
sb.Append(Uri.EscapeDataString(value!));
await ThrowExceptionOnResponseFailureAsync(response);
}
}
builder.Query = sb.ToString();
return builder.Uri;
}

private HttpRequestMessage BuildRequest(RestApiEndpoint api, HttpMethod httpMethod, string? methodName = null, object[]? args = null)
catch (HttpRequestException ex)
{
var payload = httpMethod == HttpMethod.Post ? new PayloadMessage { Target = methodName, Arguments = args } : null;
return GenerateHttpRequest(api.Audience, api.Query, httpMethod, payload, api.Token);
throw new AzureSignalRException($"An error happened when making request to {request.RequestUri}", ex);
}
}

private HttpRequestMessage GenerateHttpRequest(string url, IDictionary<string, StringValues> query, HttpMethod httpMethod, PayloadMessage? payload, string tokenString)
{
var request = new HttpRequestMessage(httpMethod, GetUri(url, query));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenString);
request.Content = _payloadContentBuilder.Build(payload);
return request;
}
private HttpRequestMessage BuildRequest(RestApiEndpoint api, HttpMethod httpMethod, string? methodName = null, object[]? args = null)
{
var payload = httpMethod == HttpMethod.Post ? new PayloadMessage { Target = methodName, Arguments = args } : null;
return GenerateHttpRequest(api.Audience, api.Query, httpMethod, payload, api.Token);
}

private HttpRequestMessage GenerateHttpRequest(string url, IDictionary<string, StringValues> query, HttpMethod httpMethod, PayloadMessage? payload, string tokenString)
{
var request = new HttpRequestMessage(httpMethod, GetUri(url, query));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenString);
request.Content = _payloadContentBuilder.Build(payload);
return request;
}
}
Loading

0 comments on commit 5caea7f

Please sign in to comment.