about summary refs log tree commit diff
path: root/LibMatrix/Services
diff options
context:
space:
mode:
authorEmma [it/its]@Rory& <root@rory.gay>2023-12-14 07:20:46 +0100
committerEmma [it/its]@Rory& <root@rory.gay>2023-12-14 07:20:46 +0100
commit5affd9f061e75f6575a2fe6715f9e8757cfe87e8 (patch)
tree13ea35ce981094a960746777a16dff8815c45e55 /LibMatrix/Services
parentTemp state (diff)
downloadLibMatrix-5affd9f061e75f6575a2fe6715f9e8757cfe87e8.tar.xz
Cleanup
Diffstat (limited to 'LibMatrix/Services')
-rw-r--r--LibMatrix/Services/HomeserverProviderService.cs47
-rw-r--r--LibMatrix/Services/HomeserverResolverService.cs25
2 files changed, 45 insertions, 27 deletions
diff --git a/LibMatrix/Services/HomeserverProviderService.cs b/LibMatrix/Services/HomeserverProviderService.cs
index a42077a..983f469 100644
--- a/LibMatrix/Services/HomeserverProviderService.cs
+++ b/LibMatrix/Services/HomeserverProviderService.cs
@@ -6,20 +6,20 @@ using Microsoft.Extensions.Logging;
 
 namespace LibMatrix.Services;
 
