tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Add a remote cache
- Commit
f58309591c3e31d24d26749eec193cc5b5263dd0- Author
- Leitwolf11 ·
- Parents
5cb8d92220a7
Changes
.github/workflows/ci.yml | 7 + CHANGELOG.md | 6 + docs/README.md | 1 + docs/project-files.md | 4 +- docs/remote-cache.md | 51 ++++ .../Module/Prelude/ModuleDsl.cs | 4 +- src/Progmasoft.Tazel/Cache/ActionResultMessage.cs | 271 ++++++++++++++++++ src/Progmasoft.Tazel/Cache/RemoteActions.cs | 290 +++++++++++++++++++ src/Progmasoft.Tazel/Cache/RemoteCache.cs | 141 ++++++++++ src/Progmasoft.Tazel/Cli/Commands.cs | 15 +- src/Progmasoft.Tazel/Driver/Executor.cs | 101 ++++--- src/Progmasoft.Tazel/Project/ScriptHost.cs | 3 +- tests/Progmasoft.Tazel.Tests/RemoteCacheTests.cs | 308 +++++++++++++++++++++ 13 files changed, 1158 insertions(+), 44 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 09a96bf..171e4cb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -261,6 +261,13 @@ jobs: dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed --filter-class Progmasoft.Tazel.Tests.QueryTests + - name: Test RemoteCacheTests (macOS) + if: runner.os == 'macOS' + timeout-minutes: 10 + run: >- + dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed + --filter-class Progmasoft.Tazel.Tests.RemoteCacheTests + - name: Test SnapshotTests (macOS) if: runner.os == 'macOS' timeout-minutes: 10 diff --git a/CHANGELOG.md b/CHANGELOG.md index 2099e26..bd960d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ ## Unreleased +- A remote cache: `Cache.Remote` takes results of actions from a cache that speaks Bazel's HTTP protocol, such as + bazel-remote, and gives it the results of actions run here. Keys do not depend on where the module is; headers a + compiler found are checked by digest before a result is taken, and every file by its SHA-256. A cache that cannot + be reached is said once, and the build goes on. +- Project files import `System`, so `Environment.GetEnvironmentVariable` works as the examples write it. + The first version of Tazel, written in C# for .NET 10. - Project files are C# scripts: `MODULE.csx` at the root of a module, `BUILD.csx` in each package, run with the C# diff --git a/docs/README.md b/docs/README.md index c0b606c..be8a1e4 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,6 +7,7 @@ | --- | --- | | [Project files](project-files.md) | `MODULE.csx`, `BUILD.csx` and toolchains, with every setting | | [Plugins](plugins.md) | making, packing and loading plugins, and their build steps | +| [Remote cache](remote-cache.md) | sharing the results of actions between machines through a cache that speaks Bazel's HTTP protocol | | [MicroVM](microvm.md) | the sandbox: what tazel custom runs in, what it needs, and building its image | | [Commands](commands.md) | the commands of `tazel`, their options, and `tazel_options.txt`, `tazel_custom.txt` and `tazel_envs.txt` | | [Architecture](architecture.md) | the projects of the solution and how a build runs | diff --git a/docs/project-files.md b/docs/project-files.md index 336f8ec..146d9ff 100644 --- a/docs/project-files.md +++ b/docs/project-files.md @@ -54,8 +54,8 @@ toolchains = Toolchains.Define("//toolchains:clang"); Its public targets are `@name//dir:x`. `Module.From`, a module of Tazel Portal Modules, is refused by this Tazel, which fetches nothing. - `plugins` loads local plugin archives ([Plugins](plugins.md)). -- This Tazel reads `Cache.Remote`, `Execution.Remote` and `Execution.Memory` and says, as a warning, that it does not - act on them. +- `Cache.Remote` is a remote cache ([Remote cache](remote-cache.md)). This Tazel reads the `PublicKey` and + `SigningKey` of it, `Execution.Remote` and `Execution.Memory` and says, as a warning, that it does not act on them. ## BUILD.csx diff --git a/docs/remote-cache.md b/docs/remote-cache.md new file mode 100644 index 0000000..c0472a9 --- /dev/null +++ b/docs/remote-cache.md @@ -0,0 +1,51 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# Remote cache + +A remote cache keeps the outputs of actions so that another machine, or another checkout on the same one, takes them +instead of running the compiler again. Tazel speaks Bazel's HTTP caching protocol, so a cache such as +[bazel-remote](https://github.com/buchgr/bazel-remote) serves it. + +```cs +cache = Cache.Define(new() { + Remote = Remote.From("https://cache.example.com", new() { + Read = true, // default: true + Write = Environment.GetEnvironmentVariable("CI") == "true", // default: false + Token = Environment.GetEnvironmentVariable("TAZEL_CACHE_TOKEN") + }) +}); +``` + +- The URL is `https`; `http` only for a cache on this machine (`localhost`, `127.0.0.1`, `[::1]`). +- `Token` goes in the `Authorization` header. One that starts with `Basic ` or `Bearer ` is sent as it is, so a cache + behind HTTP basic authentication takes `Basic ` and the base64 of `user:password`; any other token is sent as + `Bearer <token>`. +- `Read` takes results from the cache before an action runs; `Write` gives it the results of actions that ran here. + A machine that only reads, such as a pull request build, never writes. + +## What is shared + +An action's key is the SHA-256 of what decides its outputs on any machine: the platform Tazel runs on, the command +line, the digest of the program it runs, its environment without `HOME`, `TMPDIR`, `TMP` and `TEMP`, and the path and +digest of each input it declares. The directory the module is in is not part of it: the commands of Tazel name files +relative to the module, so two checkouts share their results. + +Under that key the cache keeps an `ActionResult` of the Remote Execution API, at `/ac/<key>`, with each output and +the depfile at `/cas/<sha256>`. The headers a compiler finds by itself are known only after it ran; Tazel stores +them, each with its digest, as one more file of the result. A result is taken only when every one of those headers +has here the digest it had where it was made, so a header that differs makes the action run. + +Each file is checked against its SHA-256 and its size before it is put in place, and a result that would write +outside the module is refused. Steps of plugins run in Tazel itself and are never taken from the cache. + +## When the cache is not there + +A cache that cannot be reached, or answers with an error, is said once as a warning, and the build goes on without +it. A build never fails because of its remote cache. + +## What it does not do + +The results are not signed: whoever may write to the cache decides what readers take. Give `Write` and its token only +to machines you trust, such as the builds of the default branch. `PublicKey` and `SigningKey` are read and not acted +on. diff --git a/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs b/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs index f6132e5..2c6d3c2 100644 --- a/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs +++ b/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs @@ -197,7 +197,9 @@ public sealed class Remote public static Remote From(string url, RemoteSettings settings) { ArgumentNullException.ThrowIfNull(settings); - if (!Uri.TryCreate(url, UriKind.Absolute, out var parsed) || parsed.Scheme != Uri.UriSchemeHttps) + // http only for a service on this machine, such as a cache beside the build. + if (!Uri.TryCreate(url, UriKind.Absolute, out var parsed) || + !(parsed.Scheme == Uri.UriSchemeHttps || (parsed.Scheme == Uri.UriSchemeHttp && parsed.IsLoopback))) { throw new DslException($"'{url}' is not an https URL"); } diff --git a/src/Progmasoft.Tazel/Cache/ActionResultMessage.cs b/src/Progmasoft.Tazel/Cache/ActionResultMessage.cs new file mode 100644 index 0000000..9242e2c --- /dev/null +++ b/src/Progmasoft.Tazel/Cache/ActionResultMessage.cs @@ -0,0 +1,271 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace Progmasoft.Tazel.Cache; + +/// <summary>A file of a cached result: where it goes, the SHA-256 and size of its bytes, and whether it runs.</summary> +internal sealed record OutputFile(string Path, string Hash, long Size, bool IsExecutable); + +/// <summary> +/// The part of the Remote Execution API's <c>ActionResult</c> that Tazel writes to and reads from the action cache of a +/// remote cache: its output files (field 2) and its exit code (field 4). The cache keeps it as the protocol buffer the +/// API defines, so a cache that checks what it is given, such as bazel-remote, takes it. +/// </summary> +internal static class ActionResultMessage +{ + private const int WireVarint = 0; + private const int WireLength = 2; + + /// <summary>The message of <paramref name="files"/>, with exit code 0.</summary> + public static byte[] Encode(IEnumerable<OutputFile> files) + { + ArgumentNullException.ThrowIfNull(files); + using var message = new MemoryStream(); + foreach (var file in files) + { + using var digest = new MemoryStream(); + WriteString(digest, 1, file.Hash); + WriteVarintField(digest, 2, (ulong)file.Size); + + using var output = new MemoryStream(); + WriteString(output, 1, file.Path); + WriteBytes(output, 2, digest.ToArray()); + if (file.IsExecutable) + { + WriteVarintField(output, 4, 1); + } + + WriteBytes(message, 2, output.ToArray()); + } + + return message.ToArray(); + } + + /// <summary>The output files of <paramref name="bytes"/>; null when it is not a message Tazel can use.</summary> + public static List<OutputFile>? Decode(ReadOnlySpan<byte> bytes) + { + if (Fields(bytes) is not { } fields) + { + return null; + } + + var files = new List<OutputFile>(); + foreach (var field in fields) + { + // A result that did not exit with 0 is not one Tazel caches. + if (field is { Number: 4, Wire: WireVarint } && field.Value != 0) + { + return null; + } + + if (field is { Number: 2, Wire: WireLength }) + { + if (DecodeOutput(field.Body!) is not { } file) + { + return null; + } + + files.Add(file); + } + } + + return files; + } + + private static OutputFile? DecodeOutput(byte[] bytes) + { + string? path = null, hash = null; + long size = -1; + var executable = false; + foreach (var field in Fields(bytes) ?? [new Field(0, -1, 0, null)]) + { + switch (field) + { + case { Number: 1, Wire: WireLength }: + path = Encoding.UTF8.GetString(field.Body!); + break; + case { Number: 2, Wire: WireLength }: + (hash, size) = DecodeDigest(field.Body!); + break; + case { Number: 4, Wire: WireVarint }: + executable = field.Value != 0; + break; + case { Wire: -1 }: + return null; + default: + break; + } + } + + return path is null || hash is null || size < 0 ? null : new OutputFile(path, hash, size, executable); + } + + /// <summary>The hash and size of a <c>Digest</c>; a null hash when it is not one.</summary> + private static (string? Hash, long Size) DecodeDigest(byte[] bytes) + { + string? hash = null; + long size = 0; + foreach (var field in Fields(bytes) ?? []) + { + if (field is { Number: 1, Wire: WireLength }) + { + hash = Encoding.ASCII.GetString(field.Body!); + } + else if (field is { Number: 2, Wire: WireVarint, Value: <= long.MaxValue }) + { + size = (long)field.Value; + } + } + + return (hash is { Length: 64 } ? hash : null, size); + } + + /// <summary>One field of a message: its number, its wire type, and its value or its bytes.</summary> + private sealed record Field(int Number, int Wire, ulong Value, byte[]? Body); + + /// <summary>The fields of a message in order; null when it runs past its end or has a wire type Tazel does not read.</summary> + private static List<Field>? Fields(ReadOnlySpan<byte> bytes) + { + var fields = new List<Field>(); + var reader = new Reader(bytes); + while (!reader.AtEnd) + { + if (!reader.TryTag(out var number, out var wire)) + { + return null; + } + + if (wire == WireLength && reader.TryLength(out var body)) + { + fields.Add(new Field(number, wire, 0, body.ToArray())); + } + else if (wire == WireVarint && reader.TryVarint(out var value)) + { + fields.Add(new Field(number, wire, value, null)); + } + else if (wire is WireLength or WireVarint || !reader.TrySkip(wire)) + { + return null; + } + } + + return fields; + } + + private static void WriteTag(Stream stream, int field, int wire) => WriteVarint(stream, (ulong)((field << 3) | wire)); + + private static void WriteVarintField(Stream stream, int field, ulong value) + { + WriteTag(stream, field, WireVarint); + WriteVarint(stream, value); + } + + private static void WriteString(Stream stream, int field, string text) => WriteBytes(stream, field, Encoding.UTF8.GetBytes(text)); + + private static void WriteBytes(Stream stream, int field, byte[] bytes) + { + WriteTag(stream, field, WireLength); + WriteVarint(stream, (ulong)bytes.Length); + stream.Write(bytes); + } + + private static void WriteVarint(Stream stream, ulong value) + { + while (value >= 0x80) + { + stream.WriteByte((byte)(value | 0x80)); + value >>= 7; + } + + stream.WriteByte((byte)value); + } + + /// <summary>Reads protocol buffer fields, refusing anything that runs past the end.</summary> + private ref struct Reader(ReadOnlySpan<byte> bytes) + { + private readonly ReadOnlySpan<byte> _bytes = bytes; + private int _at; + + public readonly bool AtEnd => _at >= _bytes.Length; + + public bool TryTag(out int field, out int wire) + { + field = wire = 0; + if (!TryVarint(out var tag) || tag >> 3 is 0 or > int.MaxValue) + { + return false; + } + + field = (int)(tag >> 3); + wire = (int)(tag & 7); + return true; + } + + public bool TryVarint(out ulong value) + { + value = 0; + for (var shift = 0; shift < 64; shift += 7) + { + if (_at >= _bytes.Length) + { + return false; + } + + var next = _bytes[_at++]; + value |= (ulong)(next & 0x7F) << shift; + if ((next & 0x80) == 0) + { + return true; + } + } + + return false; + } + + public bool TryLength(out ReadOnlySpan<byte> body) + { + body = default; + if (!TryVarint(out var length) || length > (ulong)(_bytes.Length - _at)) + { + return false; + } + + body = _bytes.Slice(_at, (int)length); + _at += (int)length; + return true; + } + + public bool TrySkip(int wire) + { + switch (wire) + { + case WireVarint: + return TryVarint(out _); + case WireLength: + return TryLength(out _); + case 1: + return Advance(8); + case 5: + return Advance(4); + default: + return false; + } + } + + private bool Advance(int count) + { + if (count > _bytes.Length - _at) + { + return false; + } + + _at += count; + return true; + } + } +} diff --git a/src/Progmasoft.Tazel/Cache/RemoteActions.cs b/src/Progmasoft.Tazel/Cache/RemoteActions.cs new file mode 100644 index 0000000..df48bfb --- /dev/null +++ b/src/Progmasoft.Tazel/Cache/RemoteActions.cs @@ -0,0 +1,290 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Driver; + +namespace Progmasoft.Tazel.Cache; + +/// <summary> +/// Takes the results of actions from a remote cache, and gives it the results of actions run here. +/// </summary> +/// <remarks> +/// <para> +/// The key of an action is the SHA-256 of what decides its outputs on any machine: the platform Tazel runs on, the +/// command, the digest of the program it runs, the environment without the variables that only name this user's +/// directories, and the path and digest of each input it declares. The directory it runs in is not part of it, so two +/// checkouts of a module share their results. +/// </para> +/// <para> +/// The inputs a compiler finds by itself, such as headers, are known only after it ran. Tazel stores them with the +/// result, each with its digest, as a file of the result named <see cref="DiscoveredInputs"/>; a result is taken only +/// when every one of them has here the digest it had there. Each file is checked against its SHA-256 and size before it +/// is put in place, and a result whose paths would leave the action's directory is refused. +/// </para> +/// <para> +/// A cache that cannot be reached or answers with an error is said once, and the build goes on without it. +/// </para> +/// </remarks> +internal sealed class RemoteActions(RemoteCache cache, bool read, bool write, Digests digests, Action<string> warn) +{ + /// <summary>The name, in a result, of the list of the inputs the action found by itself.</summary> + public const string DiscoveredInputs = "@tazel/discovered-inputs"; + + private static readonly HashSet<string> UserDirectories = new(StringComparer.Ordinal) { "HOME", "TMPDIR", "TMP", "TEMP" }; + + private int _broken; + + /// <summary>Whether results of actions run here are given to the cache.</summary> + public bool Writes => write && Volatile.Read(ref _broken) == 0; + + private bool Reads => read && Volatile.Read(ref _broken) == 0; + + /// <summary>The key of <paramref name="action"/>, or null when one of its declared inputs cannot be read.</summary> + public string? KeyOf(BuildAction action) + { + ArgumentNullException.ThrowIfNull(action); + var text = new StringBuilder("tazel action 1\n") + .Append(RuntimeInformation.OSDescription.Split(' ')[0]).Append('-').Append(RuntimeInformation.OSArchitecture) + .Append('\n'); + foreach (var part in action.Command) + { + text.Append(part).Append('\0'); + } + + text.Append('\u0001').Append(Path.IsPathFullyQualified(action.Command[0]) ? digests.Of(action.Command[0]) : "") + .Append('\u0001'); + foreach (var (name, value) in action.Environment.Where(entry => !UserDirectories.Contains(entry.Key)) + .OrderBy(entry => entry.Key, StringComparer.Ordinal)) + { + text.Append(name).Append('=').Append(value).Append('\0'); + } + + text.Append('\u0001'); + foreach (var input in action.Inputs.Order(StringComparer.Ordinal)) + { + if (digests.Of(action.Full(input)) is not { } digest) + { + return null; + } + + text.Append(Portable(input)).Append('\0').Append(digest).Append('\0'); + } + + return Digests.Sha256(Encoding.UTF8.GetBytes(text.ToString())); + } + + /// <summary> + /// Puts the outputs of <paramref name="action"/> in place from the cache; false when the cache has no result for it + /// that holds here. + /// </summary> + public async Task<bool> FetchAsync(BuildAction action, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(action); + if (!Reads || action.Work is not null || KeyOf(action) is not { } key) + { + return false; + } + + try + { + return await FetchAsync(action, key, cancel).ConfigureAwait(false); + } + catch (Exception error) when (IsCacheTrouble(error, cancel)) + { + Broken(error); + return false; + } + } + + /// <summary>Gives the cache the outputs of <paramref name="action"/>, which just succeeded here.</summary> + public async Task StoreAsync(BuildAction action, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(action); + if (!Writes || action.Work is not null || KeyOf(action) is not { } key) + { + return; + } + + try + { + await StoreAsync(action, key, cancel).ConfigureAwait(false); + } + catch (Exception error) when (IsCacheTrouble(error, cancel)) + { + Broken(error); + } + } + + private async Task<bool> FetchAsync(BuildAction action, string key, CancellationToken cancel) + { + if (await cache.GetActionAsync(key, cancel).ConfigureAwait(false) is not { } message || + ActionResultMessage.Decode(message) is not { } files) + { + return false; + } + + var byPath = new Dictionary<string, OutputFile>(StringComparer.Ordinal); + foreach (var file in files) + { + if (file.Path != DiscoveredInputs && !IsInside(file.Path)) + { + return false; + } + + byPath[file.Path] = file; + } + + var wanted = Wanted(action).Select(Portable).ToList(); + if (!wanted.All(byPath.ContainsKey) || !byPath.TryGetValue(DiscoveredInputs, out var list) || + !await DiscoveredInputsHoldAsync(action, list, cancel).ConfigureAwait(false)) + { + return false; + } + + foreach (var path in wanted) + { + if (!await DownloadAsync(action, byPath[path], cancel).ConfigureAwait(false)) + { + return false; + } + } + + return true; + } + + /// <summary>Whether every input the action found by itself there has here the digest it had there.</summary> + private async Task<bool> DiscoveredInputsHoldAsync(BuildAction action, OutputFile list, CancellationToken cancel) + { + if (list.Size > 16 * 1024 * 1024 || + await cache.GetContentAsync(list.Hash, cancel).ConfigureAwait(false) is not { } bytes || + Digests.Sha256(bytes) != list.Hash) + { + return false; + } + + foreach (var line in Encoding.UTF8.GetString(bytes).Split('\n', StringSplitOptions.RemoveEmptyEntries)) + { + if (line.Length < 66 || line[64] != ' ' || digests.Of(action.Full(line[65..])) != line[..64]) + { + return false; + } + } + + return true; + } + + private async Task<bool> DownloadAsync(BuildAction action, OutputFile file, CancellationToken cancel) + { + var destination = action.Full(file.Path); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + var partial = destination + ".remote"; + try + { + var stream = new FileStream(partial, FileMode.Create, FileAccess.ReadWrite, FileShare.None); + await using (stream.ConfigureAwait(false)) + { + if (!await cache.GetContentAsync(file.Hash, stream, cancel).ConfigureAwait(false) || stream.Length != file.Size) + { + return false; + } + + stream.Position = 0; + if (Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, cancel).ConfigureAwait(false)) != file.Hash) + { + return false; + } + } + + if (file.IsExecutable && !OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(partial, File.GetUnixFileMode(partial) | UnixFileMode.UserExecute | + UnixFileMode.GroupExecute | UnixFileMode.OtherExecute); + } + + File.Move(partial, destination, overwrite: true); + digests.Forget(destination); + return true; + } + finally + { + File.Delete(partial); + } + } + + private async Task StoreAsync(BuildAction action, string key, CancellationToken cancel) + { + var files = new List<OutputFile>(); + foreach (var output in Wanted(action)) + { + var full = action.Full(output); + digests.Forget(full); + if (digests.Of(full) is not { } hash) + { + return; + } + + var executable = !OperatingSystem.IsWindows() && + (File.GetUnixFileMode(full) & UnixFileMode.UserExecute) != 0; + files.Add(new OutputFile(Portable(output), hash, new FileInfo(full).Length, executable)); + if (!await cache.HasContentAsync(hash, cancel).ConfigureAwait(false)) + { + await cache.PutContentAsync(hash, full, cancel).ConfigureAwait(false); + } + } + + var list = new StringBuilder(); + var found = action.Depfile is { } depfile && File.Exists(action.Full(depfile)) + ? Depfiles.Inputs(await File.ReadAllTextAsync(action.Full(depfile), cancel).ConfigureAwait(false)) + : []; + foreach (var input in found.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)) + { + if (digests.Of(action.Full(input)) is not { } digest) + { + return; + } + + list.Append(digest).Append(' ').Append(input).Append('\n'); + } + + var bytes = Encoding.UTF8.GetBytes(list.ToString()); + var listHash = Digests.Sha256(bytes); + await cache.PutContentAsync(listHash, bytes, cancel).ConfigureAwait(false); + files.Add(new OutputFile(DiscoveredInputs, listHash, bytes.Length, IsExecutable: false)); + await cache.PutActionAsync(key, ActionResultMessage.Encode(files), cancel).ConfigureAwait(false); + } + + /// <summary>The files of a result: the outputs, and the depfile, which the local cache reads after a hit.</summary> + private static IEnumerable<string> Wanted(BuildAction action) => + action.Depfile is { } depfile ? action.Outputs.Append(depfile).Distinct(StringComparer.Ordinal) : action.Outputs; + + /// <summary>A path of an action as a result stores it: relative, with <c>/</c>.</summary> + private static string Portable(string path) => path.Replace('\\', '/'); + + /// <summary>Whether a path of a result stays below the action's directory.</summary> + private static bool IsInside(string path) => + path.Length > 0 && !Path.IsPathRooted(path) && !path.Contains('\\', StringComparison.Ordinal) && + !path.Contains(':', StringComparison.Ordinal) && + path.Split('/').All(part => part.Length > 0 && part != "." && part != ".."); + + private static bool IsCacheTrouble(Exception error, CancellationToken cancel) => + error is HttpRequestException or RemoteCacheException or IOException or UnauthorizedAccessException || + (error is OperationCanceledException && !cancel.IsCancellationRequested); + + private void Broken(Exception error) + { + if (Interlocked.Exchange(ref _broken, 1) == 0) + { + warn($"the remote cache at {cache.Address.Host} cannot be used ({error.Message}); building without it"); + } + } +} diff --git a/src/Progmasoft.Tazel/Cache/RemoteCache.cs b/src/Progmasoft.Tazel/Cache/RemoteCache.cs new file mode 100644 index 0000000..5702619 --- /dev/null +++ b/src/Progmasoft.Tazel/Cache/RemoteCache.cs @@ -0,0 +1,141 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; + +namespace Progmasoft.Tazel.Cache; + +/// <summary> +/// The HTTP side of a remote cache, as Bazel's HTTP caching protocol lays it out and bazel-remote serves it: action +/// results at <c>/ac/<sha256></c> and file contents at <c>/cas/<sha256></c>, read with GET and HEAD and written +/// with PUT. +/// </summary> +internal sealed class RemoteCache : IDisposable +{ + private readonly HttpClient _http; + private readonly string _base; + + /// <summary> + /// The cache at <paramref name="address"/>. A <paramref name="token"/> that starts with <c>Basic </c> or + /// <c>Bearer </c> is sent as it is in <c>Authorization</c>; any other is sent as a bearer token. + /// </summary> + public RemoteCache(Uri address, string? token, HttpMessageHandler? handler = null) + { + ArgumentNullException.ThrowIfNull(address); + if (address.Scheme != Uri.UriSchemeHttps && !address.IsLoopback) + { + throw new ArgumentException($"a remote cache is reached over https only, not {address}", nameof(address)); + } + + Address = address; + _base = address.ToString().TrimEnd('/'); + _http = handler is null ? new HttpClient() : new HttpClient(handler); + _http.Timeout = TimeSpan.FromMinutes(5); + _http.DefaultRequestHeaders.UserAgent.ParseAdd($"tazel/{Cli.Commands.TazelVersion.ToString(3)}"); + if (token is { Length: > 0 }) + { + _http.DefaultRequestHeaders.Authorization = token.StartsWith("Basic ", StringComparison.Ordinal) || + token.StartsWith("Bearer ", StringComparison.Ordinal) + ? AuthenticationHeaderValue.Parse(token) + : new AuthenticationHeaderValue("Bearer", token); + } + } + + public Uri Address { get; } + + /// <summary>The action result stored under <paramref name="key"/>, or null when there is none.</summary> + public Task<byte[]?> GetActionAsync(string key, CancellationToken cancel) => GetAsync($"ac/{key}", cancel); + + /// <summary>Stores <paramref name="message"/> as the action result of <paramref name="key"/>.</summary> + public Task PutActionAsync(string key, byte[] message, CancellationToken cancel) => + PutAsync($"ac/{key}", new ByteArrayContent(message), cancel); + + /// <summary>Whether the cache holds the content <paramref name="hash"/>.</summary> + public async Task<bool> HasContentAsync(string hash, CancellationToken cancel) + { + using var request = new HttpRequestMessage(HttpMethod.Head, $"{_base}/cas/{hash}"); + using var response = await _http.SendAsync(request, cancel).ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.NotFound) + { + return false; + } + + Check(response, "HEAD", $"cas/{hash}"); + return true; + } + + /// <summary>Writes the content <paramref name="hash"/> to <paramref name="destination"/>; false when there is none.</summary> + public async Task<bool> GetContentAsync(string hash, Stream destination, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(destination); + using var response = await _http.GetAsync($"{_base}/cas/{hash}", HttpCompletionOption.ResponseHeadersRead, cancel) + .ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.NotFound) + { + return false; + } + + Check(response, "GET", $"cas/{hash}"); + await response.Content.CopyToAsync(destination, cancel).ConfigureAwait(false); + return true; + } + + /// <summary>Stores the file <paramref name="path"/> as the content <paramref name="hash"/>.</summary> + public async Task PutContentAsync(string hash, string path, CancellationToken cancel) + { + var stream = File.OpenRead(path); + await using (stream.ConfigureAwait(false)) + { + await PutAsync($"cas/{hash}", new StreamContent(stream), cancel).ConfigureAwait(false); + } + } + + /// <summary>Stores <paramref name="bytes"/> as the content <paramref name="hash"/>.</summary> + public Task PutContentAsync(string hash, byte[] bytes, CancellationToken cancel) => + PutAsync($"cas/{hash}", new ByteArrayContent(bytes), cancel); + + /// <summary>The content <paramref name="hash"/>, or null when there is none; for small contents only.</summary> + public Task<byte[]?> GetContentAsync(string hash, CancellationToken cancel) => GetAsync($"cas/{hash}", cancel); + + public void Dispose() => _http.Dispose(); + + private async Task<byte[]?> GetAsync(string path, CancellationToken cancel) + { + using var response = await _http.GetAsync($"{_base}/{path}", cancel).ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.NotFound) + { + return null; + } + + Check(response, "GET", path); + return await response.Content.ReadAsByteArrayAsync(cancel).ConfigureAwait(false); + } + + private async Task PutAsync(string path, HttpContent content, CancellationToken cancel) + { + using (content) + { + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + using var response = await _http.PutAsync($"{_base}/{path}", content, cancel).ConfigureAwait(false); + Check(response, "PUT", path); + } + } + + private void Check(HttpResponseMessage response, string method, string path) + { + if (!response.IsSuccessStatusCode) + { + throw new RemoteCacheException( + $"{method} {Address.Host}/{path} answered {(int)response.StatusCode} {response.ReasonPhrase}"); + } + } +} + +/// <summary>A remote cache answered with an error or could not be reached.</summary> +internal sealed class RemoteCacheException(string message) : Exception(message); diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 614c30b..9fff720 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -99,9 +99,10 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector /// <summary>Says which settings of MODULE.csx this Tazel reads but does not act on, so none is taken for granted.</summary> private void WarnAboutWhatThisTazelDoesNotDo(Dsl.Module.Prelude.ModuleGlobals globals) { - if (globals.cache?.Settings.Remote is { } cache) + if (globals.cache?.Settings.Remote?.Settings is { } cache && (cache.PublicKey is not null || cache.SigningKey is not null)) { - reporter.Warning($"MODULE.csx names the remote cache {cache.Url}; this Tazel uses the cache on this machine only"); + reporter.Warning("MODULE.csx gives the remote cache a PublicKey or a SigningKey; this Tazel neither signs " + + "the results it writes nor checks the ones it reads with them"); } if (globals.execution?.Settings.Remote is { } remote) @@ -286,8 +287,16 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector var goals = planned.Select(entry => entry.Products.Main).OfType<BuildAction>().Distinct().ToList(); reporter.Status($"building {selected.Count} target{(selected.Count == 1 ? "" : "s")}"); var cacheSettings = workspace.Main.Globals.cache?.Settings; + var digests = new Digests(); + using var remoteCache = cacheSettings?.Remote is { } remote + ? new Cache.RemoteCache(remote.Url, remote.Settings.Token) + : null; + var remoteActions = remoteCache is null + ? null + : new Cache.RemoteActions(remoteCache, cacheSettings!.Remote!.Settings.Read, cacheSettings.Remote.Settings.Write, + digests, reporter.Warning); var executor = new Executor(buildOptions.Jobs, buildOptions.KeepGoing || kind is BuildKind.Test or BuildKind.Coverage, - new ActionCache(new Digests(), enabled: cacheSettings?.Local ?? true), reporter); + new ActionCache(digests, enabled: cacheSettings?.Local ?? true), reporter, remoteActions); var succeeded = await executor.RunAsync(goals, cancel).ConfigureAwait(false); return new Built(buildOptions, planner, chooser, executor, succeeded, planned); } diff --git a/src/Progmasoft.Tazel/Driver/Executor.cs b/src/Progmasoft.Tazel/Driver/Executor.cs index d754137..977c156 100644 --- a/src/Progmasoft.Tazel/Driver/Executor.cs +++ b/src/Progmasoft.Tazel/Driver/Executor.cs @@ -16,7 +16,8 @@ namespace Progmasoft.Tazel.Driver; /// action starts unless <c>keepGoing</c> asks for it; those running are let finish, so no compiler is left writing /// behind the back of the command. /// </summary> -internal sealed class Executor(int jobs, bool keepGoing, ActionCache cache, Reporter reporter) +internal sealed class Executor( + int jobs, bool keepGoing, ActionCache cache, Reporter reporter, Cache.RemoteActions? remote = null) { private readonly System.Collections.Concurrent.ConcurrentDictionary<BuildAction, bool> _made = new(); private int _done; @@ -80,42 +81,7 @@ internal sealed class Executor(int jobs, bool keepGoing, ActionCache cache, Repo await slots.WaitAsync(CancellationToken.None).ConfigureAwait(false); try { - if (stop.IsCancellationRequested) - { - return false; - } - - if (cache.IsCurrent(action)) - { - action.After?.Invoke(); - Interlocked.Increment(ref _done); - _made[action] = true; - return true; - } - - foreach (var output in action.Outputs) - { - var full = action.Full(output); - Directory.CreateDirectory(Path.GetDirectoryName(full)!); - File.Delete(full); - } - - cache.Forget(action); - var result = action.Work is { } work - ? await work(stop.Token).ConfigureAwait(false) - : await Processes.RunAsync(action.Command, action.Directory, action.Environment, null, stop.Token) - .ConfigureAwait(false); - // Stopped because another action failed: that one is reported, this one did not fail. - if (result.Canceled || await FailedAsync(action, result, stop).ConfigureAwait(false)) - { - return false; - } - - cache.Record(action); - action.After?.Invoke(); - _made[action] = true; - reporter.ActionDone(Interlocked.Increment(ref _done), total, action.Description, result.Output); - return true; + return !stop.IsCancellationRequested && await MakeAsync(action, total, stop).ConfigureAwait(false); } finally { @@ -124,6 +90,67 @@ internal sealed class Executor(int jobs, bool keepGoing, ActionCache cache, Repo } } + /// <summary> + /// Makes <paramref name="action"/>: it is current here, or the remote cache has its outputs, or it runs, and then the + /// caches record it. + /// </summary> + private async Task<bool> MakeAsync(BuildAction action, int total, CancellationTokenSource stop) + { + if (cache.IsCurrent(action)) + { + action.After?.Invoke(); + Interlocked.Increment(ref _done); + _made[action] = true; + return true; + } + + foreach (var output in action.Outputs) + { + var full = action.Full(output); + Directory.CreateDirectory(Path.GetDirectoryName(full)!); + File.Delete(full); + } + + cache.Forget(action); + if (remote is not null && await remote.FetchAsync(action, stop.Token).ConfigureAwait(false)) + { + Made(action, total, $"{action.Description} (remote cache)", "", record: true); + return true; + } + + var result = action.Work is { } work + ? await work(stop.Token).ConfigureAwait(false) + : await Processes.RunAsync(action.Command, action.Directory, action.Environment, null, stop.Token) + .ConfigureAwait(false); + // Stopped because another action failed: that one is reported, this one did not fail. + if (result.Canceled || await FailedAsync(action, result, stop).ConfigureAwait(false)) + { + return false; + } + + cache.Record(action); + if (remote is { Writes: true }) + { + await remote.StoreAsync(action, stop.Token).ConfigureAwait(false); + } + + Made(action, total, action.Description, result.Output, record: false); + return true; + } + + /// <summary>Marks <paramref name="action"/> made and says so; with <paramref name="record"/>, the local cache records it.</summary> + private void Made(BuildAction action, int total, string description, string output, bool record) + { + if (record) + { + cache.Record(action); + } + + action.After?.Invoke(); + _made[action] = true; + reporter.ActionDone(Interlocked.Increment(ref _done), total, description, output); + } + private static List<BuildAction> Closure(IEnumerable<BuildAction> goals) { var seen = new HashSet<BuildAction>(); diff --git a/src/Progmasoft.Tazel/Project/ScriptHost.cs b/src/Progmasoft.Tazel/Project/ScriptHost.cs index 0b1c3a6..57f556d 100644 --- a/src/Progmasoft.Tazel/Project/ScriptHost.cs +++ b/src/Progmasoft.Tazel/Project/ScriptHost.cs @@ -105,7 +105,8 @@ internal static class ScriptHost return ScriptOptions.Default .WithReferences(references) - .WithImports(CommonNamespace) + // System for what the examples of the project files use, such as Environment.GetEnvironmentVariable. + .WithImports(CommonNamespace, "System") .WithLanguageVersion(LanguageVersion.Latest) .WithOptimizationLevel(OptimizationLevel.Debug) .WithEmitDebugInformation(false) diff --git a/tests/Progmasoft.Tazel.Tests/RemoteCacheTests.cs b/tests/Progmasoft.Tazel.Tests/RemoteCacheTests.cs new file mode 100644 index 0000000..2e588b5 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/RemoteCacheTests.cs @@ -0,0 +1,308 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cache; +using Progmasoft.Tazel.Driver; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class RemoteCacheTests +{ + private const string Build = """ + using Progmasoft.Tazel.Dsl.Build.Prelude; + CC.Executable("app", new() { Sources = ["main.c"] }); + """; + + private static void SkipWithoutCompiler() + { + Assert.SkipWhen(Host.Which("clang") is null && Host.Which("gcc") is null, "no C compiler on PATH"); + Assert.SkipWhen(OperatingSystem.IsWindows() && Environment.GetEnvironmentVariable("INCLUDE") is null, + "no MSVC environment (INCLUDE) for the headers of clang on Windows"); + } + + /// <summary>A module whose main.c includes value.h, which it does not declare, using the cache at <paramref name="url"/>.</summary> + private static TemporaryModule Module(string url, bool write, string value = "42", string? token = "secret") => + new TemporaryModule() + .Write("MODULE.csx", $$""" + using Progmasoft.Tazel.Dsl.Module.Prelude; + module = Module.Define(new() { Group = "com.example", Name = "sample", Version = "0.1.0" }); + cache = Cache.Define(new() { + Remote = Remote.From("{{url}}", new() { Read = true, Write = {{(write ? "true" : "false")}}, Token = {{(token is null ? "null" : $"\"{token}\"")}} }) + }); + """) + .Write("BUILD.csx", Build) + .Write("value.h", $"#define VALUE {value}\n") + .Write("main.c", "#include \"value.h\"\nint main(void) { return VALUE == 42 ? 0 : 1; }\n"); + + [Fact] + public async Task AProjectFileReadsItsTokenFromTheEnvironment() + { + // As the examples write it: Environment without System., which project files import. + using var module = new TemporaryModule() + .Write("MODULE.csx", """ + using Progmasoft.Tazel.Dsl.Module.Prelude; + module = Module.Define(new() { Group = "com.example", Name = "sample", Version = "0.1.0" }); + cache = Cache.Define(new() { + Remote = Remote.From("https://cache.example.com", new() { Token = Environment.GetEnvironmentVariable("TAZEL_TEST_NO_SUCH_TOKEN") }) + }); + """) + .Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\n"); + + var workspace = await module.LoadAsync(); + + Assert.Equal("cache.example.com", workspace.Main.Globals.cache!.Settings.Remote!.Url.Host); + Assert.Null(workspace.Main.Globals.cache!.Settings.Remote!.Settings.Token); + } + + [Fact] + public void AResultIsTheProtocolBufferOfTheRemoteExecutionApi() + { + OutputFile[] files = [new("out/app", new string('a', 64), 1234, true), new("out/app.d", new string('b', 64), 7, false)]; + + var bytes = ActionResultMessage.Encode(files); + + // Field 2, length-delimited: an OutputFile; inside, field 1 is its path. + Assert.Equal(0x12, bytes[0]); + Assert.Equal(files, ActionResultMessage.Decode(bytes)); + Assert.Null(ActionResultMessage.Decode(bytes.AsSpan(0, bytes.Length - 3))); + // An exit code other than 0 (field 4) is not a result Tazel takes. + Assert.Null(ActionResultMessage.Decode([.. bytes, 0x20, 0x01])); + } + + [Fact] + public async Task AnotherCheckoutTakesTheResultsAndRunsNoCompiler() + { + SkipWithoutCompiler(); + using var server = new FakeRemoteCache(); + using var first = Module(server.Address, write: true); + var (status, output) = await first.TazelAsync(".", "build", "//:app"); + Assert.True(status == 0, output); + Assert.NotEmpty(server.Actions); + Assert.All(server.Authorizations, header => Assert.Equal("Bearer secret", header)); + + using var second = Module(server.Address, write: false); + (status, output) = await second.TazelAsync(".", "build", "//:app"); + Assert.True(status == 0, output); + Assert.Contains("Compiling //:app main.c (remote cache)", output, StringComparison.Ordinal); + Assert.Contains("(remote cache)", output.Split('\n').Single(line => line.Contains("Linking", StringComparison.Ordinal)), + StringComparison.Ordinal); + (status, output) = await second.TazelAsync(".", "run", "//:app"); + Assert.True(status == 0, output); + } + + [Fact] + public async Task AHeaderThatDiffersHereIsCompiledAgain() + { + SkipWithoutCompiler(); + using var server = new FakeRemoteCache(); + using var first = Module(server.Address, write: true); + Assert.Equal(0, (await first.TazelAsync(".", "build", "//:app")).Status); + + // The same declared inputs, but value.h, which the compiler found, is not the same. + using var second = Module(server.Address, write: false, value: "41"); + var (status, output) = await second.TazelAsync(".", "build", "//:app"); + Assert.True(status == 0, output); + Assert.DoesNotContain("main.c (remote cache)", output, StringComparison.Ordinal); + (status, _) = await second.TazelAsync(".", "run", "//:app"); + Assert.Equal(1, status); + } + + [Fact] + public async Task ACacheThatCannotBeReachedIsSaidOnceAndTheBuildGoesOn() + { + SkipWithoutCompiler(); + string address; + using (var server = new FakeRemoteCache()) + { + address = server.Address; + } + + using var module = Module(address, write: true); + var (status, output) = await module.TazelAsync(".", "build", "//:app"); + Assert.True(status == 0, output); + Assert.Single(output.Split('\n'), line => line.Contains("cannot be used", StringComparison.Ordinal)); + Assert.Contains("building without it", output, StringComparison.Ordinal); + } + + [Fact] + public async Task AResultWhosePathsLeaveTheActionIsRefused() + { + using var server = new FakeRemoteCache(); + using var module = new TemporaryModule().Write("in.txt", "in\n"); + var action = new BuildAction + { + Description = "Copying", + Command = ["/bin/cp", "in.txt", "out.txt"], + Directory = module.Root, + Inputs = ["in.txt"], + Outputs = ["out.txt"], + }; + var digests = new Digests(); + using var cache = new RemoteCache(new Uri(server.Address), token: null); + var remote = new RemoteActions(cache, read: true, write: false, digests, _ => { }); + var evil = Encoding.UTF8.GetBytes("owned\n"); + var hash = Digests.Sha256(evil); + server.Content[hash] = evil; + var empty = Digests.Sha256([]); + server.Content[empty] = []; + server.Actions[remote.KeyOf(action)!] = ActionResultMessage.Encode([ + new OutputFile("out.txt", hash, evil.Length, false), + new OutputFile("../escaped.txt", hash, evil.Length, false), + new OutputFile(RemoteActions.DiscoveredInputs, empty, 0, false), + ]); + + Assert.False(await remote.FetchAsync(action, Xunit.TestContext.Current.CancellationToken)); + Assert.False(File.Exists(Path.Combine(module.Root, "out.txt"))); + Assert.False(File.Exists(Path.Combine(Path.GetDirectoryName(module.Root)!, "escaped.txt"))); + } + + [Fact] + public async Task ContentThatIsNotWhatItsHashSaysIsRefused() + { + using var server = new FakeRemoteCache(); + using var module = new TemporaryModule().Write("in.txt", "in\n"); + var action = new BuildAction + { + Description = "Copying", + Command = ["/bin/cp", "in.txt", "out.txt"], + Directory = module.Root, + Inputs = ["in.txt"], + Outputs = ["out.txt"], + }; + using var cache = new RemoteCache(new Uri(server.Address), token: "Basic dXNlcjpwYXNz"); + var remote = new RemoteActions(cache, read: true, write: false, new Digests(), _ => { }); + var claimed = Digests.Sha256(Encoding.UTF8.GetBytes("right\n")); + server.Content[claimed] = Encoding.UTF8.GetBytes("wrong\n"); + var empty = Digests.Sha256([]); + server.Content[empty] = []; + server.Actions[remote.KeyOf(action)!] = ActionResultMessage.Encode([ + new OutputFile("out.txt", claimed, 6, false), + new OutputFile(RemoteActions.DiscoveredInputs, empty, 0, false), + ]); + + Assert.False(await remote.FetchAsync(action, Xunit.TestContext.Current.CancellationToken)); + Assert.False(File.Exists(Path.Combine(module.Root, "out.txt"))); + Assert.Contains("Basic dXNlcjpwYXNz", server.Authorizations); + } +} + +/// <summary> +/// A remote cache on this machine, as bazel-remote serves one over HTTP: <c>/ac/</c> takes only messages that decode +/// as an ActionResult, as bazel-remote checks them, and <c>/cas/</c> only content whose SHA-256 is its name. +/// </summary> +internal sealed class FakeRemoteCache : IDisposable +{ + private readonly HttpListener _listener = new(); + private readonly CancellationTokenSource _stop = new(); + + public FakeRemoteCache() + { + using (var socket = new TcpListener(IPAddress.Loopback, 0)) + { + socket.Start(); + Address = $"http://127.0.0.1:{((IPEndPoint)socket.LocalEndpoint).Port}"; + } + + _listener.Prefixes.Add(Address + "/"); + _listener.Start(); + _ = Task.Run(ServeAsync); + } + + public string Address { get; } + + public ConcurrentDictionary<string, byte[]> Actions { get; } = new(StringComparer.Ordinal); + + public ConcurrentDictionary<string, byte[]> Content { get; } = new(StringComparer.Ordinal); + + public ConcurrentBag<string> Authorizations { get; } = []; + + public void Dispose() + { + _stop.Cancel(); + _listener.Close(); + _stop.Dispose(); + } + + private async Task ServeAsync() + { + while (!_stop.IsCancellationRequested) + { + HttpListenerContext context; + try + { + context = await _listener.GetContextAsync(); + } + catch (Exception error) when (error is HttpListenerException or ObjectDisposedException) + { + return; + } + + try + { + await AnswerAsync(context); + } + catch (HttpListenerException) + { + // The client went away. + } + finally + { + context.Response.Close(); + } + } + } + + private async Task AnswerAsync(HttpListenerContext context) + { + Authorizations.Add(context.Request.Headers["Authorization"] ?? ""); + var parts = context.Request.Url!.AbsolutePath.Trim('/').Split('/'); + var store = parts is ["ac", _] ? Actions : parts is ["cas", _] ? Content : null; + if (store is null || parts[1].Length != 64) + { + context.Response.StatusCode = 404; + return; + } + + var key = parts[1]; + switch (context.Request.HttpMethod) + { + case "GET" or "HEAD" when store.TryGetValue(key, out var bytes): + context.Response.StatusCode = 200; + context.Response.ContentLength64 = bytes.Length; + if (context.Request.HttpMethod == "GET") + { + await context.Response.OutputStream.WriteAsync(bytes); + } + + break; + case "PUT": + using (var body = new MemoryStream()) + { + await context.Request.InputStream.CopyToAsync(body); + var bytes = body.ToArray(); + var valid = store == Actions ? ActionResultMessage.Decode(bytes) is not null : Digests.Sha256(bytes) == key; + context.Response.StatusCode = valid ? 200 : 400; + if (valid) + { + store[key] = bytes; + } + } + + break; + default: + context.Response.StatusCode = 404; + break; + } + } +}