about summary refs log tree commit diff
path: root/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/BaseWellKnownResolver.cs
blob: cbe5b0aa281b214c970b6acb0cc92ae0938fcdf4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System.Diagnostics;
using System.Net.Http.Json;
using ArcaneLibs.Collections;
using LibMatrix.Extensions;

namespace LibMatrix.Services.WellKnownResolver.WellKnownResolvers;

public class BaseWellKnownResolver<T> where T : class, new() {
    internal static readonly SemaphoreCache<WellKnownResolverService.WellKnownResolutionResult<T>> WellKnownCache = new() {
        StoreNulls = false
    };

    internal static readonly MatrixHttpClient HttpClient = new();
    
    internal async Task<WellKnownResolverService.WellKnownResolutionResult<T>> TryGetWellKnownFromUrl(string url,
        WellKnownResolverService.WellKnownSource source) {
        var sw = Stopwatch.StartNew();
        try {
            var request = await HttpClient.GetAsync(url);
            sw.Stop();
            var result = new WellKnownResolverService.WellKnownResolutionResult<T> {
                Content = await request.Content.ReadFromJsonAsync<T>(),
                Source = source,
                SourceUri = url,
                Warnings = []
            };

            if (sw.ElapsedMilliseconds > 1000) {
                // logger.LogWarning($"Support well-known resolution took {sw.ElapsedMilliseconds}ms: {url}");
                result.Warnings.Add(new() {
                    Type = WellKnownResolverService.WellKnownResolutionWarning.WellKnownResolutionWarningType.SlowResponse,
                    Message = $"Well-known resolution took {sw.ElapsedMilliseconds}ms"
                });
            }

            return result;
        }
        catch (Exception e) {
            return new WellKnownResolverService.WellKnownResolutionResult<T> {
                Source = source,
                SourceUri = url,
                Warnings = [
                    new() {
                        Exception = e,
                        Type = WellKnownResolverService.WellKnownResolutionWarning.WellKnownResolutionWarningType.Exception,
                        Message = e.Message
                    }
                ]
            };
        }
    }
}