// SPDX-FileCopyrightText: 2026 Progmasoft // SPDX-License-Identifier: MIT using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using NuGet.Versioning; using Progmasoft.Tazel.Archive; using Progmasoft.Tazel.Project; namespace Progmasoft.Tazel.Portal; /// A dependency of a version in an index. internal sealed record IndexDependency( [property: JsonPropertyName("group")] string Group, [property: JsonPropertyName("module")] string Module, [property: JsonPropertyName("version")] string Version, [property: JsonPropertyName("test")] bool Test); /// One version in an index. internal sealed record IndexVersion( [property: JsonPropertyName("version")] string Version, [property: JsonPropertyName("pushed")] DateTimeOffset Pushed, [property: JsonPropertyName("yanked")] bool Yanked, [property: JsonPropertyName("dependencies")] IReadOnlyList Dependencies); /// modules.tazel.net/$group/$module/index.json: every version of one module. internal sealed record ModuleIndex( [property: JsonPropertyName("group")] string Group, [property: JsonPropertyName("module")] string Module, [property: JsonPropertyName("versions")] IReadOnlyList Versions); /// One module of modules.tazel.net/index.json, the list that search reads. internal sealed record CatalogEntry( [property: JsonPropertyName("group")] string Group, [property: JsonPropertyName("module")] string Module, [property: JsonPropertyName("description")] string? Description, [property: JsonPropertyName("latest")] string? Latest); /// modules.tazel.net/index.json. internal sealed record Catalog([property: JsonPropertyName("modules")] IReadOnlyList Modules); /// /// The names of Tazel Portal Modules, as the JSON Schema of its index has them. A name becomes a directory below /// vendor/ and .tazel/ and a part of an address, so a name that is not one is refused before it is used: from the /// command line, a project file or an index the server sent. /// internal static partial class PortalNames { /// Throws unless and are names of the portal. public static void Check(string group, string module, string where) { ArgumentNullException.ThrowIfNull(group); ArgumentNullException.ThrowIfNull(module); if (!GroupPattern().IsMatch(group)) { throw new ProjectException($"{where}: '{group}' is not a group: lower-case names joined by dots, such as com.example"); } if (!ModulePattern().IsMatch(module) || module is "." or "..") { throw new ProjectException($"{where}: '{module}' is not the name of a module: letters, digits and _ + . -"); } } /// Throws unless is a SemVer version as the index writes it. public static void CheckVersion(string version, string where) { ArgumentNullException.ThrowIfNull(version); if (!VersionPattern().IsMatch(version)) { throw new ProjectException($"{where}: '{version}' is not a SemVer version"); } } [GeneratedRegex("^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)*$")] private static partial Regex GroupPattern(); [GeneratedRegex("^[A-Za-z0-9_+.-]+$")] private static partial Regex ModulePattern(); [GeneratedRegex("^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?(\\+[0-9A-Za-z.-]+)?$")] private static partial Regex VersionPattern(); } /// /// The client of Tazel Portal Modules, laid out as the Bazel Central Registry is: an index per module, and each version's /// archive with its .sha256sums beside it. The address is https://modules.tazel.net, or /// TAZEL_PORTAL_MODULES_URL. /// internal sealed class PortalModulesClient : IDisposable { public const string DefaultAddress = "https://modules.tazel.net"; private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = false }; private readonly HttpClient _http; private readonly string? _vendor; /// /// A client of the portal at ; with , an index found there is read /// from there instead. /// public PortalModulesClient(Uri? address = null, HttpMessageHandler? handler = null, string? vendor = null) { _vendor = vendor; Address = address ?? new Uri(Environment.GetEnvironmentVariable("TAZEL_PORTAL_MODULES_URL") is { Length: > 0 } set ? set.TrimEnd('/') : DefaultAddress); if (Address.Scheme != Uri.UriSchemeHttps && !Address.IsLoopback) { throw new ProjectException($"Tazel Portal Modules is reached over https only, not {Address}"); } _http = handler is null ? new HttpClient() : new HttpClient(handler); _http.Timeout = TimeSpan.FromMinutes(5); _http.DefaultRequestHeaders.UserAgent.ParseAdd($"tazel/{Cli.Commands.TazelVersion.ToString(3)}"); } public Uri Address { get; } /// The address as text without a closing slash, for the paths below it. private string Base => Address.ToString().TrimEnd('/'); /// The list of every module, for search. public async Task CatalogAsync(CancellationToken cancel) => await GetJsonAsync("index.json", cancel).ConfigureAwait(false) ?? throw new ProjectException($"{Base}/index.json is empty"); /// The index of :, or null when there is no such module. public async Task IndexAsync(string group, string module, CancellationToken cancel) { var text = await IndexTextAsync(group, module, cancel).ConfigureAwait(false); return text is null ? null : Parse(text, $"{group}/{module}/index.json"); } /// The text of an index: from vendor/ when it is there, else from the portal; null for no such module. public async Task IndexTextAsync(string group, string module, CancellationToken cancel) { PortalNames.Check(group, module, "Tazel Portal Modules"); var path = $"{group}/{module}/index.json"; if (_vendor is not null && File.Exists(Path.Combine(_vendor, group, module, "index.json"))) { return await File.ReadAllTextAsync(Path.Combine(_vendor, group, module, "index.json"), cancel).ConfigureAwait(false); } return await GetTextAsync(path, cancel).ConfigureAwait(false); } /// /// Downloads the archive of a version into , checks it against its /// .sha256sums, and returns its path and SHA-256. /// public async Task<(string Archive, string Sha256)> DownloadAsync( string group, string module, string version, string directory, CancellationToken cancel) { PortalNames.Check(group, module, "Tazel Portal Modules"); PortalNames.CheckVersion(version, $"{group}:{module}"); var name = $"{ModuleArchive.BaseName(group, module, version)}{ModuleArchive.Extension}"; var path = $"{group}/{module}/{version}/{name}"; var sums = await GetTextAsync(path + ".sha256sums", cancel).ConfigureAwait(false) ?? throw new ProjectException($"{Base}/{path}.sha256sums is not there"); var expected = Sha256Sums.SumFor(sums, name, $"{path}.sha256sums") ?? throw new ProjectException($"{Base}/{path}.sha256sums does not name {name}"); Directory.CreateDirectory(directory); var file = Path.Combine(directory, name); var partial = file + ".partial"; using (var response = await _http.GetAsync(new Uri($"{Base}/{path}"), HttpCompletionOption.ResponseHeadersRead, cancel) .ConfigureAwait(false)) { if (!response.IsSuccessStatusCode) { throw new ProjectException($"{Base}/{path} answered {(int)response.StatusCode}"); } var output = File.Create(partial); await using (output.ConfigureAwait(false)) { await response.Content.CopyToAsync(output, cancel).ConfigureAwait(false); } } var actual = Sha256Sums.Sha256(partial); if (!string.Equals(actual, expected, StringComparison.Ordinal)) { File.Delete(partial); throw new ProjectException($"{Base}/{path} has the SHA-256 {actual}, and its .sha256sums says {expected}"); } File.Move(partial, file, overwrite: true); await File.WriteAllTextAsync(file + ".sha256sums", $"{actual} {name}\n", cancel).ConfigureAwait(false); return (file, actual); } /// The highest version of by SemVer that is not yanked; a release before any pre-release. public static IndexVersion? Highest(ModuleIndex index) { ArgumentNullException.ThrowIfNull(index); var usable = index.Versions.Where(v => !v.Yanked && NuGetVersion.TryParseStrict(v.Version, out _)) .Select(v => (Entry: v, Version: NuGetVersion.Parse(v.Version))).ToList(); var releases = usable.Where(v => !v.Version.IsPrerelease).ToList(); return (releases.Count > 0 ? releases : usable).OrderByDescending(v => v.Version).Select(v => v.Entry).FirstOrDefault(); } public void Dispose() => _http.Dispose(); private async Task GetJsonAsync(string path, CancellationToken cancel) where T : class { var text = await GetTextAsync(path, cancel).ConfigureAwait(false); return text is null ? null : Parse(text, path); } private T Parse(string text, string path) where T : class { try { return JsonSerializer.Deserialize(text, Json) ?? throw new ProjectException($"{Base}/{path} is empty"); } catch (JsonException error) { throw new ProjectException($"{Base}/{path} is not what Tazel Portal Modules serves: {error.Message}", error); } } private async Task GetTextAsync(string path, CancellationToken cancel) { try { using var response = await _http.GetAsync(new Uri($"{Base}/{path}"), cancel).ConfigureAwait(false); if (response.StatusCode == HttpStatusCode.NotFound) { return null; } if (!response.IsSuccessStatusCode) { throw new ProjectException($"{Base}/{path} answered {(int)response.StatusCode}"); } return await response.Content.ReadAsStringAsync(cancel).ConfigureAwait(false); } catch (HttpRequestException error) { throw new ProjectException($"Tazel Portal Modules at {Address} cannot be reached: {error.Message}", error); } } }