Cache HTTP client in player locator (#12555)

Also add user agent
This commit is contained in:
Pieter-Jan Briers 2022-11-12 02:56:47 +01:00 committed by GitHub
parent e24e66e294
commit 7e886a56b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 20 additions and 5 deletions

View File

@ -1,6 +1,7 @@
using System.Collections.Immutable;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
@ -43,12 +44,23 @@ namespace Content.Server.Administration
Task<LocatedPlayerData?> LookupIdAsync(NetUserId userId, CancellationToken cancel = default);
}
internal sealed class PlayerLocator : IPlayerLocator
internal sealed class PlayerLocator : IPlayerLocator, IDisposable
{
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IConfigurationManager _configurationManager = default!;
[Dependency] private readonly IServerDbManager _db = default!;
private readonly HttpClient _httpClient = new();
public PlayerLocator()
{
if (typeof(PlayerLocator).Assembly.GetName().Version is { } version)
{
_httpClient.DefaultRequestHeaders.UserAgent.Add(
new ProductInfoHeaderValue("SpaceStation14", version.ToString()));
}
}
public async Task<LocatedPlayerData?> LookupIdByNameAsync(string playerName, CancellationToken cancel = default)
{
// Check people currently on the server, the easiest case.
@ -66,10 +78,9 @@ namespace Content.Server.Administration
return new LocatedPlayerData(record.UserId, record.LastSeenAddress, record.HWId, record.LastSeenUserName);
// If all else fails, ask the auth server.
var client = new HttpClient();
var authServer = _configurationManager.GetCVar(CVars.AuthServer);
var requestUri = $"{authServer}api/query/name?name={WebUtility.UrlEncode(playerName)}";
using var resp = await client.GetAsync(requestUri, cancel);
using var resp = await _httpClient.GetAsync(requestUri, cancel);
if (resp.StatusCode == HttpStatusCode.NotFound)
return null;
@ -107,10 +118,9 @@ namespace Content.Server.Administration
return new LocatedPlayerData(record.UserId, record.LastSeenAddress, record.HWId, record.LastSeenUserName);
// If all else fails, ask the auth server.
var client = new HttpClient();
var authServer = _configurationManager.GetCVar(CVars.AuthServer);
var requestUri = $"{authServer}api/query/userid?userid={WebUtility.UrlEncode(userId.UserId.ToString())}";
using var resp = await client.GetAsync(requestUri, cancel);
using var resp = await _httpClient.GetAsync(requestUri, cancel);
if (resp.StatusCode == HttpStatusCode.NotFound)
return null;
@ -148,5 +158,10 @@ namespace Content.Server.Administration
private sealed record UserDataResponse(string UserName, Guid UserId)
{
}
void IDisposable.Dispose()
{
_httpClient.Dispose();
}
}
}