2021-08-27 15:03:47 +00:00
|
|
|
using System;
|
2020-12-22 12:15:26 +00:00
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Diagnostics;
|
|
|
|
using System.Net;
|
|
|
|
using System.Net.Http;
|
|
|
|
using System.Net.Http.Headers;
|
|
|
|
using System.Net.Http.Json;
|
|
|
|
using System.Text.Json;
|
2021-11-02 09:34:17 +00:00
|
|
|
using System.Text.RegularExpressions;
|
2020-12-22 12:15:26 +00:00
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
using Myriad.Rest.Exceptions;
|
|
|
|
using Myriad.Rest.Ratelimit;
|
|
|
|
using Myriad.Rest.Types;
|
|
|
|
using Myriad.Serialization;
|
|
|
|
|
|
|
|
using Polly;
|
|
|
|
|
|
|
|
using Serilog;
|
2021-06-10 12:21:05 +00:00
|
|
|
using Serilog.Context;
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
namespace Myriad.Rest
|
|
|
|
{
|
|
|
|
public class BaseRestClient: IAsyncDisposable
|
|
|
|
{
|
|
|
|
private readonly Version _httpVersion = new(2, 0);
|
|
|
|
private readonly JsonSerializerOptions _jsonSerializerOptions;
|
|
|
|
private readonly ILogger _logger;
|
|
|
|
private readonly Ratelimiter _ratelimiter;
|
|
|
|
private readonly AsyncPolicy<HttpResponseMessage> _retryPolicy;
|
2021-11-02 09:36:53 +00:00
|
|
|
private readonly string _baseUrl;
|
2020-12-22 12:15:26 +00:00
|
|
|
|
2021-11-02 09:36:53 +00:00
|
|
|
public BaseRestClient(string userAgent, string token, ILogger logger, string baseUrl)
|
2020-12-22 12:15:26 +00:00
|
|
|
{
|
|
|
|
_logger = logger.ForContext<BaseRestClient>();
|
2021-11-02 09:36:53 +00:00
|
|
|
_baseUrl = baseUrl;
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
if (!token.StartsWith("Bot "))
|
|
|
|
token = "Bot " + token;
|
|
|
|
|
|
|
|
Client = new HttpClient();
|
|
|
|
Client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgent);
|
|
|
|
Client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);
|
|
|
|
|
2021-01-30 00:07:43 +00:00
|
|
|
_jsonSerializerOptions = new JsonSerializerOptions().ConfigureForMyriad();
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
_ratelimiter = new Ratelimiter(logger);
|
|
|
|
var discordPolicy = new DiscordRateLimitPolicy(_ratelimiter);
|
|
|
|
|
|
|
|
// todo: why doesn't the timeout work? o.o
|
|
|
|
var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(10));
|
|
|
|
|
|
|
|
var waitPolicy = Policy
|
|
|
|
.Handle<RatelimitBucketExhaustedException>()
|
|
|
|
.WaitAndRetryAsync(3,
|
2021-08-27 15:03:47 +00:00
|
|
|
(_, e, _) => ((RatelimitBucketExhaustedException)e).RetryAfter,
|
2020-12-22 12:15:26 +00:00
|
|
|
(_, _, _, _) => Task.CompletedTask)
|
|
|
|
.AsAsyncPolicy<HttpResponseMessage>();
|
|
|
|
|
|
|
|
_retryPolicy = Policy.WrapAsync(timeoutPolicy, waitPolicy, discordPolicy);
|
|
|
|
}
|
|
|
|
|
|
|
|
public HttpClient Client { get; }
|
2021-11-02 09:34:17 +00:00
|
|
|
public EventHandler<(string, int, long)> OnResponseEvent;
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
public ValueTask DisposeAsync()
|
|
|
|
{
|
|
|
|
_ratelimiter.Dispose();
|
|
|
|
Client.Dispose();
|
|
|
|
return default;
|
|
|
|
}
|
|
|
|
|
2021-08-27 15:03:47 +00:00
|
|
|
public async Task<T?> Get<T>(string path, (string endpointName, ulong major) ratelimitParams) where T : class
|
2020-12-22 12:15:26 +00:00
|
|
|
{
|
2021-11-02 09:36:53 +00:00
|
|
|
using var response = await Send(() => new HttpRequestMessage(HttpMethod.Get, _baseUrl + path),
|
2021-03-21 13:15:13 +00:00
|
|
|
ratelimitParams, true);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
// GET-only special case: 404s are nulls and not exceptions
|
|
|
|
if (response.StatusCode == HttpStatusCode.NotFound)
|
|
|
|
return null;
|
|
|
|
|
|
|
|
return await ReadResponse<T>(response);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task<T?> Post<T>(string path, (string endpointName, ulong major) ratelimitParams, object? body)
|
2021-08-27 15:03:47 +00:00
|
|
|
where T : class
|
2020-12-22 12:15:26 +00:00
|
|
|
{
|
2021-03-21 13:15:13 +00:00
|
|
|
using var response = await Send(() =>
|
|
|
|
{
|
2021-11-02 09:36:53 +00:00
|
|
|
var request = new HttpRequestMessage(HttpMethod.Post, _baseUrl + path);
|
2021-03-21 13:15:13 +00:00
|
|
|
SetRequestJsonBody(request, body);
|
|
|
|
return request;
|
|
|
|
}, ratelimitParams);
|
2020-12-22 12:15:26 +00:00
|
|
|
return await ReadResponse<T>(response);
|
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
public async Task<T?> PostMultipart<T>(string path, (string endpointName, ulong major) ratelimitParams, object? payload, MultipartFile[]? files)
|
2021-08-27 15:03:47 +00:00
|
|
|
where T : class
|
2020-12-22 12:15:26 +00:00
|
|
|
{
|
2021-03-21 13:15:13 +00:00
|
|
|
using var response = await Send(() =>
|
|
|
|
{
|
2021-11-02 09:36:53 +00:00
|
|
|
var request = new HttpRequestMessage(HttpMethod.Post, _baseUrl + path);
|
2021-03-21 13:15:13 +00:00
|
|
|
SetRequestFormDataBody(request, payload, files);
|
|
|
|
return request;
|
|
|
|
}, ratelimitParams);
|
2020-12-22 12:15:26 +00:00
|
|
|
return await ReadResponse<T>(response);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task<T?> Patch<T>(string path, (string endpointName, ulong major) ratelimitParams, object? body)
|
2021-08-27 15:03:47 +00:00
|
|
|
where T : class
|
2020-12-22 12:15:26 +00:00
|
|
|
{
|
2021-03-21 13:15:13 +00:00
|
|
|
using var response = await Send(() =>
|
|
|
|
{
|
2021-11-02 09:36:53 +00:00
|
|
|
var request = new HttpRequestMessage(HttpMethod.Patch, _baseUrl + path);
|
2021-03-21 13:15:13 +00:00
|
|
|
SetRequestJsonBody(request, body);
|
|
|
|
return request;
|
|
|
|
}, ratelimitParams);
|
2020-12-22 12:15:26 +00:00
|
|
|
return await ReadResponse<T>(response);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task<T?> Put<T>(string path, (string endpointName, ulong major) ratelimitParams, object? body)
|
2021-08-27 15:03:47 +00:00
|
|
|
where T : class
|
2020-12-22 12:15:26 +00:00
|
|
|
{
|
2021-03-21 13:15:13 +00:00
|
|
|
using var response = await Send(() =>
|
|
|
|
{
|
2021-11-02 09:36:53 +00:00
|
|
|
var request = new HttpRequestMessage(HttpMethod.Put, _baseUrl + path);
|
2021-03-21 13:15:13 +00:00
|
|
|
SetRequestJsonBody(request, body);
|
|
|
|
return request;
|
|
|
|
}, ratelimitParams);
|
2020-12-22 12:15:26 +00:00
|
|
|
return await ReadResponse<T>(response);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task Delete(string path, (string endpointName, ulong major) ratelimitParams)
|
|
|
|
{
|
2021-11-02 09:36:53 +00:00
|
|
|
using var _ = await Send(() => new HttpRequestMessage(HttpMethod.Delete, _baseUrl + path), ratelimitParams);
|
2020-12-22 12:15:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private void SetRequestJsonBody(HttpRequestMessage request, object? body)
|
|
|
|
{
|
|
|
|
if (body == null) return;
|
|
|
|
request.Content =
|
|
|
|
new ReadOnlyMemoryContent(JsonSerializer.SerializeToUtf8Bytes(body, _jsonSerializerOptions));
|
|
|
|
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
|
|
|
}
|
|
|
|
|
|
|
|
private void SetRequestFormDataBody(HttpRequestMessage request, object? payload, MultipartFile[]? files)
|
|
|
|
{
|
|
|
|
var bodyJson = JsonSerializer.SerializeToUtf8Bytes(payload, _jsonSerializerOptions);
|
|
|
|
|
|
|
|
var mfd = new MultipartFormDataContent();
|
|
|
|
mfd.Add(new ByteArrayContent(bodyJson), "payload_json");
|
|
|
|
|
|
|
|
if (files != null)
|
|
|
|
{
|
|
|
|
for (var i = 0; i < files.Length; i++)
|
|
|
|
{
|
|
|
|
var (filename, stream) = files[i];
|
|
|
|
mfd.Add(new StreamContent(stream), $"file{i}", filename);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
request.Content = mfd;
|
|
|
|
}
|
|
|
|
|
2021-08-27 15:03:47 +00:00
|
|
|
private async Task<T?> ReadResponse<T>(HttpResponseMessage response) where T : class
|
2020-12-22 12:15:26 +00:00
|
|
|
{
|
|
|
|
if (response.StatusCode == HttpStatusCode.NoContent)
|
|
|
|
return null;
|
|
|
|
return await response.Content.ReadFromJsonAsync<T>(_jsonSerializerOptions);
|
|
|
|
}
|
|
|
|
|
2021-03-21 13:15:13 +00:00
|
|
|
private async Task<HttpResponseMessage> Send(Func<HttpRequestMessage> createRequest,
|
2020-12-22 12:15:26 +00:00
|
|
|
(string endpointName, ulong major) ratelimitParams,
|
|
|
|
bool ignoreNotFound = false)
|
|
|
|
{
|
|
|
|
return await _retryPolicy.ExecuteAsync(async _ =>
|
|
|
|
{
|
2021-06-10 12:21:05 +00:00
|
|
|
using var __ = LogContext.PushProperty("EndpointName", ratelimitParams.endpointName);
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2021-03-21 13:15:13 +00:00
|
|
|
var request = createRequest();
|
2021-06-10 12:21:05 +00:00
|
|
|
_logger.Debug("Request: {RequestMethod} {RequestPath}",
|
2021-11-02 09:44:47 +00:00
|
|
|
request.Method, CleanForLogging(request.RequestUri!));
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
request.Version = _httpVersion;
|
|
|
|
request.VersionPolicy = HttpVersionPolicy.RequestVersionOrHigher;
|
|
|
|
|
2021-11-02 09:34:17 +00:00
|
|
|
HttpResponseMessage response;
|
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
var stopwatch = new Stopwatch();
|
|
|
|
stopwatch.Start();
|
2021-11-02 09:34:17 +00:00
|
|
|
try
|
|
|
|
{
|
|
|
|
response = await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
|
|
|
|
stopwatch.Stop();
|
|
|
|
}
|
|
|
|
catch (Exception exc)
|
|
|
|
{
|
|
|
|
_logger.Error(exc, "HTTP error: {RequestMethod} {RequestUrl}", request.Method, request.RequestUri);
|
|
|
|
|
|
|
|
// kill the running thread
|
|
|
|
// in PluralKit.Bot, this error is ignored in "IsOurProblem" (PluralKit.Bot/Utils/MiscUtils.cs)
|
|
|
|
throw;
|
|
|
|
}
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
_logger.Debug(
|
2021-06-10 12:21:05 +00:00
|
|
|
"Response: {RequestMethod} {RequestPath} -> {StatusCode} {ReasonPhrase} (in {ResponseDurationMs} ms)",
|
2021-11-02 09:44:47 +00:00
|
|
|
request.Method, CleanForLogging(request.RequestUri!), (int)response.StatusCode,
|
2021-11-02 09:36:53 +00:00
|
|
|
response.ReasonPhrase, stopwatch.ElapsedMilliseconds);
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
await HandleApiError(response, ignoreNotFound);
|
|
|
|
|
2021-11-02 09:34:17 +00:00
|
|
|
if (OnResponseEvent != null)
|
|
|
|
OnResponseEvent.Invoke(null, (
|
|
|
|
GetEndpointMetricsName(response.RequestMessage!),
|
|
|
|
(int)response.StatusCode,
|
|
|
|
stopwatch.ElapsedTicks
|
|
|
|
));
|
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
return response;
|
|
|
|
},
|
|
|
|
new Dictionary<string, object>
|
|
|
|
{
|
|
|
|
{DiscordRateLimitPolicy.EndpointContextKey, ratelimitParams.endpointName},
|
|
|
|
{DiscordRateLimitPolicy.MajorContextKey, ratelimitParams.major}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
private async ValueTask HandleApiError(HttpResponseMessage response, bool ignoreNotFound)
|
|
|
|
{
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
|
|
return;
|
|
|
|
|
|
|
|
if (response.StatusCode == HttpStatusCode.NotFound && ignoreNotFound)
|
|
|
|
return;
|
|
|
|
|
2021-06-10 12:21:05 +00:00
|
|
|
var body = await response.Content.ReadAsStringAsync();
|
2021-08-27 15:03:47 +00:00
|
|
|
var apiError = TryParseApiError(body);
|
2021-06-10 12:21:05 +00:00
|
|
|
if (apiError != null)
|
|
|
|
_logger.Warning("Discord API error: {DiscordErrorCode} {DiscordErrorMessage}", apiError.Code, apiError.Message);
|
|
|
|
|
|
|
|
throw CreateDiscordException(response, body, apiError);
|
2020-12-22 12:15:26 +00:00
|
|
|
}
|
|
|
|
|
2021-06-10 12:21:05 +00:00
|
|
|
private DiscordRequestException CreateDiscordException(HttpResponseMessage response, string body, DiscordApiError? apiError)
|
2020-12-22 12:15:26 +00:00
|
|
|
{
|
|
|
|
return response.StatusCode switch
|
|
|
|
{
|
|
|
|
HttpStatusCode.BadRequest => new BadRequestException(response, body, apiError),
|
|
|
|
HttpStatusCode.Forbidden => new ForbiddenException(response, body, apiError),
|
|
|
|
HttpStatusCode.Unauthorized => new UnauthorizedException(response, body, apiError),
|
|
|
|
HttpStatusCode.NotFound => new NotFoundException(response, body, apiError),
|
|
|
|
HttpStatusCode.Conflict => new ConflictException(response, body, apiError),
|
|
|
|
HttpStatusCode.TooManyRequests => new TooManyRequestsException(response, body, apiError),
|
|
|
|
_ => new UnknownDiscordRequestException(response, body, apiError)
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
private DiscordApiError? TryParseApiError(string responseBody)
|
|
|
|
{
|
|
|
|
if (string.IsNullOrWhiteSpace(responseBody))
|
|
|
|
return null;
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
return JsonSerializer.Deserialize<DiscordApiError>(responseBody, _jsonSerializerOptions);
|
|
|
|
}
|
|
|
|
catch (JsonException e)
|
|
|
|
{
|
|
|
|
_logger.Verbose(e, "Error deserializing API error");
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
2021-11-02 09:34:17 +00:00
|
|
|
|
|
|
|
private string NormalizeRoutePath(string url)
|
|
|
|
{
|
|
|
|
url = Regex.Replace(url, @"/channels/\d+", "/channels/{channel_id}");
|
|
|
|
url = Regex.Replace(url, @"/messages/\d+", "/messages/{message_id}");
|
|
|
|
url = Regex.Replace(url, @"/members/\d+", "/members/{user_id}");
|
|
|
|
url = Regex.Replace(url, @"/webhooks/\d+/[^/]+", "/webhooks/{webhook_id}/{webhook_token}");
|
|
|
|
url = Regex.Replace(url, @"/webhooks/\d+", "/webhooks/{webhook_id}");
|
|
|
|
url = Regex.Replace(url, @"/users/\d+", "/users/{user_id}");
|
|
|
|
url = Regex.Replace(url, @"/bans/\d+", "/bans/{user_id}");
|
|
|
|
url = Regex.Replace(url, @"/roles/\d+", "/roles/{role_id}");
|
|
|
|
url = Regex.Replace(url, @"/pins/\d+", "/pins/{message_id}");
|
|
|
|
url = Regex.Replace(url, @"/emojis/\d+", "/emojis/{emoji_id}");
|
|
|
|
url = Regex.Replace(url, @"/guilds/\d+", "/guilds/{guild_id}");
|
|
|
|
url = Regex.Replace(url, @"/integrations/\d+", "/integrations/{integration_id}");
|
|
|
|
url = Regex.Replace(url, @"/permissions/\d+", "/permissions/{overwrite_id}");
|
|
|
|
url = Regex.Replace(url, @"/reactions/[^{/]+/\d+", "/reactions/{emoji}/{user_id}");
|
|
|
|
url = Regex.Replace(url, @"/reactions/[^{/]+", "/reactions/{emoji}");
|
|
|
|
url = Regex.Replace(url, @"/invites/[^{/]+", "/invites/{invite_code}");
|
|
|
|
url = Regex.Replace(url, @"/interactions/\d+/[^{/]+", "/interactions/{interaction_id}/{interaction_token}");
|
|
|
|
url = Regex.Replace(url, @"/interactions/\d+", "/interactions/{interaction_id}");
|
|
|
|
|
|
|
|
// catch-all for missed IDs
|
|
|
|
url = Regex.Replace(url, @"\d{17,19}", "{snowflake}");
|
|
|
|
|
|
|
|
return url;
|
|
|
|
}
|
|
|
|
|
|
|
|
private string GetEndpointMetricsName(HttpRequestMessage req)
|
|
|
|
{
|
|
|
|
var localPath = Regex.Replace(req.RequestUri!.LocalPath, @"/api/v\d+", "");
|
|
|
|
var routePath = NormalizeRoutePath(localPath);
|
|
|
|
return $"{req.Method} {routePath}";
|
|
|
|
}
|
2021-11-02 09:44:47 +00:00
|
|
|
|
|
|
|
private string CleanForLogging(Uri uri)
|
|
|
|
{
|
|
|
|
var path = uri.ToString();
|
|
|
|
|
|
|
|
// don't show tokens in logs
|
|
|
|
// todo: anything missing here?
|
|
|
|
path = Regex.Replace(path, @"/webhooks/(\d+)/[^/]+", "/webhooks/$1/:token");
|
|
|
|
path = Regex.Replace(path, @"/interactions/(\d+)/[^{/]+", "/interactions/$1/:token");
|
|
|
|
|
|
|
|
// remove base URL
|
|
|
|
path = path.Substring(_baseUrl.Length);
|
|
|
|
|
|
|
|
return path;
|
|
|
|
}
|
2020-12-22 12:15:26 +00:00
|
|
|
}
|
|
|
|
}
|