From b75135d8cdb702423d693558ffaec3f025264b98 Mon Sep 17 00:00:00 2001 From: TheArcaneBrony Date: Thu, 26 Oct 2023 13:09:05 +0000 Subject: split client and server http client for homeservers --- LibMatrix/Services/HomeserverProviderService.cs | 31 ++++++------ LibMatrix/Services/HomeserverResolverService.cs | 63 ++++++++----------------- 2 files changed, 36 insertions(+), 58 deletions(-) (limited to 'LibMatrix/Services') diff --git a/LibMatrix/Services/HomeserverProviderService.cs b/LibMatrix/Services/HomeserverProviderService.cs index c7fa5c3..a43f518 100644 --- a/LibMatrix/Services/HomeserverProviderService.cs +++ b/LibMatrix/Services/HomeserverProviderService.cs @@ -16,23 +16,26 @@ public class HomeserverProviderService { } private static Dictionary _authenticatedHomeserverSemaphore = new(); - private static Dictionary _authenticatedHomeServerCache = new(); + private static Dictionary _authenticatedHomeserverCache = new(); private static Dictionary _remoteHomeserverSemaphore = new(); - private static Dictionary _remoteHomeServerCache = new(); + private static Dictionary _remoteHomeserverCache = new(); - public async Task GetAuthenticatedWithToken(string homeserver, string accessToken, - string? proxy = null) { + public async Task GetAuthenticatedWithToken(string homeserver, string accessToken, string? proxy = null) { var sem = _authenticatedHomeserverSemaphore.GetOrCreate(homeserver + accessToken, _ => new SemaphoreSlim(1, 1)); await sem.WaitAsync(); - lock (_authenticatedHomeServerCache) { - if (_authenticatedHomeServerCache.ContainsKey(homeserver + accessToken)) { + lock (_authenticatedHomeserverCache) { + if (_authenticatedHomeserverCache.ContainsKey(homeserver + accessToken)) { sem.Release(); - return _authenticatedHomeServerCache[homeserver + accessToken]; + return _authenticatedHomeserverCache[homeserver + accessToken]; } } - var domain = proxy ?? await _homeserverResolverService.ResolveHomeserverFromWellKnown(homeserver); + // var domain = proxy ?? (await _homeserverResolverService.ResolveHomeserverFromWellKnown(homeserver)).client; + + var rhs = await RemoteHomeserver.Create(homeserver); + var serverVersion = await rhs.GetServerVersionAsync(); + AuthenticatedHomeserverGeneric hs; if (true) { @@ -44,15 +47,15 @@ public class HomeserverProviderService { // (() => hs.WhoAmI) = (await hs._httpClient.GetFromJsonAsync("/_matrix/client/v3/account/whoami"))!; - lock(_authenticatedHomeServerCache) - _authenticatedHomeServerCache[homeserver + accessToken] = hs; + lock (_authenticatedHomeserverCache) + _authenticatedHomeserverCache[homeserver + accessToken] = hs; sem.Release(); return hs; } - public async Task GetRemoteHomeserver(string homeserver, string? proxy = null) { - var hs = await RemoteHomeServer.Create(proxy ?? await _homeserverResolverService.ResolveHomeserverFromWellKnown(homeserver)); + public async Task GetRemoteHomeserver(string homeserver, string? proxy = null) { + var hs = await RemoteHomeserver.Create(proxy ?? homeserver); // hs._httpClient.Dispose(); // hs._httpClient = new MatrixHttpClient { BaseAddress = new Uri(hs.ServerName) }; // hs._httpClient.Timeout = TimeSpan.FromSeconds(120); @@ -65,8 +68,8 @@ public class HomeserverProviderService { Identifier = new LoginRequest.LoginIdentifier { User = user }, Password = password }; - var resp = await hs._httpClient.PostAsJsonAsync("/_matrix/client/v3/login", payload); + var resp = await hs.ClientHttpClient.PostAsJsonAsync("/_matrix/client/v3/login", payload); var data = await resp.Content.ReadFromJsonAsync(); return data!; } -} +} \ No newline at end of file diff --git a/LibMatrix/Services/HomeserverResolverService.cs b/LibMatrix/Services/HomeserverResolverService.cs index 75545db..06771b0 100644 --- a/LibMatrix/Services/HomeserverResolverService.cs +++ b/LibMatrix/Services/HomeserverResolverService.cs @@ -8,42 +8,28 @@ namespace LibMatrix.Services; public class HomeserverResolverService(ILogger? logger = null) { private readonly MatrixHttpClient _httpClient = new(); - private static readonly Dictionary _wellKnownCache = new(); + private static readonly Dictionary _wellKnownCache = new(); private static readonly Dictionary _wellKnownSemaphores = new(); - public async Task ResolveHomeserverFromWellKnown(string homeserver) { + public async Task<(string client, string server)> ResolveHomeserverFromWellKnown(string homeserver) { if (homeserver is null) throw new ArgumentNullException(nameof(homeserver)); - if(_wellKnownCache.TryGetValue(homeserver, out var known)) return known; - logger?.LogInformation("Resolving homeserver: {}", homeserver); - var res = await _resolveHomeserverFromWellKnown(homeserver); - if (!res.StartsWith("http")) res = "https://" + res; - if (res.EndsWith(":443")) res = res[..^4]; - return res; - } - - private async Task _resolveHomeserverFromWellKnown(string homeserver) { - if (homeserver is null) throw new ArgumentNullException(nameof(homeserver)); - var sem = _wellKnownSemaphores.GetOrCreate(homeserver, _ => new SemaphoreSlim(1, 1)); - if(_wellKnownCache.TryGetValue(homeserver, out var wellKnown)) return wellKnown; - await sem.WaitAsync(); + // if(!_wellKnownSemaphores.ContainsKey(homeserver)) + // _wellKnownSemaphores[homeserver] = new(1, 1); + _wellKnownSemaphores.TryAdd(homeserver, new(1, 1)); + await _wellKnownSemaphores[homeserver].WaitAsync(); if (_wellKnownCache.TryGetValue(homeserver, out var known)) { - sem.Release(); + _wellKnownSemaphores[homeserver].Release(); return known; } - - string? result = null; - logger?.LogInformation("Attempting to resolve homeserver: {}", homeserver); - result ??= await _tryResolveFromClientWellknown(homeserver); - result ??= await _tryResolveFromServerWellknown(homeserver); - result ??= await _tryCheckIfDomainHasHomeserver(homeserver); - - if (result is null) throw new InvalidDataException($"Failed to resolve homeserver for {homeserver}! Is it online and configured correctly?"); - - //success! - logger?.LogInformation("Resolved homeserver: {} -> {}", homeserver, result); - _wellKnownCache[homeserver] = result; - sem.Release(); - return result; + + logger?.LogInformation("Resolving homeserver: {}", homeserver); + var res = ( + await _tryResolveFromClientWellknown(homeserver), + await _tryResolveFromServerWellknown(homeserver) + ); + _wellKnownCache.Add(homeserver, res!); + _wellKnownSemaphores[homeserver].Release(); + return res; } private async Task _tryResolveFromClientWellknown(string homeserver) { @@ -63,6 +49,8 @@ public class HomeserverResolverService(ILogger? logge if (await _httpClient.CheckSuccessStatus($"{homeserver}/.well-known/matrix/server")) { var resp = await _httpClient.GetFromJsonAsync($"{homeserver}/.well-known/matrix/server"); var hs = resp.GetProperty("m.server").GetString(); + if (!hs.StartsWithAnyOf("http://", "https://")) + hs = $"https://{hs}"; return hs; } @@ -70,24 +58,11 @@ public class HomeserverResolverService(ILogger? logge return null; } - private async Task _tryCheckIfDomainHasHomeserver(string homeserver) { - logger?.LogInformation("Checking if {} hosts a homeserver...", homeserver); - if (await _httpClient.CheckSuccessStatus($"{homeserver}/_matrix/client/versions")) - return homeserver; - logger?.LogInformation("No homeserver on shortname..."); - return null; - } - - private async Task _tryCheckIfSubDomainHasHomeserver(string homeserver, string subdomain) { - homeserver = homeserver.Replace("https://", $"https://{subdomain}."); - return await _tryCheckIfDomainHasHomeserver(homeserver); - } - public async Task ResolveMediaUri(string homeserver, string mxc) { if (homeserver is null) throw new ArgumentNullException(nameof(homeserver)); if (mxc is null) throw new ArgumentNullException(nameof(mxc)); if (!mxc.StartsWith("mxc://")) throw new InvalidDataException("mxc must start with mxc://"); - homeserver = await ResolveHomeserverFromWellKnown(homeserver); + homeserver = (await ResolveHomeserverFromWellKnown(homeserver)).client; return mxc.Replace("mxc://", $"{homeserver}/_matrix/media/v3/download/"); } } -- cgit 1.4.1