|
| 1 | +using OpenShock.RepositoryServer.Config; |
| 2 | +using OpenShock.RepositoryServer.Enums; |
| 3 | +using OpenShock.RepositoryServer.Utils; |
| 4 | +using System.Net; |
| 5 | + |
| 6 | +namespace OpenShock.RepositoryServer.Services; |
| 7 | + |
| 8 | +/// <param name="Url">The URL that was probed, as it would be advertised to a hub.</param> |
| 9 | +/// <param name="Status">HTTP status observed, or null if the request never got one.</param> |
| 10 | +/// <param name="Detail">Why it failed, for the problem response and the log.</param> |
| 11 | +public sealed record UnreachableArtifact(string Url, HttpStatusCode? Status, string Detail); |
| 12 | + |
| 13 | +/// <summary> |
| 14 | +/// Checks that published artifacts are actually retrievable at the URLs the server hands out. |
| 15 | +/// </summary> |
| 16 | +/// <remarks> |
| 17 | +/// Writing to storage and advertising a URL are two independent facts here: the server uploads |
| 18 | +/// through <see cref="IStorageService"/> and builds URLs from <c>Firmware:CdnBaseUrl</c>, and |
| 19 | +/// nothing has ever tied the two together. An instance whose storage is not the storage behind that |
| 20 | +/// hostname — a Local backend on a deployment that advertises a CDN, or a bucket the CDN is not |
| 21 | +/// fronting — uploads every artifact successfully, publishes successfully, and serves a version |
| 22 | +/// whose every download is a 404. |
| 23 | +/// |
| 24 | +/// That state is invisible from the API. The version lists, the artifact hashes are correct, the |
| 25 | +/// sizes are right; only a client actually fetching the bytes finds out, and the clients here are |
| 26 | +/// hubs applying an OTA update. So the check belongs at publish, where it can still refuse. |
| 27 | +/// </remarks> |
| 28 | +public sealed class PublishedArtifactVerifier |
| 29 | +{ |
| 30 | + private readonly HttpClient _http; |
| 31 | + private readonly ApiConfig _config; |
| 32 | + private readonly ILogger<PublishedArtifactVerifier> _logger; |
| 33 | + |
| 34 | + public PublishedArtifactVerifier( |
| 35 | + HttpClient http, ApiConfig config, ILogger<PublishedArtifactVerifier> logger) |
| 36 | + { |
| 37 | + _http = http; |
| 38 | + _config = config; |
| 39 | + _logger = logger; |
| 40 | + } |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Probes every artifact of a release. Returns the ones that could not be retrieved; an empty |
| 44 | + /// list means every artifact answered 200. |
| 45 | + /// </summary> |
| 46 | + /// <remarks> |
| 47 | + /// Probes run concurrently — a release is up to five artifacts per board across a dozen boards, |
| 48 | + /// and doing that serially would add real latency to every publish. |
| 49 | + /// |
| 50 | + /// A freshly written object can take a moment to become visible at the edge, so a miss is |
| 51 | + /// retried a few times before it counts. The retry is deliberately short: it exists to absorb |
| 52 | + /// propagation, not to wait out a misconfiguration, which will never resolve no matter how long |
| 53 | + /// the publish blocks. |
| 54 | + /// </remarks> |
| 55 | + public async Task<IReadOnlyList<UnreachableArtifact>> FindUnreachableAsync( |
| 56 | + string version, |
| 57 | + IEnumerable<(Guid BoardId, FirmwareArtifactType Type)> artifacts, |
| 58 | + CancellationToken ct = default) |
| 59 | + { |
| 60 | + if (!_config.Firmware.VerifyPublishedArtifacts) |
| 61 | + { |
| 62 | + return []; |
| 63 | + } |
| 64 | + |
| 65 | + var cdnBase = _config.Firmware.CdnBaseUrl.TrimEnd('/'); |
| 66 | + |
| 67 | + var probes = artifacts |
| 68 | + .Select(a => FirmwareArtifactFileNames.BuildUrl(cdnBase, version, a.BoardId, a.Type)) |
| 69 | + .Distinct() |
| 70 | + .Select(url => ProbeAsync(url, ct)); |
| 71 | + |
| 72 | + var results = await Task.WhenAll(probes); |
| 73 | + |
| 74 | + return results.Where(r => r is not null).Select(r => r!).ToList(); |
| 75 | + } |
| 76 | + |
| 77 | + private async Task<UnreachableArtifact?> ProbeAsync(string url, CancellationToken ct) |
| 78 | + { |
| 79 | + const int attempts = 3; |
| 80 | + UnreachableArtifact? last = null; |
| 81 | + |
| 82 | + for (var attempt = 1; attempt <= attempts; attempt++) |
| 83 | + { |
| 84 | + if (attempt > 1) |
| 85 | + { |
| 86 | + await Task.Delay(TimeSpan.FromSeconds(2 * (attempt - 1)), ct); |
| 87 | + } |
| 88 | + |
| 89 | + try |
| 90 | + { |
| 91 | + // HEAD, because the body is not wanted and some of these are megabytes. A store that |
| 92 | + // refuses HEAD reports 405, which is treated as reachable below rather than as a |
| 93 | + // failed publish - the object is evidently there, the method is not supported. |
| 94 | + using var request = new HttpRequestMessage(HttpMethod.Head, url); |
| 95 | + using var response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct); |
| 96 | + |
| 97 | + if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.MethodNotAllowed) |
| 98 | + { |
| 99 | + return null; |
| 100 | + } |
| 101 | + |
| 102 | + last = new UnreachableArtifact(url, response.StatusCode, DescribeStatus(response.StatusCode)); |
| 103 | + } |
| 104 | + catch (HttpRequestException ex) |
| 105 | + { |
| 106 | + last = new UnreachableArtifact(url, null, $"request failed: {ex.Message}"); |
| 107 | + } |
| 108 | + catch (TaskCanceledException) when (!ct.IsCancellationRequested) |
| 109 | + { |
| 110 | + last = new UnreachableArtifact(url, null, "timed out"); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + _logger.LogError( |
| 115 | + "Published artifact is not retrievable at {Url}: {Detail}", last!.Url, last.Detail); |
| 116 | + |
| 117 | + return last; |
| 118 | + } |
| 119 | + |
| 120 | + private static string DescribeStatus(HttpStatusCode status) => status switch |
| 121 | + { |
| 122 | + HttpStatusCode.NotFound => |
| 123 | + "not found - the storage this server writes to is not the storage behind Firmware:CdnBaseUrl", |
| 124 | + HttpStatusCode.Forbidden or HttpStatusCode.Unauthorized => |
| 125 | + "access denied - the artifact exists but is not publicly readable", |
| 126 | + _ => $"unexpected status {(int)status}" |
| 127 | + }; |
| 128 | +} |
0 commit comments