-public class HomeserverProviderService(ILogger<HomeserverProviderService> logger, HomeserverResolverService homeserverResolverService) {
-    private static Dictionary<string, SemaphoreSlim> _authenticatedHomeserverSemaphore = new();
-    private static Dictionary<string, AuthenticatedHomeserverGeneric> _authenticatedHomeserverCache = new();
+public class HomeserverProviderService(ILogger<HomeserverProviderService> logger) {
+    private static readonly Dictionary<string, SemaphoreSlim> AuthenticatedHomeserverSemaphore = new();
+    private static readonly Dictionary<string, AuthenticatedHomeserverGeneric> AuthenticatedHomeserverCache = new();
 
-    private static Dictionary<string, SemaphoreSlim> _remoteHomeserverSemaphore = new();
-    private static Dictionary<string, RemoteHomeserver> _remoteHomeserverCache = new();
+    private static readonly Dictionary<string, SemaphoreSlim> RemoteHomeserverSemaphore = new();
+    private static readonly Dictionary<string, RemoteHomeserver> RemoteHomeserverCache = new();
 
     public async Task<AuthenticatedHomeserverGeneric> GetAuthenticatedWithToken(string homeserver, string accessToken, string? proxy = null) {
         var cacheKey = homeserver + accessToken + proxy;
-        var sem = _authenticatedHomeserverSemaphore.GetOrCreate(cacheKey, _ => new SemaphoreSlim(1, 1));
+        var sem = AuthenticatedHomeserverSemaphore.GetOrCreate(cacheKey, _ => new SemaphoreSlim(1, 1));
         await sem.WaitAsync();
         AuthenticatedHomeserverGeneric? hs;
-        lock (_authenticatedHomeserverCache) {
-            if (_authenticatedHomeserverCache.TryGetValue(cacheKey, out hs)) {
+        lock (AuthenticatedHomeserverCache) {
+            if (AuthenticatedHomeserverCache.TryGetValue(cacheKey, out hs)) {
                 sem.Release();
                 return hs;
             }
@@ -30,8 +30,8 @@ public class HomeserverProviderService(ILogger<HomeserverProviderService> logger
         var rhs = await RemoteHomeserver.Create(homeserver, proxy);
         var clientVersions = await rhs.GetClientVersionsAsync();
         if (proxy is not null)
-            Console.WriteLine($"Homeserver {homeserver} proxied via {proxy}...");
-        Console.WriteLine($"{homeserver}: " + clientVersions.ToJson());
+            logger.LogInformation($"Homeserver {homeserver} proxied via {proxy}...");
+        logger.LogInformation($"{homeserver}: " + clientVersions.ToJson());
 
         if (clientVersions.UnstableFeatures.TryGetValue("gay.rory.mxapiextensions.v0", out bool a) && a)
             hs = await AuthenticatedHomeserverGeneric.Create<AuthenticatedHomeserverMxApiExtended>(homeserver, accessToken, proxy);
@@ -43,18 +43,31 @@ public class HomeserverProviderService(ILogger<HomeserverProviderService> logger
                 hs = await AuthenticatedHomeserverGeneric.Create<AuthenticatedHomeserverGeneric>(homeserver, accessToken, proxy);
         }
 
-        lock (_authenticatedHomeserverCache)
-            _authenticatedHomeserverCache[cacheKey] = hs;
+        lock (AuthenticatedHomeserverCache)
+            AuthenticatedHomeserverCache[cacheKey] = hs;
         sem.Release();
 
         return hs;
     }
 
     public async Task<RemoteHomeserver> GetRemoteHomeserver(string homeserver, string? proxy = null) {
-        var hs = await RemoteHomeserver.Create(homeserver, proxy);
-        // hs._httpClient.Dispose();
-        // hs._httpClient = new MatrixHttpClient { BaseAddress = new Uri(hs.ServerName) };
-        // hs._httpClient.Timeout = TimeSpan.FromSeconds(120);
+        var cacheKey = homeserver + proxy;
+        var sem = RemoteHomeserverSemaphore.GetOrCreate(cacheKey, _ => new SemaphoreSlim(1, 1));
+        await sem.WaitAsync();
+        RemoteHomeserver? hs;
+        lock (RemoteHomeserverCache) {
+            if (RemoteHomeserverCache.TryGetValue(cacheKey, out hs)) {
+                sem.Release();
+                return hs;
+            }
+        }
+
+        hs = await RemoteHomeserver.Create(homeserver, proxy);
+
+        lock (RemoteHomeserverCache)
+            RemoteHomeserverCache[cacheKey] = hs;
+        sem.Release();
+        
         return hs;
     }
 
@@ -68,4 +81,4 @@ public class HomeserverProviderService(ILogger<HomeserverProviderService> logger
         var data = await resp.Content.ReadFromJsonAsync<LoginResponse>();
         return data!;
     }
-}
+}
\ No newline at end of file
diff --git a/LibMatrix/Services/HomeserverResolverService.cs b/LibMatrix/Services/HomeserverResolverService.cs
index f9f92d6..9f937c5 100644
--- a/LibMatrix/Services/HomeserverResolverService.cs
+++ b/LibMatrix/Services/HomeserverResolverService.cs
@@ -11,15 +11,15 @@ public class HomeserverResolverService(ILogger<HomeserverResolverService>? logge
         Timeout = TimeSpan.FromMilliseconds(10000)
     };
 
-    private static readonly ConcurrentDictionary<string, WellKnownUris> _wellKnownCache = new();
-    private static readonly ConcurrentDictionary<string, SemaphoreSlim> _wellKnownSemaphores = new();
+    private static readonly ConcurrentDictionary<string, WellKnownUris> WellKnownCache = new();
+    private static readonly ConcurrentDictionary<string, SemaphoreSlim> WellKnownSemaphores = new();
 
     public async Task<WellKnownUris> ResolveHomeserverFromWellKnown(string homeserver) {
         if (homeserver is null) throw new ArgumentNullException(nameof(homeserver));
-        _wellKnownSemaphores.TryAdd(homeserver, new(1, 1));
-        await _wellKnownSemaphores[homeserver].WaitAsync();
-        if (_wellKnownCache.TryGetValue(homeserver, out var known)) {
-            _wellKnownSemaphores[homeserver].Release();
+        WellKnownSemaphores.TryAdd(homeserver, new(1, 1));
+        await WellKnownSemaphores[homeserver].WaitAsync();
+        if (WellKnownCache.TryGetValue(homeserver, out var known)) {
+            WellKnownSemaphores[homeserver].Release();
             return known;
         }
 
@@ -28,8 +28,8 @@ public class HomeserverResolverService(ILogger<HomeserverResolverService>? logge
             Client = await _tryResolveFromClientWellknown(homeserver),
             Server = await _tryResolveFromServerWellknown(homeserver)
         };
-        _wellKnownCache.TryAdd(homeserver, res);
-        _wellKnownSemaphores[homeserver].Release();
+        WellKnownCache.TryAdd(homeserver, res);
+        WellKnownSemaphores[homeserver].Release();
         return res;
     }
 
@@ -40,7 +40,9 @@ public class HomeserverResolverService(ILogger<HomeserverResolverService>? logge
             var hs = resp.GetProperty("m.homeserver").GetProperty("base_url").GetString();
             return hs;
         }
-        catch { }
+        catch {
+            // ignored
+        }
 
         logger?.LogInformation("No client well-known...");
         return null;
@@ -51,11 +53,14 @@ public class HomeserverResolverService(ILogger<HomeserverResolverService>? logge
         try {
             var resp = await _httpClient.GetFromJsonAsync<JsonElement>($"{homeserver}/.well-known/matrix/server");
             var hs = resp.GetProperty("m.server").GetString();
+            if(hs is null) throw new InvalidDataException("m.server is null");
             if (!hs.StartsWithAnyOf("http://", "https://"))
                 hs = $"https://{hs}";
             return hs;
         }
-        catch { }
+        catch {
+            // ignored
+        }
 
         // fallback: most servers host these on the same location
         var clientUrl = await _tryResolveFromClientWellknown(homeserver);