From 99f790eabc1f7461b49f5cf4ee31997781c76cdd Mon Sep 17 00:00:00 2001 From: withakay Date: Wed, 5 Aug 2026 11:46:11 +0100 Subject: [PATCH] chore(code-quality): enforce dotnet formatting and analysis --- .config/dotnet-tools.json | 13 + .config/wt.toml | 6 + .editorconfig | 77 + .githooks/pre-commit | 9 + .github/workflows/ci.yml | 16 +- .pre-commit-config.yaml | 14 + AGENTS.md | 4 + Directory.Build.props | 10 + Microsandbox.slnx | 12 +- docs/agents/dotnet-style-guide.md | 101 + examples/basic.cs | 46 +- examples/detached.cs | 33 +- examples/filesystem.cs | 52 +- examples/metrics.cs | 51 +- examples/patches.cs | 170 +- examples/ports.cs | 43 +- examples/secrets.cs | 76 +- examples/snapshot-fork.cs | 47 +- examples/streaming-exec.cs | 48 +- examples/volumes.cs | 34 +- global.json | 5 + mise.toml | 19 +- scripts/download-runtime.cs | 103 +- scripts/pre-commit-format.sh | 12 + scripts/pre-commit-hook.sh | 9 + src/Microsandbox/Agent.cs | 23 +- src/Microsandbox/ConsumingCloseState.cs | 7 +- src/Microsandbox/ExecOptions.cs | 32 +- src/Microsandbox/ExecStreaming.cs | 27 +- src/Microsandbox/Filesystem.cs | 161 +- src/Microsandbox/Images.cs | 57 +- src/Microsandbox/Logs.cs | 56 +- src/Microsandbox/Metrics.cs | 7 +- src/Microsandbox/Microsandbox.csproj | 50 +- src/Microsandbox/MicrosandboxClient.cs | 49 +- src/Microsandbox/NativeApi.cs | 1969 ++++++++++++----- src/Microsandbox/RetryableCompletionState.cs | 10 +- src/Microsandbox/Sandbox.cs | 85 +- src/Microsandbox/SandboxHandle.cs | 50 +- src/Microsandbox/SandboxLifecycle.cs | 14 +- src/Microsandbox/SandboxModification.cs | 155 +- src/Microsandbox/SandboxOptions.cs | 166 +- src/Microsandbox/Snapshots.cs | 109 +- src/Microsandbox/Ssh.cs | 92 +- src/Microsandbox/Volumes.cs | 38 +- .../Microsandbox.Tests.csproj | 4 - tests/Microsandbox.Tests/SdkTests.cs | 311 ++- 47 files changed, 3190 insertions(+), 1292 deletions(-) create mode 100644 .config/dotnet-tools.json create mode 100644 .config/wt.toml create mode 100644 .editorconfig create mode 100755 .githooks/pre-commit create mode 100644 .pre-commit-config.yaml create mode 100644 Directory.Build.props create mode 100644 docs/agents/dotnet-style-guide.md create mode 100755 scripts/pre-commit-format.sh create mode 100755 scripts/pre-commit-hook.sh diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 0000000..9e028ef --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "csharpier": { + "version": "1.3.0", + "commands": [ + "csharpier" + ], + "rollForward": false + } + } +} diff --git a/.config/wt.toml b/.config/wt.toml new file mode 100644 index 0000000..c1e775d --- /dev/null +++ b/.config/wt.toml @@ -0,0 +1,6 @@ +# Keep Worktrunk merges aligned with ordinary Git commits and CI. +[pre-commit] +format = "bash scripts/pre-commit-hook.sh" + +[pre-merge] +check = "mise run check" diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..ed06674 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,77 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 + +[*.cs] +dotnet_sort_system_directives_first = true +dotnet_separate_import_directive_groups = false +dotnet_style_qualification_for_event = false:error +dotnet_style_qualification_for_field = false:error +dotnet_style_qualification_for_method = false:error +dotnet_style_qualification_for_property = false:error +dotnet_style_predefined_type_for_locals_parameters_members = true:error +dotnet_style_predefined_type_for_member_access = true:error +dotnet_style_require_accessibility_modifiers = for_non_interface_members:error +dotnet_style_readonly_field = true:error +csharp_style_namespace_declarations = file_scoped:error +csharp_using_directive_placement = outside_namespace:error +csharp_new_line_before_open_brace = all +csharp_prefer_braces = true +dotnet_diagnostic.IDE0011.severity = error + +dotnet_naming_rule.private_fields_underscore.symbols = private_fields +dotnet_naming_rule.private_fields_underscore.style = underscore_prefix +dotnet_naming_rule.private_fields_underscore.severity = error + +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private + +dotnet_naming_rule.private_static_fields_pascal.symbols = private_static_fields +dotnet_naming_rule.private_static_fields_pascal.style = pascal_case +dotnet_naming_rule.private_static_fields_pascal.severity = error + +dotnet_naming_rule.interface_prefix.symbols = interfaces +dotnet_naming_rule.interface_prefix.style = interface_prefix +dotnet_naming_rule.interface_prefix.severity = error + +dotnet_naming_rule.types_pascal_case.symbols = types +dotnet_naming_rule.types_pascal_case.style = pascal_case +dotnet_naming_rule.types_pascal_case.severity = error + +dotnet_naming_rule.non_field_members_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_pascal_case.style = pascal_case +dotnet_naming_rule.non_field_members_pascal_case.severity = error + +dotnet_naming_symbols.private_static_fields.applicable_kinds = field +dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private +dotnet_naming_symbols.private_static_fields.required_modifiers = static + +dotnet_naming_symbols.interfaces.applicable_kinds = interface +dotnet_naming_symbols.interfaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected + +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.interface_prefix.required_prefix = I +dotnet_naming_style.interface_prefix.capitalization = pascal_case + +dotnet_naming_style.underscore_prefix.required_prefix = _ +dotnet_naming_style.underscore_prefix.capitalization = camel_case + +# These names describe public streaming handles, and the semaphore fields are +# synchronization gates whose lifetime is bounded by their disposable owners. +dotnet_diagnostic.CA1001.severity = none +dotnet_diagnostic.CA1711.severity = none + +[*.{csproj,props,targets}] +indent_size = 2 diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..a6a7f49 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail + +mapfile -t staged_files < <(git diff --cached --name-only --diff-filter=ACMR) +if ((${#staged_files[@]} > 0)); then + bash scripts/pre-commit-format.sh "${staged_files[@]}" +fi + +exec prek run --hook-stage pre-commit diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9680ed8..a3f9f2a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,10 +17,13 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: - dotnet-version: 10.0.x + dotnet-version: 10.0.x + - run: dotnet tool restore - run: dotnet restore Microsandbox.slnx - - run: dotnet build Microsandbox.slnx --no-restore - - run: dotnet test Microsandbox.slnx --no-build --no-restore + - run: dotnet csharpier check . + - run: dotnet format Microsandbox.slnx --verify-no-changes --no-restore + - run: dotnet build Microsandbox.slnx --no-restore --configuration Release + - run: dotnet test Microsandbox.slnx --no-build --no-restore --configuration Release - name: Build examples run: for example in examples/*.cs; do dotnet build "$example"; done - name: Pack and verify managed-only package @@ -37,12 +40,13 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: - dotnet-version: 10.0.x + dotnet-version: 10.0.x + - run: dotnet tool restore - run: dotnet restore Microsandbox.slnx - - run: dotnet build Microsandbox.slnx --no-restore + - run: dotnet build Microsandbox.slnx --no-restore --configuration Release - name: Download and validate upstream FFI assets run: scripts/download-native.sh - name: Test downloaded current-platform ABI env: MICROSANDBOX_FFI_LIBRARY: ${{ github.workspace }}/src/Microsandbox/runtimes/linux-x64/native/libmicrosandbox_go_ffi.so - run: dotnet test Microsandbox.slnx --no-build --no-restore + run: dotnet test Microsandbox.slnx --no-build --no-restore --configuration Release diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..d7ba273 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,14 @@ +default_install_hook_types: + - pre-commit +default_stages: + - pre-commit + +repos: + - repo: local + hooks: + - id: dotnet-format-check + name: Verify .NET code style + entry: dotnet format Microsandbox.slnx --verify-no-changes --no-restore + language: system + files: \.(cs|csproj|props|targets|slnx)$ + pass_filenames: false diff --git a/AGENTS.md b/AGENTS.md index c9c02f1..7f9231d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,6 +2,10 @@ - This is the standalone, independently maintained .NET SDK. Do not add Rust, Cargo, or Go source-build dependencies. - Run `dotnet restore Microsandbox.slnx`, `dotnet build Microsandbox.slnx --no-restore`, and `dotnet test Microsandbox.slnx --no-build --no-restore`. +- Run `mise run format-check` to verify CSharpier and .NET formatting before submitting changes. +- Run `mise run hooks-install` once to install the Git/prek pre-commit hook; it formats and re-stages staged C# files automatically. +- Use Worktrunk (`wt switch`, `wt list`, and `wt merge`) for repository worktrees; its project hooks run prek before commits and the full check before merges. +- Follow `docs/agents/dotnet-style-guide.md` for SDK design and testing conventions. - Run `mise run examples-build` to compile every .NET 10 file-based example. - Run `mise run native-download` to download, checksum, and stage all five upstream FFI release assets for the project version. - `native-assets.sha256` must contain exactly five reviewed digests and a `version` matching the project version. diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..436e307 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,10 @@ + + + true + latest-recommended + true + true + portable + true + + diff --git a/Microsandbox.slnx b/Microsandbox.slnx index 27dbf0f..7a8d925 100644 --- a/Microsandbox.slnx +++ b/Microsandbox.slnx @@ -1,8 +1,8 @@ - - - - - - + + + + + + diff --git a/docs/agents/dotnet-style-guide.md b/docs/agents/dotnet-style-guide.md new file mode 100644 index 0000000..dd0a099 --- /dev/null +++ b/docs/agents/dotnet-style-guide.md @@ -0,0 +1,101 @@ +# .NET SDK Style Guide + +This guide records conventions already established by the SDK. Repository +configuration enforces formatting, analyzers, and warnings-as-errors; the +remaining rules describe the expected design of new code. + +## Source Layout + +- Use file-scoped namespaces. +- Keep `System.*` imports first and use one import group. +- Use four-space indentation in C# and two-space indentation in MSBuild files. +- Put opening braces on the following line. +- Always use braces for conditional and loop bodies. +- Use the pinned CSharpier tool for deterministic formatting; retain + `dotnet format` for analyzer and code-style fixes that CSharpier does not + apply. +- Prefer concise expression-bodied members for simple delegation or return logic. +- Keep implementation details internal and expose the smallest public surface. +- Name private instance fields with an underscore and camel case, such as + `_native` or `_state`. +- Keep private properties, methods, static fields, and constants in PascalCase; + do not use `this.` to qualify instance field access. +- Use explicit accessibility modifiers on non-interface members. +- Prefer C# keywords such as `string` and `int` over framework type aliases. +- Mark fields `readonly` whenever they are not reassigned after construction. +- Use file-scoped namespaces and place `using` directives outside namespaces. +- Use PascalCase for types and non-field members; prefix interfaces with `I`. + +## Public APIs + +- Use `Async` suffixes for asynchronous methods. +- Put `CancellationToken` last and default it to `default` on public async APIs. +- Use `ConfigureAwait(false)` in library implementation code. +- Validate public string inputs with framework guard APIs and reject null, + empty, or whitespace values where the protocol requires a value. +- Use `required` for values that must be supplied by callers or protocol + payloads. +- Prefer immutable option and result models with `init` properties or records. +- Make types `sealed` by default; leave them extensible only when inheritance + is part of the intended API. + +## JSON And Native Contracts + +- Treat native JSON as an external ABI. Never rely on managed property naming + conventions to define native names. +- Put serialization behind internal `ToJson` methods and private payload + types where the public model does not exactly match the wire contract. +- Use explicit `JsonPropertyName` attributes for native fields. +- Preserve omission semantics: default-valued optional fields are omitted, and + protocol fields that require explicit zero or false values opt into writing + those defaults. +- Serialize protocol enums using the established lowercase snake-case format. +- Convert time values explicitly at the boundary, using the protocol unit and + rounding behavior rather than implicit conversions. +- Keep native byte encoding and decoding at the interop boundary; expose byte + arrays to managed callers. + +## Native Handles And Disposal + +- Represent native ownership with `IAsyncDisposable` when cleanup crosses the + native or asynchronous boundary. +- Make handle ownership explicit. Consume handles atomically and treat zero as + consumed or unavailable. +- Throw `ObjectDisposedException` when an operation needs a consumed handle. +- Serialize concurrent close or completion operations. +- Mark consuming ownership as gone before invoking native cleanup; retryable + completion should remain open until native cleanup succeeds. +- Once ownership has been consumed, perform final native cleanup with + `CancellationToken.None`. +- Use `await using` for SDK resources in examples and application-facing code. + +## Tests + +- Use TUnit `[Test]` methods with behavior-oriented names. +- Test wire contracts directly: exact property names, omitted fields, explicit + zero and false values, enum strings, nullable fields, and byte encoding. +- Add tests for cancellation, concurrency, repeated disposal, handle ownership, + and retry behavior when changing stateful native wrappers. +- Gate native integration tests on an explicitly configured native library; + managed contract tests must not silently require native assets. +- Prefer focused assertions that explain the contract being protected. + +## Examples + +- File-based examples start with a `#:project` reference to the local SDK. +- Use bounded cancellation, unique sandbox names, `try/finally`, and + best-effort cleanup. +- Keep examples runnable and focused on one SDK capability. + +## Native Assets + +- Download and checksum native assets through the repository scripts. +- Match native asset versions to the managed package version. +- Do not commit generated native runtime directories or package artifacts. + +## Deliberate Non-Rules + +- Do not require XML documentation on every member yet; coverage is strong in + core public types but not universal. +- Do not require every public type to be sealed; some models intentionally allow + inheritance. diff --git a/examples/basic.cs b/examples/basic.cs index 1f273b6..14a8a7d 100644 --- a/examples/basic.cs +++ b/examples/basic.cs @@ -11,23 +11,34 @@ try { Console.WriteLine($"Creating sandbox {name}..."); - sandbox = await client.CreateAsync(name, new SandboxOptions - { - Image = "alpine:3.20", - MemoryMiB = 256, - CPUs = 1, - Environment = new Dictionary { ["GREETING"] = "hello-from-dotnet" }, - }, cancellationToken); + sandbox = await client.CreateAsync( + name, + new SandboxOptions + { + Image = "alpine:3.20", + MemoryMiB = 256, + CPUs = 1, + Environment = new Dictionary { ["GREETING"] = "hello-from-dotnet" }, + }, + cancellationToken + ); - var echo = await sandbox.ExecuteAsync("echo", new ExecOptions - { - Arguments = ["hello", "world"], - }, cancellationToken); - Require(echo.IsSuccess && echo.StandardOutput.Contains("hello world"), "echo output was unexpected"); + var echo = await sandbox.ExecuteAsync( + "echo", + new ExecOptions { Arguments = ["hello", "world"] }, + cancellationToken + ); + Require( + echo.IsSuccess && echo.StandardOutput.Contains("hello world"), + "echo output was unexpected" + ); Console.WriteLine($" echo: {echo.StandardOutput.Trim()}"); var environment = await sandbox.ShellAsync("echo $GREETING", cancellationToken); - Require(environment.StandardOutput.Contains("hello-from-dotnet"), "guest environment was not applied"); + Require( + environment.StandardOutput.Contains("hello-from-dotnet"), + "guest environment was not applied" + ); Console.WriteLine($" environment: {environment.StandardOutput.Trim()}"); var nonZero = await sandbox.ShellAsync("exit 42", cancellationToken); @@ -36,11 +47,16 @@ const string payload = "microsandbox .NET filesystem works\n"; await sandbox.Filesystem.WriteStringAsync("/tmp/dotnet-sdk.txt", payload, cancellationToken); - var roundTrip = await sandbox.Filesystem.ReadStringAsync("/tmp/dotnet-sdk.txt", cancellationToken); + var roundTrip = await sandbox.Filesystem.ReadStringAsync( + "/tmp/dotnet-sdk.txt", + cancellationToken + ); Require(roundTrip == payload, "filesystem round trip failed"); var metrics = await sandbox.MetricsAsync(cancellationToken); - Console.WriteLine($" metrics: uptime={metrics.Uptime} memory={metrics.MemoryBytes} cpu={metrics.CpuPercent:F1}%"); + Console.WriteLine( + $" metrics: uptime={metrics.Uptime} memory={metrics.MemoryBytes} cpu={metrics.CpuPercent:F1}%" + ); Console.WriteLine("Basic example passed."); } finally diff --git a/examples/detached.cs b/examples/detached.cs index 3df7315..77cca59 100644 --- a/examples/detached.cs +++ b/examples/detached.cs @@ -12,11 +12,11 @@ try { - sandbox = await client.CreateAsync(name, new SandboxOptions - { - Image = "alpine:3.20", - Detached = true, - }, cancellationToken); + sandbox = await client.CreateAsync( + name, + new SandboxOptions { Image = "alpine:3.20", Detached = true }, + cancellationToken + ); Console.WriteLine($"Initial handle owns lifecycle: {sandbox.OwnsLifecycle}"); await sandbox.ShellAsync("echo lived-through-detach > /tmp/witness", cancellationToken); @@ -25,7 +25,8 @@ Console.WriteLine("Detached local handle; VM remains running."); var persisted = await client.ListAsync(cancellationToken: cancellationToken); - var handle = persisted.SingleOrDefault(candidate => candidate.Name == name) + var handle = + persisted.SingleOrDefault(candidate => candidate.Name == name) ?? throw new InvalidOperationException("detached sandbox was not listed"); Console.WriteLine($"Persisted status: {handle.Status}"); @@ -63,17 +64,29 @@ static MicrosandboxClient LoadClient() { var client = MicrosandboxClient.Load(); var msbPath = Environment.GetEnvironmentVariable("MICROSANDBOX_MSB_PATH"); - if (!string.IsNullOrWhiteSpace(msbPath)) client.SetMsbPath(msbPath); + if (!string.IsNullOrWhiteSpace(msbPath)) + { + client.SetMsbPath(msbPath); + } return client; } static void Require(bool condition, string message) { - if (!condition) throw new InvalidOperationException(message); + if (!condition) + { + throw new InvalidOperationException(message); + } } static async Task BestEffort(Func action) { - try { await action(); } - catch (Exception exception) { Console.Error.WriteLine($"cleanup: {exception.Message}"); } + try + { + await action(); + } + catch (Exception exception) + { + Console.Error.WriteLine($"cleanup: {exception.Message}"); + } } diff --git a/examples/filesystem.cs b/examples/filesystem.cs index 4e6961f..a3ca55f 100644 --- a/examples/filesystem.cs +++ b/examples/filesystem.cs @@ -11,11 +11,17 @@ try { - sandbox = await client.CreateAsync(name, new SandboxOptions { Image = "alpine:3.20" }, cancellationToken); + sandbox = await client.CreateAsync( + name, + new SandboxOptions { Image = "alpine:3.20" }, + cancellationToken + ); var filesystem = sandbox.Filesystem; await filesystem.WriteStringAsync("/tmp/note.txt", "hello\n", cancellationToken); - Console.WriteLine($" note: {(await filesystem.ReadStringAsync("/tmp/note.txt", cancellationToken)).Trim()}"); + Console.WriteLine( + $" note: {(await filesystem.ReadStringAsync("/tmp/note.txt", cancellationToken)).Trim()}" + ); await filesystem.MkdirAsync("/tmp/work/data", cancellationToken); await filesystem.WriteStringAsync("/tmp/work/data/a.txt", "alpha", cancellationToken); @@ -27,8 +33,14 @@ } await filesystem.CopyAsync("/tmp/work/data/a.txt", "/tmp/work/data/a.copy", cancellationToken); - await filesystem.RenameAsync("/tmp/work/data/b.txt", "/tmp/work/data/b.renamed", cancellationToken); - Console.WriteLine($" copy exists: {await filesystem.ExistsAsync("/tmp/work/data/a.copy", cancellationToken)}"); + await filesystem.RenameAsync( + "/tmp/work/data/b.txt", + "/tmp/work/data/b.renamed", + cancellationToken + ); + Console.WriteLine( + $" copy exists: {await filesystem.ExistsAsync("/tmp/work/data/a.copy", cancellationToken)}" + ); var hostDirectory = Directory.CreateTempSubdirectory("dotnet-sdk-fs-"); try @@ -38,14 +50,19 @@ await File.WriteAllTextAsync(source, "round-tripped through a microVM", cancellationToken); await filesystem.CopyFromHostAsync(source, "/tmp/from-host.txt", cancellationToken); await filesystem.CopyToHostAsync("/tmp/from-host.txt", destination, cancellationToken); - Console.WriteLine($" host round trip: {await File.ReadAllTextAsync(destination, cancellationToken)}"); + Console.WriteLine( + $" host round trip: {await File.ReadAllTextAsync(destination, cancellationToken)}" + ); } finally { hostDirectory.Delete(recursive: true); } - await sandbox.ShellAsync("dd if=/dev/zero of=/tmp/big.bin bs=1M count=2 status=none", cancellationToken); + await sandbox.ShellAsync( + "dd if=/dev/zero of=/tmp/big.bin bs=1M count=2 status=none", + cancellationToken + ); await using (var input = await filesystem.ReadStreamAsync("/tmp/big.bin", cancellationToken)) { var sink = new MemoryStream(); @@ -53,7 +70,9 @@ Console.WriteLine($" streamed read: {sink.Length} bytes"); } - await using (var output = await filesystem.WriteStreamAsync("/tmp/composed.txt", cancellationToken)) + await using ( + var output = await filesystem.WriteStreamAsync("/tmp/composed.txt", cancellationToken) + ) { foreach (var chunk in new[] { "alpha;", "beta;", "gamma;" }) { @@ -61,7 +80,9 @@ } } - Console.WriteLine($" streamed write: {await filesystem.ReadStringAsync("/tmp/composed.txt", cancellationToken)}"); + Console.WriteLine( + $" streamed write: {await filesystem.ReadStringAsync("/tmp/composed.txt", cancellationToken)}" + ); await filesystem.RemoveDirAsync("/tmp/work", cancellationToken); Console.WriteLine("Filesystem example passed."); } @@ -80,12 +101,21 @@ static MicrosandboxClient LoadClient() { var client = MicrosandboxClient.Load(); var msbPath = Environment.GetEnvironmentVariable("MICROSANDBOX_MSB_PATH"); - if (!string.IsNullOrWhiteSpace(msbPath)) client.SetMsbPath(msbPath); + if (!string.IsNullOrWhiteSpace(msbPath)) + { + client.SetMsbPath(msbPath); + } return client; } static async Task BestEffort(Func action) { - try { await action(); } - catch (Exception exception) { Console.Error.WriteLine($"cleanup: {exception.Message}"); } + try + { + await action(); + } + catch (Exception exception) + { + Console.Error.WriteLine($"cleanup: {exception.Message}"); + } } diff --git a/examples/metrics.cs b/examples/metrics.cs index d298e91..982e7d9 100644 --- a/examples/metrics.cs +++ b/examples/metrics.cs @@ -13,11 +13,13 @@ { foreach (var name in names) { - sandboxes.Add(await client.CreateAsync(name, new SandboxOptions - { - Image = "alpine:3.20", - MemoryMiB = 256, - }, cancellationToken)); + sandboxes.Add( + await client.CreateAsync( + name, + new SandboxOptions { Image = "alpine:3.20", MemoryMiB = 256 }, + cancellationToken + ) + ); } foreach (var sandbox in sandboxes) @@ -26,17 +28,27 @@ } var point = await sandboxes[0].MetricsAsync(cancellationToken); - Console.WriteLine($"{sandboxes[0].Name}: cpu={point.CpuPercent:F1}% memory={point.MemoryBytes >> 10} KiB uptime={point.Uptime}"); + Console.WriteLine( + $"{sandboxes[0].Name}: cpu={point.CpuPercent:F1}% memory={point.MemoryBytes >> 10} KiB uptime={point.Uptime}" + ); - await using (var stream = await sandboxes[0].MetricsStreamAsync(TimeSpan.FromMilliseconds(250), cancellationToken)) + await using ( + var stream = await sandboxes[0] + .MetricsStreamAsync(TimeSpan.FromMilliseconds(250), cancellationToken) + ) { for (var index = 1; index <= 3; index++) { - using var receiveTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + using var receiveTimeout = CancellationTokenSource.CreateLinkedTokenSource( + cancellationToken + ); receiveTimeout.CancelAfter(TimeSpan.FromSeconds(5)); - var sample = await stream.ReceiveAsync(receiveTimeout.Token) + var sample = + await stream.ReceiveAsync(receiveTimeout.Token) ?? throw new InvalidOperationException("metrics stream ended early"); - Console.WriteLine($" #{index}: cpu={sample.CpuPercent:F1}% rx={sample.NetworkReceiveBytes} tx={sample.NetworkTransmitBytes}"); + Console.WriteLine( + $" #{index}: cpu={sample.CpuPercent:F1}% rx={sample.NetworkReceiveBytes} tx={sample.NetworkTransmitBytes}" + ); } } @@ -44,7 +56,9 @@ Console.WriteLine($"AllMetricsAsync returned {all.Count} running sandboxes:"); foreach (var (name, metrics) in all) { - Console.WriteLine($" {name}: memory={metrics.MemoryBytes >> 10} KiB uptime={metrics.Uptime}"); + Console.WriteLine( + $" {name}: memory={metrics.MemoryBytes >> 10} KiB uptime={metrics.Uptime}" + ); } Console.WriteLine("Metrics example passed."); @@ -67,12 +81,21 @@ static MicrosandboxClient LoadClient() { var client = MicrosandboxClient.Load(); var msbPath = Environment.GetEnvironmentVariable("MICROSANDBOX_MSB_PATH"); - if (!string.IsNullOrWhiteSpace(msbPath)) client.SetMsbPath(msbPath); + if (!string.IsNullOrWhiteSpace(msbPath)) + { + client.SetMsbPath(msbPath); + } return client; } static async Task BestEffort(Func action) { - try { await action(); } - catch (Exception exception) { Console.Error.WriteLine($"cleanup: {exception.Message}"); } + try + { + await action(); + } + catch (Exception exception) + { + Console.Error.WriteLine($"cleanup: {exception.Message}"); + } } diff --git a/examples/patches.cs b/examples/patches.cs index 6ba8249..d3d6ff2 100644 --- a/examples/patches.cs +++ b/examples/patches.cs @@ -12,60 +12,114 @@ try { var configPath = Path.Combine(hostDirectory.FullName, "config.toml"); - var scriptsPath = Directory.CreateDirectory(Path.Combine(hostDirectory.FullName, "scripts")).FullName; + var scriptsPath = Directory + .CreateDirectory(Path.Combine(hostDirectory.FullName, "scripts")) + .FullName; await File.WriteAllTextAsync(configPath, "staged = true\n", cancellationToken); await File.WriteAllTextAsync( Path.Combine(scriptsPath, "hello.sh"), "#!/bin/sh\necho hello-from-script\n", - cancellationToken); + cancellationToken + ); - sandbox = await client.CreateAsync(name, new SandboxOptions - { - Image = "alpine:3.20", - Patches = - [ - new SandboxPatchOptions - { - Kind = "text", - Path = "/etc/greeting.txt", - Content = "hello from a patched rootfs\n", - }, - new SandboxPatchOptions - { - Kind = "append", - Path = "/etc/profile", - Content = "\n# dotnet-patches-example\nexport PATCHED=1\n", - }, - new SandboxPatchOptions { Kind = "mkdir", Path = "/opt/dotnet-sdk", Mode = 493 }, - new SandboxPatchOptions - { - Kind = "symlink", - Target = "/etc/greeting.txt", - Link = "/etc/greeting.link", - }, - new SandboxPatchOptions - { - Kind = "copy_file", - Source = configPath, - Destination = "/etc/dotnet-sdk-config.toml", - }, - new SandboxPatchOptions - { - Kind = "copy_dir", - Source = scriptsPath, - Destination = "/opt/dotnet-sdk/scripts", - }, - new SandboxPatchOptions { Kind = "remove", Path = "/etc/motd" }, - ], - }, cancellationToken); + sandbox = await client.CreateAsync( + name, + new SandboxOptions + { + Image = "alpine:3.20", + Patches = + [ + new SandboxPatchOptions + { + Kind = "text", + Path = "/etc/greeting.txt", + Content = "hello from a patched rootfs\n", + }, + new SandboxPatchOptions + { + Kind = "append", + Path = "/etc/profile", + Content = "\n# dotnet-patches-example\nexport PATCHED=1\n", + }, + new SandboxPatchOptions + { + Kind = "mkdir", + Path = "/opt/dotnet-sdk", + Mode = 493, + }, + new SandboxPatchOptions + { + Kind = "symlink", + Target = "/etc/greeting.txt", + Link = "/etc/greeting.link", + }, + new SandboxPatchOptions + { + Kind = "copy_file", + Source = configPath, + Destination = "/etc/dotnet-sdk-config.toml", + }, + new SandboxPatchOptions + { + Kind = "copy_dir", + Source = scriptsPath, + Destination = "/opt/dotnet-sdk/scripts", + }, + new SandboxPatchOptions { Kind = "remove", Path = "/etc/motd" }, + ], + }, + cancellationToken + ); - await Check(sandbox, "Text", "cat /etc/greeting.txt", "hello from a patched rootfs", cancellationToken); - await Check(sandbox, "Append", "grep dotnet-patches-example /etc/profile", "dotnet-patches-example", cancellationToken); - await Check(sandbox, "Mkdir", "test -d /opt/dotnet-sdk && echo dir-exists", "dir-exists", cancellationToken); - await Check(sandbox, "Symlink", "readlink /etc/greeting.link", "/etc/greeting.txt", cancellationToken); - await Check(sandbox, "CopyFile", "cat /etc/dotnet-sdk-config.toml", "staged = true", cancellationToken); - await Check(sandbox, "CopyDir", "sh /opt/dotnet-sdk/scripts/hello.sh", "hello-from-script", cancellationToken); - await Check(sandbox, "Remove", "test -e /etc/motd && echo present || echo absent", "absent", cancellationToken); + await Check( + sandbox, + "Text", + "cat /etc/greeting.txt", + "hello from a patched rootfs", + cancellationToken + ); + await Check( + sandbox, + "Append", + "grep dotnet-patches-example /etc/profile", + "dotnet-patches-example", + cancellationToken + ); + await Check( + sandbox, + "Mkdir", + "test -d /opt/dotnet-sdk && echo dir-exists", + "dir-exists", + cancellationToken + ); + await Check( + sandbox, + "Symlink", + "readlink /etc/greeting.link", + "/etc/greeting.txt", + cancellationToken + ); + await Check( + sandbox, + "CopyFile", + "cat /etc/dotnet-sdk-config.toml", + "staged = true", + cancellationToken + ); + await Check( + sandbox, + "CopyDir", + "sh /opt/dotnet-sdk/scripts/hello.sh", + "hello-from-script", + cancellationToken + ); + await Check( + sandbox, + "Remove", + "test -e /etc/motd && echo present || echo absent", + "absent", + cancellationToken + ); Console.WriteLine("Patches example passed."); } finally @@ -85,7 +139,8 @@ static async Task Check( string label, string command, string expected, - CancellationToken cancellationToken) + CancellationToken cancellationToken +) { var result = await sandbox.ShellAsync(command, cancellationToken); var output = result.StandardOutput + result.StandardError; @@ -94,19 +149,28 @@ static async Task Check( throw new InvalidOperationException($"{label} patch did not produce {expected}: {output}"); } - Console.WriteLine($" {label,-8} {expected}"); + Console.WriteLine($" {label, -8} {expected}"); } static MicrosandboxClient LoadClient() { var client = MicrosandboxClient.Load(); var msbPath = Environment.GetEnvironmentVariable("MICROSANDBOX_MSB_PATH"); - if (!string.IsNullOrWhiteSpace(msbPath)) client.SetMsbPath(msbPath); + if (!string.IsNullOrWhiteSpace(msbPath)) + { + client.SetMsbPath(msbPath); + } return client; } static async Task BestEffort(Func action) { - try { await action(); } - catch (Exception exception) { Console.Error.WriteLine($"cleanup: {exception.Message}"); } + try + { + await action(); + } + catch (Exception exception) + { + Console.Error.WriteLine($"cleanup: {exception.Message}"); + } } diff --git a/examples/ports.cs b/examples/ports.cs index 959c526..d6dd45b 100644 --- a/examples/ports.cs +++ b/examples/ports.cs @@ -17,15 +17,20 @@ try { Console.WriteLine($"Publishing host port {hostPort} to guest port {guestPort}..."); - sandbox = await client.CreateAsync(name, new SandboxOptions - { - Image = "alpine:3.20", - Ports = new Dictionary { [hostPort] = guestPort }, - }, cancellationToken); + sandbox = await client.CreateAsync( + name, + new SandboxOptions + { + Image = "alpine:3.20", + Ports = new Dictionary { [hostPort] = guestPort }, + }, + cancellationToken + ); await using var command = await sandbox.ShellStreamingAsync( $"printf '{payload}' | nc -l -p {guestPort}", - cancellationToken: cancellationToken); + cancellationToken: cancellationToken + ); using var connection = await ConnectWithRetry("127.0.0.1", hostPort, cancellationToken); var buffer = new byte[Encoding.UTF8.GetByteCount(payload)]; @@ -58,7 +63,11 @@ static ushort ReserveHostPort() return port; } -static async Task ConnectWithRetry(string host, ushort port, CancellationToken cancellationToken) +static async Task ConnectWithRetry( + string host, + ushort port, + CancellationToken cancellationToken +) { Exception? lastError = null; for (var attempt = 0; attempt < 20; attempt++) @@ -89,17 +98,29 @@ static MicrosandboxClient LoadClient() { var client = MicrosandboxClient.Load(); var msbPath = Environment.GetEnvironmentVariable("MICROSANDBOX_MSB_PATH"); - if (!string.IsNullOrWhiteSpace(msbPath)) client.SetMsbPath(msbPath); + if (!string.IsNullOrWhiteSpace(msbPath)) + { + client.SetMsbPath(msbPath); + } return client; } static void Require(bool condition, string message) { - if (!condition) throw new InvalidOperationException(message); + if (!condition) + { + throw new InvalidOperationException(message); + } } static async Task BestEffort(Func action) { - try { await action(); } - catch (Exception exception) { Console.Error.WriteLine($"cleanup: {exception.Message}"); } + try + { + await action(); + } + catch (Exception exception) + { + Console.Error.WriteLine($"cleanup: {exception.Message}"); + } } diff --git a/examples/secrets.cs b/examples/secrets.cs index cddeffc..9ddece1 100644 --- a/examples/secrets.cs +++ b/examples/secrets.cs @@ -13,29 +13,47 @@ try { - sandbox = await client.CreateAsync(name, new SandboxOptions - { - Image = "alpine:3.20", - Secrets = - [ - new SandboxSecretOptions - { - EnvironmentVariable = environmentVariable, - Value = secretValue, - AllowedHosts = ["api.example.com"], - Placeholder = placeholder, - }, - ], - }, cancellationToken); + sandbox = await client.CreateAsync( + name, + new SandboxOptions + { + Image = "alpine:3.20", + Secrets = + [ + new SandboxSecretOptions + { + EnvironmentVariable = environmentVariable, + Value = secretValue, + AllowedHosts = ["api.example.com"], + Placeholder = placeholder, + }, + ], + }, + cancellationToken + ); - var visible = await sandbox.ShellAsync($"printenv {environmentVariable}; true", cancellationToken); - Require(!visible.StandardOutput.Contains(secretValue), "secret value leaked into the guest environment"); - Require(visible.StandardOutput.Contains(placeholder), "guest did not receive the secret placeholder"); + var visible = await sandbox.ShellAsync( + $"printenv {environmentVariable}; true", + cancellationToken + ); + Require( + !visible.StandardOutput.Contains(secretValue), + "secret value leaked into the guest environment" + ); + Require( + visible.StandardOutput.Contains(placeholder), + "guest did not receive the secret placeholder" + ); Console.WriteLine($" guest sees placeholder: {visible.StandardOutput.Trim()}"); var environment = await sandbox.ShellAsync("env", cancellationToken); - Require(!environment.StandardOutput.Contains(secretValue), "secret value appeared in the full environment"); - Console.WriteLine($" scanned {environment.StandardOutput.Length} environment bytes without exposing the secret"); + Require( + !environment.StandardOutput.Contains(secretValue), + "secret value appeared in the full environment" + ); + Console.WriteLine( + $" scanned {environment.StandardOutput.Length} environment bytes without exposing the secret" + ); Console.WriteLine("Secrets example passed."); } finally @@ -53,17 +71,29 @@ static MicrosandboxClient LoadClient() { var client = MicrosandboxClient.Load(); var msbPath = Environment.GetEnvironmentVariable("MICROSANDBOX_MSB_PATH"); - if (!string.IsNullOrWhiteSpace(msbPath)) client.SetMsbPath(msbPath); + if (!string.IsNullOrWhiteSpace(msbPath)) + { + client.SetMsbPath(msbPath); + } return client; } static void Require(bool condition, string message) { - if (!condition) throw new InvalidOperationException(message); + if (!condition) + { + throw new InvalidOperationException(message); + } } static async Task BestEffort(Func action) { - try { await action(); } - catch (Exception exception) { Console.Error.WriteLine($"cleanup: {exception.Message}"); } + try + { + await action(); + } + catch (Exception exception) + { + Console.Error.WriteLine($"cleanup: {exception.Message}"); + } } diff --git a/examples/snapshot-fork.cs b/examples/snapshot-fork.cs index 403d5dd..89bc339 100644 --- a/examples/snapshot-fork.cs +++ b/examples/snapshot-fork.cs @@ -15,19 +15,26 @@ try { - source = await client.CreateAsync(baseName, new SandboxOptions { Image = "alpine:3.20" }, cancellationToken); + source = await client.CreateAsync( + baseName, + new SandboxOptions { Image = "alpine:3.20" }, + cancellationToken + ); var payload = $"created by {baseName}\n"; await source.Filesystem.WriteStringAsync(markerPath, payload, cancellationToken); await source.StopAsync(cancellationToken: cancellationToken); await source.DisposeAsync(); source = null; - var artifact = await client.Snapshots.CreateAsync(new SnapshotCreateOptions - { - Name = snapshotName, - SourceSandbox = baseName, - RecordIntegrity = true, - }, cancellationToken); + var artifact = await client.Snapshots.CreateAsync( + new SnapshotCreateOptions + { + Name = snapshotName, + SourceSandbox = baseName, + RecordIntegrity = true, + }, + cancellationToken + ); Console.WriteLine($" snapshot: digest={artifact.Digest} size={artifact.SizeBytes} bytes"); var report = await client.Snapshots.VerifyAsync(snapshotName, cancellationToken); @@ -38,7 +45,11 @@ Require(indexed.Digest == artifact.Digest, "snapshot index digest did not match artifact"); Console.WriteLine($" index: name={indexed.Name ?? "(unnamed)"} digest={indexed.Digest}"); - fork = await client.CreateAsync(forkName, new SandboxOptions { Snapshot = snapshotName }, cancellationToken); + fork = await client.CreateAsync( + forkName, + new SandboxOptions { Snapshot = snapshotName }, + cancellationToken + ); var restored = await fork.Filesystem.ReadStringAsync(markerPath, cancellationToken); Require(restored == payload, "fork did not preserve the snapshot marker"); Console.WriteLine($" fork preserved: {restored.Trim()}"); @@ -55,13 +66,19 @@ static MicrosandboxClient LoadClient() { var client = MicrosandboxClient.Load(); var msbPath = Environment.GetEnvironmentVariable("MICROSANDBOX_MSB_PATH"); - if (!string.IsNullOrWhiteSpace(msbPath)) client.SetMsbPath(msbPath); + if (!string.IsNullOrWhiteSpace(msbPath)) + { + client.SetMsbPath(msbPath); + } return client; } static void Require(bool condition, string message) { - if (!condition) throw new InvalidOperationException(message); + if (!condition) + { + throw new InvalidOperationException(message); + } } static async Task CleanupSandbox(Sandbox? sandbox, string name, MicrosandboxClient client) @@ -77,6 +94,12 @@ static async Task CleanupSandbox(Sandbox? sandbox, string name, MicrosandboxClie static async Task BestEffort(Func action) { - try { await action(); } - catch (Exception exception) { Console.Error.WriteLine($"cleanup: {exception.Message}"); } + try + { + await action(); + } + catch (Exception exception) + { + Console.Error.WriteLine($"cleanup: {exception.Message}"); + } } diff --git a/examples/streaming-exec.cs b/examples/streaming-exec.cs index fd90761..e7d86a4 100644 --- a/examples/streaming-exec.cs +++ b/examples/streaming-exec.cs @@ -11,11 +11,18 @@ try { - sandbox = await client.CreateAsync(name, new SandboxOptions { Image = "alpine:3.20" }, cancellationToken); + sandbox = await client.CreateAsync( + name, + new SandboxOptions { Image = "alpine:3.20" }, + cancellationToken + ); - await using (var command = await sandbox.ShellStreamingAsync( - "echo out-line; echo err-line >&2; exit 3", - cancellationToken: cancellationToken)) + await using ( + var command = await sandbox.ShellStreamingAsync( + "echo out-line; echo err-line >&2; exit 3", + cancellationToken: cancellationToken + ) + ) { var stdout = new StringBuilder(); var stderr = new StringBuilder(); @@ -42,7 +49,7 @@ } } - Complete: + Complete: Require(exitCode == 3, $"expected exit 3, got {exitCode}"); Require(stdout.ToString().Contains("out-line"), "stdout event was not received"); Require(stderr.ToString().Contains("err-line"), "stderr event was not received"); @@ -50,11 +57,14 @@ Console.WriteLine($" stderr: {stderr.ToString().Trim()}"); } - await using (var sleeper = await sandbox.ShellStreamingAsync("sleep 60", cancellationToken: cancellationToken)) + await using ( + var sleeper = await sandbox.ShellStreamingAsync( + "sleep 60", + cancellationToken: cancellationToken + ) + ) { - while (await sleeper.ReceiveAsync(cancellationToken) is not ExecStartedEvent) - { - } + while (await sleeper.ReceiveAsync(cancellationToken) is not ExecStartedEvent) { } Console.WriteLine(" sending SIGTERM to long-running command"); await sleeper.SignalAsync(15, cancellationToken); @@ -79,17 +89,29 @@ static MicrosandboxClient LoadClient() { var client = MicrosandboxClient.Load(); var msbPath = Environment.GetEnvironmentVariable("MICROSANDBOX_MSB_PATH"); - if (!string.IsNullOrWhiteSpace(msbPath)) client.SetMsbPath(msbPath); + if (!string.IsNullOrWhiteSpace(msbPath)) + { + client.SetMsbPath(msbPath); + } return client; } static void Require(bool condition, string message) { - if (!condition) throw new InvalidOperationException(message); + if (!condition) + { + throw new InvalidOperationException(message); + } } static async Task BestEffort(Func action) { - try { await action(); } - catch (Exception exception) { Console.Error.WriteLine($"cleanup: {exception.Message}"); } + try + { + await action(); + } + catch (Exception exception) + { + Console.Error.WriteLine($"cleanup: {exception.Message}"); + } } diff --git a/examples/volumes.cs b/examples/volumes.cs index 37fa32e..967e6a8 100644 --- a/examples/volumes.cs +++ b/examples/volumes.cs @@ -10,15 +10,15 @@ try { - var volume = await client.Volumes.CreateAsync(name, new VolumeCreateOptions - { - QuotaMiB = 64, - Labels = new Dictionary + var volume = await client.Volumes.CreateAsync( + name, + new VolumeCreateOptions { - ["team"] = "agents", - ["tier"] = "example", + QuotaMiB = 64, + Labels = new Dictionary { ["team"] = "agents", ["tier"] = "example" }, }, - }, cancellationToken); + cancellationToken + ); Require(volume.Name == name, "created volume name did not match"); var volumes = await client.Volumes.ListAsync(cancellationToken); @@ -53,17 +53,29 @@ static MicrosandboxClient LoadClient() { var client = MicrosandboxClient.Load(); var msbPath = Environment.GetEnvironmentVariable("MICROSANDBOX_MSB_PATH"); - if (!string.IsNullOrWhiteSpace(msbPath)) client.SetMsbPath(msbPath); + if (!string.IsNullOrWhiteSpace(msbPath)) + { + client.SetMsbPath(msbPath); + } return client; } static void Require(bool condition, string message) { - if (!condition) throw new InvalidOperationException(message); + if (!condition) + { + throw new InvalidOperationException(message); + } } static async Task BestEffort(Func action) { - try { await action(); } - catch (Exception exception) { Console.Error.WriteLine($"cleanup: {exception.Message}"); } + try + { + await action(); + } + catch (Exception exception) + { + Console.Error.WriteLine($"cleanup: {exception.Message}"); + } } diff --git a/global.json b/global.json index 3140116..a51d4b0 100644 --- a/global.json +++ b/global.json @@ -1,4 +1,9 @@ { + "sdk": { + "version": "10.0.302", + "rollForward": "latestFeature", + "allowPrerelease": false + }, "test": { "runner": "Microsoft.Testing.Platform" } diff --git a/mise.toml b/mise.toml index b53e20f..bf2ea95 100644 --- a/mise.toml +++ b/mise.toml @@ -1,19 +1,28 @@ [tools] -dotnet = "10" +dotnet = "10.0.302" [tasks.restore] description = "Restore .NET SDK dependencies" -run = "dotnet restore Microsandbox.slnx" +run = "dotnet tool restore && dotnet restore Microsandbox.slnx" [tasks.build] description = "Build the .NET SDK" depends = ["restore"] -run = "dotnet build Microsandbox.slnx --no-restore" +run = "dotnet build Microsandbox.slnx --no-restore --configuration Release" [tasks.test] description = "Run the TUnit test suite" depends = ["build"] -run = "dotnet test Microsandbox.slnx --no-build --no-restore" +run = "dotnet test Microsandbox.slnx --no-build --no-restore --configuration Release" + +[tasks.format-check] +description = "Verify C# and .NET formatting" +depends = ["restore"] +run = "dotnet csharpier check . && dotnet format Microsandbox.slnx --verify-no-changes --no-restore" + +[tasks.hooks-install] +description = "Install prek Git hooks" +run = "git config core.hooksPath .githooks" [tasks.examples-build] description = "Build all .NET 10 file-based app examples" @@ -69,4 +78,4 @@ MICROSANDBOX_FFI_LIBRARY="$library" dotnet test Microsandbox.slnx --no-build --n [tasks.check] description = "Build and test the .NET SDK" -depends = ["test", "examples-build"] +depends = ["test", "examples-build", "format-check"] diff --git a/scripts/download-runtime.cs b/scripts/download-runtime.cs index 0e894d5..6a7a9f1 100644 --- a/scripts/download-runtime.cs +++ b/scripts/download-runtime.cs @@ -8,7 +8,9 @@ var projectPath = Path.Combine(sdkDirectory, "src", "Microsandbox", "Microsandbox.csproj"); if (!File.Exists(projectPath)) { - throw new InvalidOperationException("Run this file from the microsandbox-dotnet repository root."); + throw new InvalidOperationException( + "Run this file from the microsandbox-dotnet repository root." + ); } var platform = CurrentPlatform(); @@ -23,9 +25,11 @@ http.DefaultRequestHeaders.UserAgent.ParseAdd("microsandbox-dotnet-examples"); var releaseJson = await http.GetByteArrayAsync( - "https://api.github.com/repos/superradcompany/microsandbox/releases/latest"); + "https://api.github.com/repos/superradcompany/microsandbox/releases/latest" + ); using var release = JsonDocument.Parse(releaseJson); - var tag = release.RootElement.GetProperty("tag_name").GetString() + var tag = + release.RootElement.GetProperty("tag_name").GetString() ?? throw new InvalidDataException("Latest GitHub release did not contain tag_name"); var version = tag.TrimStart('v'); var releaseBase = $"https://github.com/superradcompany/microsandbox/releases/download/{tag}"; @@ -56,17 +60,26 @@ if (!OperatingSystem.IsWindows()) { - File.SetUnixFileMode(msbPath, - UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | - UnixFileMode.GroupRead | UnixFileMode.GroupExecute | - UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + File.SetUnixFileMode( + msbPath, + UnixFileMode.UserRead + | UnixFileMode.UserWrite + | UnixFileMode.UserExecute + | UnixFileMode.GroupRead + | UnixFileMode.GroupExecute + | UnixFileMode.OtherRead + | UnixFileMode.OtherExecute + ); CreateKrunfwLinks(temporaryDirectory); } var finalMsbPath = Path.Combine(runtimeDirectory, platform.MsbFilename); var finalFfiPath = Path.Combine(runtimeDirectory, ffiName); WriteEnvironmentFiles(temporaryDirectory, finalMsbPath, finalFfiPath, version); - await File.WriteAllTextAsync(Path.Combine(temporaryDirectory, "version"), version + Environment.NewLine); + await File.WriteAllTextAsync( + Path.Combine(temporaryDirectory, "version"), + version + Environment.NewLine + ); if (Directory.Exists(runtimeDirectory)) { @@ -98,14 +111,16 @@ } catch (Exception exception) { - Console.Error.WriteLine($"Warning: could not remove previous runtime at {backupDirectory}: {exception.Message}"); + Console.Error.WriteLine( + $"Warning: could not remove previous runtime at {backupDirectory}: {exception.Message}" + ); } } Console.WriteLine("Release runtime downloaded and checksums verified."); - Console.WriteLine(OperatingSystem.IsWindows() - ? @"Next: . .\.runtime\env.ps1" - : "Next: source .runtime/env.sh"); + Console.WriteLine( + OperatingSystem.IsWindows() ? @"Next: . .\.runtime\env.ps1" : "Next: source .runtime/env.sh" + ); } finally { @@ -127,27 +142,42 @@ static PlatformAssets CurrentPlatform() { var releaseArchitecture = architecture == Architecture.X64 ? "x86_64" : "aarch64"; var ffiArchitecture = architecture == Architecture.X64 ? "amd64" : "arm64"; - return new($"linux-{releaseArchitecture}", $"linux-{ffiArchitecture}", "tar.gz", "so", "msb"); + return new( + $"linux-{releaseArchitecture}", + $"linux-{ffiArchitecture}", + "tar.gz", + "so", + "msb" + ); } if (OperatingSystem.IsWindows() && architecture is Architecture.X64 or Architecture.Arm64) { var releaseArchitecture = architecture == Architecture.X64 ? "x86_64" : "aarch64"; var ffiArchitecture = architecture == Architecture.X64 ? "amd64" : "arm64"; - return new($"windows-{releaseArchitecture}", $"windows-{ffiArchitecture}", "zip", "dll", "msb.exe"); + return new( + $"windows-{releaseArchitecture}", + $"windows-{ffiArchitecture}", + "zip", + "dll", + "msb.exe" + ); } - throw new PlatformNotSupportedException($"Unsupported platform: {RuntimeInformation.OSDescription} {architecture}"); + throw new PlatformNotSupportedException( + $"Unsupported platform: {RuntimeInformation.OSDescription} {architecture}" + ); } static void VerifyChecksum(string filename, byte[] content, string manifest) { - var expected = manifest - .Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) - .Select(line => line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)) - .Where(parts => parts.Length >= 2 && parts[1].TrimStart('*') == filename) - .Select(parts => parts[0]) - .SingleOrDefault() + var expected = + manifest + .Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(line => line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)) + .Where(parts => parts.Length >= 2 && parts[1].TrimStart('*') == filename) + .Select(parts => parts[0]) + .SingleOrDefault() ?? throw new InvalidDataException($"checksums.sha256 did not contain {filename}"); var actual = Convert.ToHexStringLower(SHA256.HashData(content)); if (!string.Equals(actual, expected, StringComparison.OrdinalIgnoreCase)) @@ -187,13 +217,17 @@ static void ExtractBundle(byte[] bundle, string extension, string destination) static void CreateKrunfwLinks(string directory) { - var libraries = Directory.GetFiles(directory, "libkrunfw*") + var libraries = Directory + .GetFiles(directory, "libkrunfw*") .Select(Path.GetFileName) .OfType() .ToArray(); if (OperatingSystem.IsMacOS()) { - var library = libraries.Single(name => name.StartsWith("libkrunfw.", StringComparison.Ordinal) && name.EndsWith(".dylib", StringComparison.Ordinal)); + var library = libraries.Single(name => + name.StartsWith("libkrunfw.", StringComparison.Ordinal) + && name.EndsWith(".dylib", StringComparison.Ordinal) + ); File.CreateSymbolicLink(Path.Combine(directory, "libkrunfw.dylib"), library); return; } @@ -210,14 +244,18 @@ static void WriteEnvironmentFiles(string directory, string msbPath, string ffiPa static string ShellQuote(string value) => $"'{value.Replace("'", "'\"'\"'")}'"; static string PowerShellQuote(string value) => $"'{value.Replace("'", "''")}'"; - File.WriteAllText(Path.Combine(directory, "env.sh"), - $"export MICROSANDBOX_MSB_PATH={ShellQuote(msbPath)}\n" + - $"export MICROSANDBOX_FFI_LIBRARY={ShellQuote(ffiPath)}\n" + - $"export MICROSANDBOX_RELEASE_VERSION={ShellQuote(version)}\n"); - File.WriteAllText(Path.Combine(directory, "env.ps1"), - $"$env:MICROSANDBOX_MSB_PATH = {PowerShellQuote(msbPath)}\n" + - $"$env:MICROSANDBOX_FFI_LIBRARY = {PowerShellQuote(ffiPath)}\n" + - $"$env:MICROSANDBOX_RELEASE_VERSION = {PowerShellQuote(version)}\n"); + File.WriteAllText( + Path.Combine(directory, "env.sh"), + $"export MICROSANDBOX_MSB_PATH={ShellQuote(msbPath)}\n" + + $"export MICROSANDBOX_FFI_LIBRARY={ShellQuote(ffiPath)}\n" + + $"export MICROSANDBOX_RELEASE_VERSION={ShellQuote(version)}\n" + ); + File.WriteAllText( + Path.Combine(directory, "env.ps1"), + $"$env:MICROSANDBOX_MSB_PATH = {PowerShellQuote(msbPath)}\n" + + $"$env:MICROSANDBOX_FFI_LIBRARY = {PowerShellQuote(ffiPath)}\n" + + $"$env:MICROSANDBOX_RELEASE_VERSION = {PowerShellQuote(version)}\n" + ); } internal sealed record PlatformAssets( @@ -225,4 +263,5 @@ internal sealed record PlatformAssets( string FfiTarget, string BundleExtension, string FfiExtension, - string MsbFilename); + string MsbFilename +); diff --git a/scripts/pre-commit-format.sh b/scripts/pre-commit-format.sh new file mode 100755 index 0000000..daa24fa --- /dev/null +++ b/scripts/pre-commit-format.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail + +for file in "$@"; do + case "$file" in + *.cs|*.csproj|*.props|*.targets|*.slnx) + [[ -f "$file" ]] || continue + dotnet csharpier format "$file" + git add -- "$file" + ;; + esac +done diff --git a/scripts/pre-commit-hook.sh b/scripts/pre-commit-hook.sh new file mode 100755 index 0000000..a6a7f49 --- /dev/null +++ b/scripts/pre-commit-hook.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail + +mapfile -t staged_files < <(git diff --cached --name-only --diff-filter=ACMR) +if ((${#staged_files[@]} > 0)); then + bash scripts/pre-commit-format.sh "${staged_files[@]}" +fi + +exec prek run --hook-stage pre-commit diff --git a/src/Microsandbox/Agent.cs b/src/Microsandbox/Agent.cs index 78d1e93..62d29c1 100644 --- a/src/Microsandbox/Agent.cs +++ b/src/Microsandbox/Agent.cs @@ -32,17 +32,19 @@ internal AgentClient(NativeApi native, ulong handle) public Task RequestAsync( byte flags, ReadOnlyMemory body, - CancellationToken cancellationToken = default) => - _native.AgentRequestAsync(GetHandle(), flags, body, cancellationToken); + CancellationToken cancellationToken = default + ) => _native.AgentRequestAsync(GetHandle(), flags, body, cancellationToken); /// Opens a raw streaming session. public async Task StreamAsync( byte flags, ReadOnlyMemory body, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { var agentHandle = GetHandle(); - var stream = await _native.AgentStreamOpenAsync(agentHandle, flags, body, cancellationToken) + var stream = await _native + .AgentStreamOpenAsync(agentHandle, flags, body, cancellationToken) .ConfigureAwait(false); return new AgentStream(_native, agentHandle, stream.StreamHandle, stream.Id); } @@ -52,8 +54,8 @@ public Task SendAsync( uint id, byte flags, ReadOnlyMemory body, - CancellationToken cancellationToken = default) => - _native.AgentSendAsync(GetHandle(), id, flags, body, cancellationToken); + CancellationToken cancellationToken = default + ) => _native.AgentSendAsync(GetHandle(), id, flags, body, cancellationToken); /// Returns a copy of the cached handshake core.ready CBOR body. public byte[] GetReadyBytes() => _native.AgentReadyBytes(GetHandle()); @@ -63,7 +65,8 @@ public Task CloseAsync(CancellationToken cancellationToken = default) => _state.CloseAsync(_native.AgentCloseAsync, cancellationToken); /// - public async ValueTask DisposeAsync() => await CloseAsync(CancellationToken.None).ConfigureAwait(false); + public async ValueTask DisposeAsync() => + await CloseAsync(CancellationToken.None).ConfigureAwait(false); private ulong GetHandle() => _state.GetHandle(nameof(AgentClient)); @@ -96,10 +99,12 @@ internal AgentStream(NativeApi native, ulong agentHandle, ulong streamHandle, ui public Task CloseAsync(CancellationToken cancellationToken = default) => _state.CloseAsync( (handle, token) => _native.AgentStreamCloseAsync(_agentHandle, handle, token), - cancellationToken); + cancellationToken + ); /// - public async ValueTask DisposeAsync() => await CloseAsync(CancellationToken.None).ConfigureAwait(false); + public async ValueTask DisposeAsync() => + await CloseAsync(CancellationToken.None).ConfigureAwait(false); private ulong GetHandle() => _state.GetHandle(nameof(AgentStream)); diff --git a/src/Microsandbox/ConsumingCloseState.cs b/src/Microsandbox/ConsumingCloseState.cs index d59a5a7..9c59e16 100644 --- a/src/Microsandbox/ConsumingCloseState.cs +++ b/src/Microsandbox/ConsumingCloseState.cs @@ -20,14 +20,13 @@ internal ConsumingCloseState(ulong handle) internal ulong GetHandle(string owner) { var handle = Volatile.Read(ref _handle); - return handle > 0 - ? (ulong)handle - : throw new ObjectDisposedException(owner); + return handle > 0 ? (ulong)handle : throw new ObjectDisposedException(owner); } internal async Task CloseAsync( Func closeAsync, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { await _closeGate.WaitAsync(cancellationToken).ConfigureAwait(false); try diff --git a/src/Microsandbox/ExecOptions.cs b/src/Microsandbox/ExecOptions.cs index 469cb5b..1925dc2 100644 --- a/src/Microsandbox/ExecOptions.cs +++ b/src/Microsandbox/ExecOptions.cs @@ -34,20 +34,24 @@ internal string ToJson() throw new ArgumentOutOfRangeException(nameof(Timeout), "Timeout cannot be negative."); } - var timeoutSeconds = Timeout is { } timeout && timeout > TimeSpan.Zero - ? checked((ulong)Math.Ceiling(timeout.TotalSeconds)) - : (ulong?)null; - - return JsonSerializer.Serialize(new ExecPayload - { - Arguments = Arguments, - WorkingDirectory = WorkingDirectory, - TimeoutSeconds = timeoutSeconds, - Tty = Tty, - User = User, - Environment = Environment, - StdinPipe = StdinPipe, - }, JsonDefaults.Options); + var timeoutSeconds = + Timeout is { } timeout && timeout > TimeSpan.Zero + ? checked((ulong)Math.Ceiling(timeout.TotalSeconds)) + : (ulong?)null; + + return JsonSerializer.Serialize( + new ExecPayload + { + Arguments = Arguments, + WorkingDirectory = WorkingDirectory, + TimeoutSeconds = timeoutSeconds, + Tty = Tty, + User = User, + Environment = Environment, + StdinPipe = StdinPipe, + }, + JsonDefaults.Options + ); } private sealed record ExecPayload diff --git a/src/Microsandbox/ExecStreaming.cs b/src/Microsandbox/ExecStreaming.cs index 455d2ba..5857014 100644 --- a/src/Microsandbox/ExecStreaming.cs +++ b/src/Microsandbox/ExecStreaming.cs @@ -8,7 +8,8 @@ public sealed record ExecFailure( [property: JsonPropertyName("errno")] int? Errno = null, [property: JsonPropertyName("errno_name")] string? ErrnoName = null, [property: JsonPropertyName("message")] string Message = "", - [property: JsonPropertyName("path")] string? Path = null); + [property: JsonPropertyName("path")] string? Path = null +); /// Base type for events received from a streaming exec session. public abstract record ExecEvent; @@ -34,9 +35,7 @@ public sealed record ExecStdinErrorEvent(ExecFailure Failure) : ExecEvent; /// Indicates that every exec event has been consumed. public sealed record ExecDoneEvent : ExecEvent { - private ExecDoneEvent() - { - } + private ExecDoneEvent() { } /// Gets the shared completion event instance. public static ExecDoneEvent Instance { get; } = new(); @@ -81,14 +80,19 @@ public Task SignalAsync(int signal, CancellationToken cancellationToken = defaul _native.ExecSignalAsync(GetHandle(), signal, cancellationToken); /// Resizes the pseudo-terminal allocated for this process. - public Task ResizeAsync(ushort rows, ushort columns, CancellationToken cancellationToken = default) => - _native.ExecResizeAsync(GetHandle(), rows, columns, cancellationToken); + public Task ResizeAsync( + ushort rows, + ushort columns, + CancellationToken cancellationToken = default + ) => _native.ExecResizeAsync(GetHandle(), rows, columns, cancellationToken); /// /// Takes the process stdin sink once, or returns when stdin was not piped or was already taken. /// public ExecStdinSink? TakeStdin() => - _hasStdin && Interlocked.Exchange(ref _stdinTaken, 1) == 0 ? new ExecStdinSink(this, _native) : null; + _hasStdin && Interlocked.Exchange(ref _stdinTaken, 1) == 0 + ? new ExecStdinSink(this, _native) + : null; /// Releases the native exec handle without killing the process. public async ValueTask DisposeAsync() @@ -96,7 +100,9 @@ public async ValueTask DisposeAsync() var handle = ConsumeHandle(ref _handle); if (handle != 0) { - await _native.ExecCloseAsync(checked((ulong)handle), CancellationToken.None).ConfigureAwait(false); + await _native + .ExecCloseAsync(checked((ulong)handle), CancellationToken.None) + .ConfigureAwait(false); } } @@ -133,7 +139,10 @@ public Task WriteAsync(ReadOnlyMemory data, CancellationToken cancellation /// Closes process stdin. This operation may only be completed once. public Task CompleteAsync(CancellationToken cancellationToken = default) => - _completion.CompleteAsync(token => _native.ExecStdinCloseAsync(_exec.GetHandle(), token), cancellationToken); + _completion.CompleteAsync( + token => _native.ExecStdinCloseAsync(_exec.GetHandle(), token), + cancellationToken + ); /// Completes process stdin without allowing cleanup cancellation. public async ValueTask DisposeAsync() => diff --git a/src/Microsandbox/Filesystem.cs b/src/Microsandbox/Filesystem.cs index b0063e5..9fa463e 100644 --- a/src/Microsandbox/Filesystem.cs +++ b/src/Microsandbox/Filesystem.cs @@ -1,6 +1,6 @@ +using System.Runtime.ExceptionServices; using System.Text; using System.Text.Json.Serialization; -using System.Runtime.ExceptionServices; namespace Microsandbox; @@ -21,7 +21,9 @@ public async Task ReadAsync(string path, CancellationToken cancellationT path = Required(path); try { - return await _native.FsReadAsync(_sandbox.GetHandle(), path, cancellationToken).ConfigureAwait(false); + return await _native + .FsReadAsync(_sandbox.GetHandle(), path, cancellationToken) + .ConfigureAwait(false); } catch (MicrosandboxException exception) when (exception.Kind == "buffer_too_small") { @@ -45,8 +47,10 @@ public async Task ReadAsync(string path, CancellationToken cancellationT } } - public async Task ReadStringAsync(string path, CancellationToken cancellationToken = default) => - Encoding.UTF8.GetString(await ReadAsync(path, cancellationToken).ConfigureAwait(false)); + public async Task ReadStringAsync( + string path, + CancellationToken cancellationToken = default + ) => Encoding.UTF8.GetString(await ReadAsync(path, cancellationToken).ConfigureAwait(false)); public Task WriteAsync(string path, byte[] data, CancellationToken cancellationToken = default) { @@ -54,23 +58,49 @@ public Task WriteAsync(string path, byte[] data, CancellationToken cancellationT return _native.FsWriteAsync(_sandbox.GetHandle(), Required(path), data, cancellationToken); } - public Task WriteStringAsync(string path, string content, CancellationToken cancellationToken = default) + public Task WriteStringAsync( + string path, + string content, + CancellationToken cancellationToken = default + ) { ArgumentNullException.ThrowIfNull(content); return WriteAsync(path, Encoding.UTF8.GetBytes(content), cancellationToken); } - public Task> ListAsync(string path, CancellationToken cancellationToken = default) => - _native.FsListAsync(_sandbox.GetHandle(), Required(path), cancellationToken); - - public Task StatAsync(string path, CancellationToken cancellationToken = default) => - _native.FsStatAsync(_sandbox.GetHandle(), Required(path), cancellationToken); - - public Task CopyFromHostAsync(string hostPath, string guestPath, CancellationToken cancellationToken = default) => - _native.FsCopyFromHostAsync(_sandbox.GetHandle(), Required(hostPath), Required(guestPath), cancellationToken); + public Task> ListAsync( + string path, + CancellationToken cancellationToken = default + ) => _native.FsListAsync(_sandbox.GetHandle(), Required(path), cancellationToken); - public Task CopyToHostAsync(string guestPath, string hostPath, CancellationToken cancellationToken = default) => - _native.FsCopyToHostAsync(_sandbox.GetHandle(), Required(guestPath), Required(hostPath), cancellationToken); + public Task StatAsync( + string path, + CancellationToken cancellationToken = default + ) => _native.FsStatAsync(_sandbox.GetHandle(), Required(path), cancellationToken); + + public Task CopyFromHostAsync( + string hostPath, + string guestPath, + CancellationToken cancellationToken = default + ) => + _native.FsCopyFromHostAsync( + _sandbox.GetHandle(), + Required(hostPath), + Required(guestPath), + cancellationToken + ); + + public Task CopyToHostAsync( + string guestPath, + string hostPath, + CancellationToken cancellationToken = default + ) => + _native.FsCopyToHostAsync( + _sandbox.GetHandle(), + Required(guestPath), + Required(hostPath), + cancellationToken + ); public Task MkdirAsync(string path, CancellationToken cancellationToken = default) => _native.FsMkdirAsync(_sandbox.GetHandle(), Required(path), cancellationToken); @@ -81,11 +111,29 @@ public Task RemoveAsync(string path, CancellationToken cancellationToken = defau public Task RemoveDirAsync(string path, CancellationToken cancellationToken = default) => _native.FsRemoveDirAsync(_sandbox.GetHandle(), Required(path), cancellationToken); - public Task CopyAsync(string source, string destination, CancellationToken cancellationToken = default) => - _native.FsCopyAsync(_sandbox.GetHandle(), Required(source), Required(destination), cancellationToken); - - public Task RenameAsync(string source, string destination, CancellationToken cancellationToken = default) => - _native.FsRenameAsync(_sandbox.GetHandle(), Required(source), Required(destination), cancellationToken); + public Task CopyAsync( + string source, + string destination, + CancellationToken cancellationToken = default + ) => + _native.FsCopyAsync( + _sandbox.GetHandle(), + Required(source), + Required(destination), + cancellationToken + ); + + public Task RenameAsync( + string source, + string destination, + CancellationToken cancellationToken = default + ) => + _native.FsRenameAsync( + _sandbox.GetHandle(), + Required(source), + Required(destination), + cancellationToken + ); public Task ExistsAsync(string path, CancellationToken cancellationToken = default) => _native.FsExistsAsync(_sandbox.GetHandle(), Required(path), cancellationToken); @@ -93,24 +141,24 @@ public Task ExistsAsync(string path, CancellationToken cancellationToken = /// Opens a readable stream for a guest file. public async Task ReadStreamAsync( string path, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var handle = await _native.FsReadStreamAsync( - _sandbox.GetHandle(), - Required(path), - cancellationToken).ConfigureAwait(false); + var handle = await _native + .FsReadStreamAsync(_sandbox.GetHandle(), Required(path), cancellationToken) + .ConfigureAwait(false); return new SandboxFileReadStream(_native, handle); } /// Opens a writable stream that must be completed or disposed to commit EOF. public async Task WriteStreamAsync( string path, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var handle = await _native.FsWriteStreamAsync( - _sandbox.GetHandle(), - Required(path), - cancellationToken).ConfigureAwait(false); + var handle = await _native + .FsWriteStreamAsync(_sandbox.GetHandle(), Required(path), cancellationToken) + .ConfigureAwait(false); return new SandboxFileWriteStream(_native, handle); } @@ -158,12 +206,16 @@ public override long Position /// public override int Read(byte[] buffer, int offset, int count) => - ReadAsync(buffer.AsMemory(offset, count), CancellationToken.None).AsTask().GetAwaiter().GetResult(); + ReadAsync(buffer.AsMemory(offset, count), CancellationToken.None) + .AsTask() + .GetAwaiter() + .GetResult(); /// public override async ValueTask ReadAsync( Memory buffer, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ObjectDisposedException.ThrowIf(Volatile.Read(ref _handle) == 0, this); if (buffer.Length == 0 || _eof) @@ -176,7 +228,9 @@ public override async ValueTask ReadAsync( { while (_chunk is null || _chunkOffset == _chunk.Length) { - _chunk = await _native.FsReadStreamReceiveAsync(GetHandle(), cancellationToken).ConfigureAwait(false); + _chunk = await _native + .FsReadStreamReceiveAsync(GetHandle(), cancellationToken) + .ConfigureAwait(false); _chunkOffset = 0; if (_chunk is null) { @@ -197,9 +251,7 @@ public override async ValueTask ReadAsync( } /// - public override void Flush() - { - } + public override void Flush() { } /// public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); @@ -208,7 +260,8 @@ public override void Flush() public override void SetLength(long value) => throw new NotSupportedException(); /// - public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => + throw new NotSupportedException(); /// protected override void Dispose(bool disposing) @@ -216,7 +269,10 @@ protected override void Dispose(bool disposing) var handle = Interlocked.Exchange(ref _handle, 0); if (handle != 0) { - _native.FsReadStreamCloseAsync(checked((ulong)handle), CancellationToken.None).GetAwaiter().GetResult(); + _native + .FsReadStreamCloseAsync(checked((ulong)handle), CancellationToken.None) + .GetAwaiter() + .GetResult(); } if (disposing) @@ -232,7 +288,7 @@ public override ValueTask DisposeAsync() { Dispose(true); GC.SuppressFinalize(this); - return ValueTask.CompletedTask; + return base.DisposeAsync(); } private ulong GetHandle() @@ -277,10 +333,16 @@ public override long Position /// public override void Write(byte[] buffer, int offset, int count) => - WriteAsync(buffer.AsMemory(offset, count), CancellationToken.None).AsTask().GetAwaiter().GetResult(); + WriteAsync(buffer.AsMemory(offset, count), CancellationToken.None) + .AsTask() + .GetAwaiter() + .GetResult(); /// - public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + public override ValueTask WriteAsync( + ReadOnlyMemory buffer, + CancellationToken cancellationToken = default + ) { var task = _native.FsWriteStreamWriteAsync(GetHandle(), buffer, cancellationToken); return new ValueTask(task); @@ -291,15 +353,14 @@ public Task CompleteAsync(CancellationToken cancellationToken = default) => _state.CloseAsync(_native.FsWriteStreamCloseAsync, cancellationToken); /// - public override void Flush() - { - } + public override void Flush() { } /// public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; /// - public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override int Read(byte[] buffer, int offset, int count) => + throw new NotSupportedException(); /// public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); @@ -318,6 +379,7 @@ protected override void Dispose(bool disposing) public override async ValueTask DisposeAsync() { await CompleteAsync(CancellationToken.None).ConfigureAwait(false); + await base.DisposeAsync().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -337,15 +399,18 @@ public sealed record FilesystemEntry( [property: JsonPropertyName("path")] string Path, [property: JsonPropertyName("kind")] FilesystemEntryKind Kind, [property: JsonPropertyName("size")] long Size, - [property: JsonPropertyName("mode")] uint Mode); + [property: JsonPropertyName("mode")] uint Mode +); public sealed record FilesystemStat( [property: JsonPropertyName("kind")] FilesystemEntryKind Kind, [property: JsonPropertyName("size")] long Size, [property: JsonPropertyName("mode")] uint Mode, [property: JsonPropertyName("readonly")] bool IsReadOnly, - [property: JsonPropertyName("modified_unix")] long? ModifiedUnix) + [property: JsonPropertyName("modified_unix")] long? ModifiedUnix +) { - public DateTimeOffset? ModifiedAt => ModifiedUnix is { } value ? DateTimeOffset.FromUnixTimeSeconds(value) : null; + public DateTimeOffset? ModifiedAt => + ModifiedUnix is { } value ? DateTimeOffset.FromUnixTimeSeconds(value) : null; public bool IsDirectory => Kind is FilesystemEntryKind.Dir or FilesystemEntryKind.Directory; } diff --git a/src/Microsandbox/Images.cs b/src/Microsandbox/Images.cs index 398c594..7af578c 100644 --- a/src/Microsandbox/Images.cs +++ b/src/Microsandbox/Images.cs @@ -9,17 +9,25 @@ public sealed class ImageService internal ImageService(NativeApi native) => _native = native; - public Task GetAsync(string reference, CancellationToken cancellationToken = default) => - _native.GetImageAsync(Required(reference), cancellationToken); - - public Task> ListAsync(CancellationToken cancellationToken = default) => - _native.ListImagesAsync(cancellationToken); - - public Task InspectAsync(string reference, CancellationToken cancellationToken = default) => - _native.InspectImageAsync(Required(reference), cancellationToken); - - public Task RemoveAsync(string reference, bool force = false, CancellationToken cancellationToken = default) => - _native.RemoveImageAsync(Required(reference), force, cancellationToken); + public Task GetAsync( + string reference, + CancellationToken cancellationToken = default + ) => _native.GetImageAsync(Required(reference), cancellationToken); + + public Task> ListAsync( + CancellationToken cancellationToken = default + ) => _native.ListImagesAsync(cancellationToken); + + public Task InspectAsync( + string reference, + CancellationToken cancellationToken = default + ) => _native.InspectImageAsync(Required(reference), cancellationToken); + + public Task RemoveAsync( + string reference, + bool force = false, + CancellationToken cancellationToken = default + ) => _native.RemoveImageAsync(Required(reference), force, cancellationToken); public Task PruneAsync(CancellationToken cancellationToken = default) => _native.PruneImagesAsync(cancellationToken); @@ -27,24 +35,28 @@ public Task PruneAsync(CancellationToken cancellationToken = d public Task> LoadAsync( string inputPath, IReadOnlyList? tags = null, - CancellationToken cancellationToken = default) => + CancellationToken cancellationToken = default + ) => _native.LoadImagesAsync( Required(inputPath), JsonSerializer.Serialize(tags ?? Array.Empty(), JsonDefaults.Options), - cancellationToken); + cancellationToken + ); public Task SaveAsync( IReadOnlyList references, string outputPath, ImageArchiveFormat format = ImageArchiveFormat.Docker, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentNullException.ThrowIfNull(references); return _native.SaveImagesAsync( JsonSerializer.Serialize(references, JsonDefaults.Options), Required(outputPath), format == ImageArchiveFormat.Oci ? "oci" : "docker", - cancellationToken); + cancellationToken + ); } private static string Required(string value) @@ -86,8 +98,10 @@ public class ImageInfo [JsonPropertyName("last_used_at_unix")] public long? LastUsedAtUnix { get; init; } - public DateTimeOffset? CreatedAt => CreatedAtUnix is { } value ? DateTimeOffset.FromUnixTimeSeconds(value) : null; - public DateTimeOffset? LastUsedAt => LastUsedAtUnix is { } value ? DateTimeOffset.FromUnixTimeSeconds(value) : null; + public DateTimeOffset? CreatedAt => + CreatedAtUnix is { } value ? DateTimeOffset.FromUnixTimeSeconds(value) : null; + public DateTimeOffset? LastUsedAt => + LastUsedAtUnix is { } value ? DateTimeOffset.FromUnixTimeSeconds(value) : null; } public sealed class ImageDetail : ImageInfo @@ -107,7 +121,8 @@ public sealed record ImageConfig( [property: JsonPropertyName("working_dir")] string WorkingDirectory, [property: JsonPropertyName("user")] string User, [property: JsonPropertyName("labels")] IReadOnlyDictionary Labels, - [property: JsonPropertyName("stop_signal")] string StopSignal); + [property: JsonPropertyName("stop_signal")] string StopSignal +); public sealed record ImageLayer( [property: JsonPropertyName("diff_id")] string DiffId, @@ -115,7 +130,8 @@ public sealed record ImageLayer( [property: JsonPropertyName("media_type")] string MediaType, [property: JsonPropertyName("compressed_size_bytes")] long? CompressedSizeBytes, [property: JsonPropertyName("erofs_size_bytes")] long? ErofsSizeBytes, - [property: JsonPropertyName("position")] int Position); + [property: JsonPropertyName("position")] int Position +); public sealed record ImagePruneReport( [property: JsonPropertyName("image_refs_removed")] uint ImageReferencesRemoved, @@ -123,4 +139,5 @@ public sealed record ImagePruneReport( [property: JsonPropertyName("layers_removed")] uint LayersRemoved, [property: JsonPropertyName("fsmeta_removed")] uint FilesystemMetadataRemoved, [property: JsonPropertyName("vmdk_removed")] uint VmdkRemoved, - [property: JsonPropertyName("bytes_reclaimed")] ulong? BytesReclaimed); + [property: JsonPropertyName("bytes_reclaimed")] ulong? BytesReclaimed +); diff --git a/src/Microsandbox/Logs.cs b/src/Microsandbox/Logs.cs index 74a988c..93b79a4 100644 --- a/src/Microsandbox/Logs.cs +++ b/src/Microsandbox/Logs.cs @@ -9,10 +9,13 @@ public enum LogSource { /// Standard output. Stdout, + /// Standard error. Stderr, + /// Combined process output. Output, + /// Runtime and kernel diagnostics. System, } @@ -22,20 +25,27 @@ public sealed class LogOptions { /// Gets the maximum number of trailing entries to return. public ulong Tail { get; init; } + /// Gets the inclusive lower timestamp bound. public DateTimeOffset? Since { get; init; } + /// Gets the exclusive upper timestamp bound. public DateTimeOffset? Until { get; init; } + /// Gets the sources to include. public IReadOnlyList? Sources { get; init; } - internal string ToJson() => JsonSerializer.Serialize(new Payload - { - Tail = Tail, - SinceMilliseconds = Since?.ToUnixTimeMilliseconds(), - UntilMilliseconds = Until?.ToUnixTimeMilliseconds(), - Sources = Sources, - }, JsonDefaults.Options); + internal string ToJson() => + JsonSerializer.Serialize( + new Payload + { + Tail = Tail, + SinceMilliseconds = Since?.ToUnixTimeMilliseconds(), + UntilMilliseconds = Until?.ToUnixTimeMilliseconds(), + Sources = Sources, + }, + JsonDefaults.Options + ); private sealed class Payload { @@ -71,14 +81,18 @@ public sealed class LogStreamOptions /// Gets whether the stream remains open to follow new entries. public bool Follow { get; init; } - internal string ToJson() => JsonSerializer.Serialize(new Payload - { - Sources = Sources, - SinceMilliseconds = Since?.ToUnixTimeMilliseconds(), - FromCursor = FromCursor, - UntilMilliseconds = Until?.ToUnixTimeMilliseconds(), - Follow = Follow, - }, JsonDefaults.Options); + internal string ToJson() => + JsonSerializer.Serialize( + new Payload + { + Sources = Sources, + SinceMilliseconds = Since?.ToUnixTimeMilliseconds(), + FromCursor = FromCursor, + UntilMilliseconds = Until?.ToUnixTimeMilliseconds(), + Follow = Follow, + }, + JsonDefaults.Options + ); private sealed class Payload { @@ -100,7 +114,13 @@ private sealed class Payload } /// One persisted sandbox log entry. -public sealed record LogEntry(LogSource Source, ulong? SessionId, DateTimeOffset Timestamp, byte[] Data, string Cursor) +public sealed record LogEntry( + LogSource Source, + ulong? SessionId, + DateTimeOffset Timestamp, + byte[] Data, + string Cursor +) { /// Gets the payload decoded as UTF-8 text. public string Text => Encoding.UTF8.GetString(Data); @@ -128,7 +148,9 @@ public async ValueTask DisposeAsync() var handle = Interlocked.Exchange(ref _handle, 0); if (handle != 0) { - await _native.LogCloseAsync(checked((ulong)handle), CancellationToken.None).ConfigureAwait(false); + await _native + .LogCloseAsync(checked((ulong)handle), CancellationToken.None) + .ConfigureAwait(false); } } diff --git a/src/Microsandbox/Metrics.cs b/src/Microsandbox/Metrics.cs index 2a2e95f..a619d5a 100644 --- a/src/Microsandbox/Metrics.cs +++ b/src/Microsandbox/Metrics.cs @@ -17,7 +17,8 @@ public sealed record SandboxMetrics( [property: JsonPropertyName("upper_used_bytes")] ulong? UpperUsedBytes, [property: JsonPropertyName("upper_free_bytes")] ulong? UpperFreeBytes, [property: JsonPropertyName("upper_host_allocated_bytes")] ulong? UpperHostAllocatedBytes, - [property: JsonPropertyName("uptime_secs")] ulong UptimeSeconds) + [property: JsonPropertyName("uptime_secs")] ulong UptimeSeconds +) { /// Gets the sandbox uptime. public TimeSpan Uptime => TimeSpan.FromSeconds(UptimeSeconds); @@ -45,7 +46,9 @@ public async ValueTask DisposeAsync() var handle = Interlocked.Exchange(ref _handle, 0); if (handle != 0) { - await _native.MetricsCloseAsync(checked((ulong)handle), CancellationToken.None).ConfigureAwait(false); + await _native + .MetricsCloseAsync(checked((ulong)handle), CancellationToken.None) + .ConfigureAwait(false); } } diff --git a/src/Microsandbox/Microsandbox.csproj b/src/Microsandbox/Microsandbox.csproj index 4b404a0..28c6263 100644 --- a/src/Microsandbox/Microsandbox.csproj +++ b/src/Microsandbox/Microsandbox.csproj @@ -1,5 +1,4 @@  - net8.0 enable @@ -21,25 +20,29 @@ true $(MSBuildProjectDirectory)/runtimes - - - + - - + - - + @@ -48,16 +51,23 @@ - - - + + + - + - diff --git a/src/Microsandbox/MicrosandboxClient.cs b/src/Microsandbox/MicrosandboxClient.cs index 95db3dd..d0333c5 100644 --- a/src/Microsandbox/MicrosandboxClient.cs +++ b/src/Microsandbox/MicrosandboxClient.cs @@ -25,7 +25,8 @@ private MicrosandboxClient(NativeApi native) public SnapshotService Snapshots { get; } /// Loads the native ABI from an explicit path, environment, package runtime asset, or system search path. - public static MicrosandboxClient Load(string? nativeLibraryPath = null) => new(NativeApi.Load(nativeLibraryPath)); + public static MicrosandboxClient Load(string? nativeLibraryPath = null) => + new(NativeApi.Load(nativeLibraryPath)); /// Gets the microsandbox runtime version exposed by the loaded ABI. public string RuntimeVersion => _native.Version(); @@ -41,16 +42,21 @@ public void SetMsbPath(string path) public async Task CreateAsync( string name, SandboxOptions? options = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ValidateName(name); - var handle = await _native.CreateAsync(name, (options ?? new SandboxOptions()).ToJson(), cancellationToken) + var handle = await _native + .CreateAsync(name, (options ?? new SandboxOptions()).ToJson(), cancellationToken) .ConfigureAwait(false); return new Sandbox(_native, name, handle); } /// Looks up persisted sandbox metadata without connecting. - public Task LookupAsync(string name, CancellationToken cancellationToken = default) + public Task LookupAsync( + string name, + CancellationToken cancellationToken = default + ) { ValidateName(name); return _native.LookupAsync(name, cancellationToken); @@ -59,8 +65,8 @@ public Task LookupAsync(string name, CancellationToken cancellati /// Lists persisted sandboxes, optionally filtering by labels. public Task> ListAsync( SandboxFilter? filter = null, - CancellationToken cancellationToken = default) => - _native.ListAsync((filter ?? new SandboxFilter()).ToJson(), cancellationToken); + CancellationToken cancellationToken = default + ) => _native.ListAsync((filter ?? new SandboxFilter()).ToJson(), cancellationToken); /// Connects to an already-running sandbox by name. public Task ConnectAsync(string name, CancellationToken cancellationToken = default) @@ -73,14 +79,18 @@ public Task ConnectAsync(string name, CancellationToken cancellationTok public Task StartAsync( string name, bool detached = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ValidateName(name); return _native.StartAsync(name, detached, cancellationToken); } /// Starts a persisted sandbox in detached mode. - public Task StartDetachedAsync(string name, CancellationToken cancellationToken = default) + public Task StartDetachedAsync( + string name, + CancellationToken cancellationToken = default + ) { ValidateName(name); return _native.StartAsync(name, true, cancellationToken); @@ -95,26 +105,32 @@ public Task RemoveAsync(string name, CancellationToken cancellationToken = defau /// Gets point-in-time metrics for every running sandbox, keyed by sandbox name. public Task> AllMetricsAsync( - CancellationToken cancellationToken = default) => - _native.AllMetricsAsync(cancellationToken); + CancellationToken cancellationToken = default + ) => _native.AllMetricsAsync(cancellationToken); /// Connects a low-level raw agent client to a running sandbox by name. public async Task ConnectAgentAsync( string name, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ValidateName(name); - var handle = await _native.OpenAgentSandboxAsync(name, cancellationToken).ConfigureAwait(false); + var handle = await _native + .OpenAgentSandboxAsync(name, cancellationToken) + .ConfigureAwait(false); return new AgentClient(_native, handle); } /// Connects a low-level raw agent client to a relay socket path. public async Task ConnectAgentPathAsync( string path, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentException.ThrowIfNullOrWhiteSpace(path); - var handle = await _native.OpenAgentPathAsync(path, cancellationToken).ConfigureAwait(false); + var handle = await _native + .OpenAgentPathAsync(path, cancellationToken) + .ConfigureAwait(false); return new AgentClient(_native, handle); } @@ -130,7 +146,10 @@ internal static void ValidateName(string name) ArgumentException.ThrowIfNullOrWhiteSpace(name); if (Encoding.UTF8.GetByteCount(name) > 128) { - throw new ArgumentOutOfRangeException(nameof(name), "Sandbox names cannot exceed 128 UTF-8 bytes."); + throw new ArgumentOutOfRangeException( + nameof(name), + "Sandbox names cannot exceed 128 UTF-8 bytes." + ); } } } diff --git a/src/Microsandbox/NativeApi.cs b/src/Microsandbox/NativeApi.cs index f5a4998..acde10e 100644 --- a/src/Microsandbox/NativeApi.cs +++ b/src/Microsandbox/NativeApi.cs @@ -11,6 +11,7 @@ internal sealed class NativeApi private const int BufferSize = 1 << 20; private const int FilesystemStreamBufferSize = 6 << 20; private static readonly string ManagedVersion = GetManagedVersion(); + // Matches Go: enough for the runtime's bounded 10 MiB x3 history after base64/JSON expansion. private const int LogsBufferSize = 48 << 20; private readonly FreeStringFn _freeString; @@ -159,14 +160,29 @@ private NativeApi(nint library) _sandboxConnect = GetExport(library, "msb_sandbox_connect"); _sandboxStart = GetExport(library, "msb_sandbox_start"); _sandboxHandleStop = GetExport(library, "msb_sandbox_handle_stop"); - _sandboxHandleRequestStop = GetExport(library, "msb_sandbox_handle_request_stop"); + _sandboxHandleRequestStop = GetExport( + library, + "msb_sandbox_handle_request_stop" + ); _sandboxHandleKill = GetExport(library, "msb_sandbox_handle_kill"); - _sandboxHandleRequestKill = GetExport(library, "msb_sandbox_handle_request_kill"); - _sandboxHandleRequestDrain = GetExport(library, "msb_sandbox_handle_request_drain"); - _sandboxHandleWaitUntilStopped = GetExport(library, "msb_sandbox_handle_wait_until_stopped"); + _sandboxHandleRequestKill = GetExport( + library, + "msb_sandbox_handle_request_kill" + ); + _sandboxHandleRequestDrain = GetExport( + library, + "msb_sandbox_handle_request_drain" + ); + _sandboxHandleWaitUntilStopped = GetExport( + library, + "msb_sandbox_handle_wait_until_stopped" + ); _sandboxHandlePing = GetExport(library, "msb_sandbox_handle_ping"); _sandboxHandleTouch = GetExport(library, "msb_sandbox_handle_touch"); - _sandboxHandleModify = GetExport(library, "msb_sandbox_handle_modify"); + _sandboxHandleModify = GetExport( + library, + "msb_sandbox_handle_modify" + ); _sandboxList = GetExport(library, "msb_sandbox_list"); _sandboxRemove = GetExport(library, "msb_sandbox_remove"); _sandboxExec = GetExport(library, "msb_sandbox_exec"); @@ -189,16 +205,25 @@ private NativeApi(nint library) _sandboxDrain = GetExport(library, "msb_sandbox_drain"); _sandboxRequestDrain = GetExport(library, "msb_sandbox_request_drain"); _sandboxWait = GetExport(library, "msb_sandbox_wait"); - _sandboxWaitUntilStopped = GetExport(library, "msb_sandbox_wait_until_stopped"); + _sandboxWaitUntilStopped = GetExport( + library, + "msb_sandbox_wait_until_stopped" + ); _sandboxPing = GetExport(library, "msb_sandbox_ping"); _sandboxTouch = GetExport(library, "msb_sandbox_touch"); _sandboxDetach = GetExport(library, "msb_sandbox_detach"); - _sandboxOwnsLifecycle = GetExport(library, "msb_sandbox_owns_lifecycle"); + _sandboxOwnsLifecycle = GetExport( + library, + "msb_sandbox_owns_lifecycle" + ); _sandboxClose = GetExport(library, "msb_sandbox_close"); _sandboxModify = GetExport(library, "msb_sandbox_modify"); _sandboxAttach = GetExport(library, "msb_sandbox_attach"); _sandboxAttachShell = GetExport(library, "msb_sandbox_attach_shell"); - _sandboxRemovePersisted = GetExport(library, "msb_sandbox_remove_persisted"); + _sandboxRemovePersisted = GetExport( + library, + "msb_sandbox_remove_persisted" + ); _sandboxSshConnect = GetExport(library, "msb_sandbox_ssh_connect"); _sandboxSshServer = GetExport(library, "msb_sandbox_ssh_server"); _sshClientExec = GetExport(library, "msb_ssh_client_exec"); @@ -206,8 +231,14 @@ private NativeApi(nint library) _sshClientSftp = GetExport(library, "msb_ssh_client_sftp"); _sshClientClose = GetExport(library, "msb_ssh_client_close"); _sshServerClose = GetExport(library, "msb_ssh_server_close"); - _sshServerServeConnection = GetExport(library, "msb_ssh_server_serve_connection"); - _sshServerServeStandardIo = GetExport(library, "msb_ssh_server_serve_stdio"); + _sshServerServeConnection = GetExport( + library, + "msb_ssh_server_serve_connection" + ); + _sshServerServeStandardIo = GetExport( + library, + "msb_ssh_server_serve_stdio" + ); _sftpRead = GetExport(library, "msb_sftp_read"); _sftpWrite = GetExport(library, "msb_sftp_write"); _sftpMkdir = GetExport(library, "msb_sftp_mkdir"); @@ -239,11 +270,17 @@ private NativeApi(nint library) _sandboxLogs = GetExport(library, "msb_sandbox_logs"); _sandboxHandleLogs = GetExport(library, "msb_sandbox_handle_logs"); _sandboxLogStream = GetExport(library, "msb_sandbox_log_stream"); - _sandboxHandleLogStream = GetExport(library, "msb_sandbox_handle_log_stream"); + _sandboxHandleLogStream = GetExport( + library, + "msb_sandbox_handle_log_stream" + ); _logReceive = GetExport(library, "msb_log_recv"); _logClose = GetExport(library, "msb_log_close"); _sandboxMetrics = GetExport(library, "msb_sandbox_metrics"); - _sandboxMetricsStream = GetExport(library, "msb_sandbox_metrics_stream"); + _sandboxMetricsStream = GetExport( + library, + "msb_sandbox_metrics_stream" + ); _metricsReceive = GetExport(library, "msb_metrics_recv"); _metricsClose = GetExport(library, "msb_metrics_close"); _allSandboxMetrics = GetExport(library, "msb_all_sandbox_metrics"); @@ -298,17 +335,22 @@ internal static NativeApi Load(string? explicitPath) // Match the Go SDK: keep compatible libraries loaded for process lifetime so handles stay valid. return native; } - catch (Exception exception) when (exception is EntryPointNotFoundException - or InvalidDataException - or JsonException - or MicrosandboxException) + catch (Exception exception) + when (exception + is EntryPointNotFoundException + or InvalidDataException + or JsonException + or MicrosandboxException + ) { NativeLibrary.Free(library); } } } - throw new DllNotFoundException($"Could not load the microsandbox native library. Tried: {string.Join(", ", candidates)}"); + throw new DllNotFoundException( + $"Could not load the microsandbox native library. Tried: {string.Join(", ", candidates)}" + ); } internal string Version() => ParseVersion(Invoke((buffer, length) => _version(buffer, length))); @@ -319,13 +361,26 @@ internal void SetMsbPath(string path) _setMsbPath(nativePath.Pointer); } - internal async Task CreateAsync(string name, string optionsJson, CancellationToken cancellationToken) + internal async Task CreateAsync( + string name, + string optionsJson, + CancellationToken cancellationToken + ) { using var nativeName = new Utf8String(name); using var nativeOptions = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxCreate(cancelId, nativeName.Pointer, nativeOptions.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxCreate( + cancelId, + nativeName.Pointer, + nativeOptions.Pointer, + buffer, + length + ), + cancellationToken + ) + .ConfigureAwait(false); try { return Deserialize(json).Handle; @@ -353,8 +408,11 @@ internal async Task LookupAsync(string name, CancellationToken ca { using var nativeName = new Utf8String(name); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxLookup(cancelId, nativeName.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxLookup(cancelId, nativeName.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); return new SandboxHandle(this, ParseMetadata(json)); } @@ -362,39 +420,64 @@ internal async Task ConnectAsync(string name, CancellationToken cancell { using var nativeName = new Utf8String(name); var handle = await AcquireHandleAsync( - (cancelId, buffer, length) => _sandboxConnect(cancelId, nativeName.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxConnect(cancelId, nativeName.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); return new Sandbox(this, name, handle); } - internal async Task StartAsync(string name, bool detached, CancellationToken cancellationToken) + internal async Task StartAsync( + string name, + bool detached, + CancellationToken cancellationToken + ) { using var nativeName = new Utf8String(name); var handle = await AcquireHandleAsync( - (cancelId, buffer, length) => _sandboxStart(cancelId, nativeName.Pointer, detached, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxStart(cancelId, nativeName.Pointer, detached, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); return new Sandbox(this, name, handle); } - internal async Task> ListAsync(string filterJson, CancellationToken cancellationToken) + internal async Task> ListAsync( + string filterJson, + CancellationToken cancellationToken + ) { using var nativeFilter = new Utf8String(filterJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxList(cancelId, nativeFilter.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); - return Deserialize>(json).Select(item => new SandboxHandle(this, item.ToMetadata())).ToArray(); + (cancelId, buffer, length) => + _sandboxList(cancelId, nativeFilter.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); + return Deserialize>(json) + .Select(item => new SandboxHandle(this, item.ToMetadata())) + .ToArray(); } - internal Task RemoveAsync(string name, CancellationToken cancellationToken) => InvokeByNameAsync(_sandboxRemove, name, cancellationToken); + internal Task RemoveAsync(string name, CancellationToken cancellationToken) => + InvokeByNameAsync(_sandboxRemove, name, cancellationToken); - internal Task StopByNameAsync(string name, ulong timeoutMilliseconds, CancellationToken cancellationToken) => - InvokeByNameAsync(_sandboxHandleStop, name, timeoutMilliseconds, cancellationToken); + internal Task StopByNameAsync( + string name, + ulong timeoutMilliseconds, + CancellationToken cancellationToken + ) => InvokeByNameAsync(_sandboxHandleStop, name, timeoutMilliseconds, cancellationToken); internal Task RequestStopByNameAsync(string name, CancellationToken cancellationToken) => InvokeByNameAsync(_sandboxHandleRequestStop, name, cancellationToken); - internal Task KillByNameAsync(string name, ulong timeoutMilliseconds, CancellationToken cancellationToken) => - InvokeByNameAsync(_sandboxHandleKill, name, timeoutMilliseconds, cancellationToken); + internal Task KillByNameAsync( + string name, + ulong timeoutMilliseconds, + CancellationToken cancellationToken + ) => InvokeByNameAsync(_sandboxHandleKill, name, timeoutMilliseconds, cancellationToken); internal Task RequestKillByNameAsync(string name, CancellationToken cancellationToken) => InvokeByNameAsync(_sandboxHandleRequestKill, name, cancellationToken); @@ -402,36 +485,81 @@ internal Task RequestKillByNameAsync(string name, CancellationToken cancellation internal Task RequestDrainByNameAsync(string name, CancellationToken cancellationToken) => InvokeByNameAsync(_sandboxHandleRequestDrain, name, cancellationToken); - internal async Task WaitUntilStoppedByNameAsync(string name, CancellationToken cancellationToken) => - ParseStopResult(await InvokeByNameWithResultAsync(_sandboxHandleWaitUntilStopped, name, cancellationToken).ConfigureAwait(false)); - - internal async Task PingByNameAsync(string name, CancellationToken cancellationToken) => - ParsePingResult(await InvokeByNameWithResultAsync(_sandboxHandlePing, name, cancellationToken).ConfigureAwait(false)); - - internal async Task TouchByNameAsync(string name, CancellationToken cancellationToken) => - ParseTouchResult(await InvokeByNameWithResultAsync(_sandboxHandleTouch, name, cancellationToken).ConfigureAwait(false)); - - internal async Task ModifyByNameAsync(string name, string optionsJson, CancellationToken cancellationToken) + internal async Task WaitUntilStoppedByNameAsync( + string name, + CancellationToken cancellationToken + ) => + ParseStopResult( + await InvokeByNameWithResultAsync( + _sandboxHandleWaitUntilStopped, + name, + cancellationToken + ) + .ConfigureAwait(false) + ); + + internal async Task PingByNameAsync( + string name, + CancellationToken cancellationToken + ) => + ParsePingResult( + await InvokeByNameWithResultAsync(_sandboxHandlePing, name, cancellationToken) + .ConfigureAwait(false) + ); + + internal async Task TouchByNameAsync( + string name, + CancellationToken cancellationToken + ) => + ParseTouchResult( + await InvokeByNameWithResultAsync(_sandboxHandleTouch, name, cancellationToken) + .ConfigureAwait(false) + ); + + internal async Task ModifyByNameAsync( + string name, + string optionsJson, + CancellationToken cancellationToken + ) { using var nativeName = new Utf8String(name); using var nativeOptions = new Utf8String(optionsJson); return await InvokeAsync( - (cancelId, buffer, length) => _sandboxHandleModify( - cancelId, - nativeName.Pointer, - nativeOptions.Pointer, - buffer, - length), - cancellationToken).ConfigureAwait(false); - } - - internal async Task ExecAsync(ulong handle, string command, string optionsJson, CancellationToken cancellationToken) + (cancelId, buffer, length) => + _sandboxHandleModify( + cancelId, + nativeName.Pointer, + nativeOptions.Pointer, + buffer, + length + ), + cancellationToken + ) + .ConfigureAwait(false); + } + + internal async Task ExecAsync( + ulong handle, + string command, + string optionsJson, + CancellationToken cancellationToken + ) { using var nativeCommand = new Utf8String(command); using var nativeOptions = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxExec(cancelId, handle, nativeCommand.Pointer, nativeOptions.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxExec( + cancelId, + handle, + nativeCommand.Pointer, + nativeOptions.Pointer, + buffer, + length + ), + cancellationToken + ) + .ConfigureAwait(false); var response = Deserialize(json); return new ExecResult(response.Stdout, response.Stderr, response.ExitCode ?? -1); } @@ -440,67 +568,110 @@ internal async Task ExecStreamAsync( ulong handle, string command, string optionsJson, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var nativeCommand = new Utf8String(command); using var nativeOptions = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxExecStream( - cancelId, - handle, - nativeCommand.Pointer, - nativeOptions.Pointer, - buffer, - length), - cancellationToken).ConfigureAwait(false); - return await ParseOwnedHandleAsync(json, "exec_handle", ExecCloseAsync).ConfigureAwait(false); - } - - internal string ExecId(ulong handle) => Deserialize( - Invoke((buffer, length) => _execId(handle, buffer, length))).Id; - - internal async Task ExecReceiveAsync(ulong handle, CancellationToken cancellationToken) => - ParseExecEvent(await InvokeExecAsync(_execReceive, handle, cancellationToken).ConfigureAwait(false)); + (cancelId, buffer, length) => + _sandboxExecStream( + cancelId, + handle, + nativeCommand.Pointer, + nativeOptions.Pointer, + buffer, + length + ), + cancellationToken + ) + .ConfigureAwait(false); + return await ParseOwnedHandleAsync(json, "exec_handle", ExecCloseAsync) + .ConfigureAwait(false); + } + + internal string ExecId(ulong handle) => + Deserialize(Invoke((buffer, length) => _execId(handle, buffer, length))).Id; + + internal async Task ExecReceiveAsync( + ulong handle, + CancellationToken cancellationToken + ) => + ParseExecEvent( + await InvokeExecAsync(_execReceive, handle, cancellationToken).ConfigureAwait(false) + ); - internal async Task ExecCollectAsync(ulong handle, CancellationToken cancellationToken) => - ParseExecCollect(await InvokeExecAsync(_execCollect, handle, cancellationToken).ConfigureAwait(false)); + internal async Task ExecCollectAsync( + ulong handle, + CancellationToken cancellationToken + ) => + ParseExecCollect( + await InvokeExecAsync(_execCollect, handle, cancellationToken).ConfigureAwait(false) + ); internal async Task ExecWaitAsync(ulong handle, CancellationToken cancellationToken) => - Deserialize(await InvokeExecAsync(_execWait, handle, cancellationToken).ConfigureAwait(false)).ExitCode; + Deserialize( + await InvokeExecAsync(_execWait, handle, cancellationToken).ConfigureAwait(false) + ).ExitCode; internal Task ExecKillAsync(ulong handle, CancellationToken cancellationToken) => InvokeExecAsync(_execKill, handle, cancellationToken); - internal Task ExecSignalAsync(ulong handle, int signal, CancellationToken cancellationToken) => InvokeAsync( - (cancelId, buffer, length) => _execSignal(cancelId, handle, signal, buffer, length), - cancellationToken); + internal Task ExecSignalAsync(ulong handle, int signal, CancellationToken cancellationToken) => + InvokeAsync( + (cancelId, buffer, length) => _execSignal(cancelId, handle, signal, buffer, length), + cancellationToken + ); - internal Task ExecResizeAsync(ulong handle, ushort rows, ushort columns, CancellationToken cancellationToken) => InvokeAsync( - (cancelId, buffer, length) => _execResize(cancelId, handle, rows, columns, buffer, length), - cancellationToken); + internal Task ExecResizeAsync( + ulong handle, + ushort rows, + ushort columns, + CancellationToken cancellationToken + ) => + InvokeAsync( + (cancelId, buffer, length) => + _execResize(cancelId, handle, rows, columns, buffer, length), + cancellationToken + ); - internal async Task ExecStdinWriteAsync(ulong handle, ReadOnlyMemory data, CancellationToken cancellationToken) + internal async Task ExecStdinWriteAsync( + ulong handle, + ReadOnlyMemory data, + CancellationToken cancellationToken + ) { using var encoded = new Utf8String(Convert.ToBase64String(data.Span)); await InvokeAsync( - (cancelId, buffer, length) => _execStdinWrite(cancelId, handle, encoded.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _execStdinWrite(cancelId, handle, encoded.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } internal Task ExecStdinCloseAsync(ulong handle, CancellationToken cancellationToken) => InvokeAsync( (cancelId, buffer, length) => _execStdinClose(cancelId, handle, buffer, length), cancellationToken, - checkInitialCancellation: false); + checkInitialCancellation: false + ); internal Task ExecCloseAsync(ulong handle, CancellationToken cancellationToken) => InvokeExecAsync(_execClose, handle, cancellationToken); - internal async Task StopAsync(ulong handle, ulong timeoutMilliseconds, CancellationToken cancellationToken) + internal async Task StopAsync( + ulong handle, + ulong timeoutMilliseconds, + CancellationToken cancellationToken + ) { await InvokeAsync( - (cancelId, buffer, length) => _sandboxStop(cancelId, handle, timeoutMilliseconds, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxStop(cancelId, handle, timeoutMilliseconds, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } internal Task RequestStopAsync(ulong handle, CancellationToken cancellationToken) => @@ -508,13 +679,22 @@ internal Task RequestStopAsync(ulong handle, CancellationToken cancellationToken internal async Task StopAndWaitAsync(ulong handle, CancellationToken cancellationToken) => Deserialize( - await InvokeHandleAsync(_sandboxStopAndWait, handle, cancellationToken).ConfigureAwait(false)).ExitCode; + await InvokeHandleAsync(_sandboxStopAndWait, handle, cancellationToken) + .ConfigureAwait(false) + ).ExitCode; - internal async Task KillAsync(ulong handle, ulong timeoutMilliseconds, CancellationToken cancellationToken) + internal async Task KillAsync( + ulong handle, + ulong timeoutMilliseconds, + CancellationToken cancellationToken + ) { await InvokeAsync( - (cancelId, buffer, length) => _sandboxKill(cancelId, handle, timeoutMilliseconds, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxKill(cancelId, handle, timeoutMilliseconds, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } internal Task RequestKillAsync(ulong handle, CancellationToken cancellationToken) => @@ -528,25 +708,44 @@ internal Task RequestDrainAsync(ulong handle, CancellationToken cancellationToke internal async Task WaitAsync(ulong handle, CancellationToken cancellationToken) { - var json = await InvokeHandleAsync(_sandboxWait, handle, cancellationToken).ConfigureAwait(false); + var json = await InvokeHandleAsync(_sandboxWait, handle, cancellationToken) + .ConfigureAwait(false); return Deserialize(json).ExitCode; } - internal async Task WaitUntilStoppedAsync(ulong handle, CancellationToken cancellationToken) => - ParseStopResult(await InvokeHandleAsync(_sandboxWaitUntilStopped, handle, cancellationToken).ConfigureAwait(false)); - - internal async Task PingAsync(ulong handle, CancellationToken cancellationToken) => - ParsePingResult(await InvokeHandleAsync(_sandboxPing, handle, cancellationToken).ConfigureAwait(false)); + internal async Task WaitUntilStoppedAsync( + ulong handle, + CancellationToken cancellationToken + ) => + ParseStopResult( + await InvokeHandleAsync(_sandboxWaitUntilStopped, handle, cancellationToken) + .ConfigureAwait(false) + ); + + internal async Task PingAsync( + ulong handle, + CancellationToken cancellationToken + ) => + ParsePingResult( + await InvokeHandleAsync(_sandboxPing, handle, cancellationToken).ConfigureAwait(false) + ); - internal async Task TouchAsync(ulong handle, CancellationToken cancellationToken) => - ParseTouchResult(await InvokeHandleAsync(_sandboxTouch, handle, cancellationToken).ConfigureAwait(false)); + internal async Task TouchAsync( + ulong handle, + CancellationToken cancellationToken + ) => + ParseTouchResult( + await InvokeHandleAsync(_sandboxTouch, handle, cancellationToken).ConfigureAwait(false) + ); internal async Task DetachAsync(ulong handle, CancellationToken cancellationToken) { await InvokeAsync( - (cancelId, buffer, length) => _sandboxDetach(cancelId, handle, buffer, length), - cancellationToken, - checkInitialCancellation: false).ConfigureAwait(false); + (cancelId, buffer, length) => _sandboxDetach(cancelId, handle, buffer, length), + cancellationToken, + checkInitialCancellation: false + ) + .ConfigureAwait(false); } internal bool OwnsLifecycle(ulong handle) @@ -558,118 +757,164 @@ internal bool OwnsLifecycle(ulong handle) internal async Task CloseAsync(ulong handle, CancellationToken cancellationToken) { await InvokeAsync( - (cancelId, buffer, length) => _sandboxClose(cancelId, handle, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => _sandboxClose(cancelId, handle, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } - internal async Task ModifyAsync(ulong handle, string optionsJson, CancellationToken cancellationToken) + internal async Task ModifyAsync( + ulong handle, + string optionsJson, + CancellationToken cancellationToken + ) { using var nativeOptions = new Utf8String(optionsJson); return await InvokeAsync( - (cancelId, buffer, length) => _sandboxModify(cancelId, handle, nativeOptions.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxModify(cancelId, handle, nativeOptions.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } internal async Task AttachAsync( ulong handle, string command, string optionsJson, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var nativeCommand = new Utf8String(command); using var nativeOptions = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxAttach( - cancelId, - handle, - nativeCommand.Pointer, - nativeOptions.Pointer, - buffer, - length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxAttach( + cancelId, + handle, + nativeCommand.Pointer, + nativeOptions.Pointer, + buffer, + length + ), + cancellationToken + ) + .ConfigureAwait(false); return Deserialize(json).ExitCode - ?? throw new InvalidDataException("The native attach response did not include an exit code."); + ?? throw new InvalidDataException( + "The native attach response did not include an exit code." + ); } internal async Task AttachShellAsync(ulong handle, CancellationToken cancellationToken) { - var json = await InvokeHandleAsync(_sandboxAttachShell, handle, cancellationToken).ConfigureAwait(false); + var json = await InvokeHandleAsync(_sandboxAttachShell, handle, cancellationToken) + .ConfigureAwait(false); return Deserialize(json).ExitCode - ?? throw new InvalidDataException("The native shell attach response did not include an exit code."); + ?? throw new InvalidDataException( + "The native shell attach response did not include an exit code." + ); } internal Task RemovePersistedAsync(ulong handle, CancellationToken cancellationToken) => InvokeConsumingHandleAsync(_sandboxRemovePersisted, handle, cancellationToken); - internal async Task SshConnectAsync(ulong sandboxHandle, string optionsJson, CancellationToken cancellationToken) + internal async Task SshConnectAsync( + ulong sandboxHandle, + string optionsJson, + CancellationToken cancellationToken + ) { using var nativeOptions = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxSshConnect( - cancelId, - sandboxHandle, - nativeOptions.Pointer, - buffer, - length), - cancellationToken).ConfigureAwait(false); - return await ParseOwnedHandleAsync(json, "client_handle", SshClientCloseAsync).ConfigureAwait(false); - } - - internal async Task SshServerAsync(ulong sandboxHandle, string optionsJson, CancellationToken cancellationToken) + (cancelId, buffer, length) => + _sandboxSshConnect( + cancelId, + sandboxHandle, + nativeOptions.Pointer, + buffer, + length + ), + cancellationToken + ) + .ConfigureAwait(false); + return await ParseOwnedHandleAsync(json, "client_handle", SshClientCloseAsync) + .ConfigureAwait(false); + } + + internal async Task SshServerAsync( + ulong sandboxHandle, + string optionsJson, + CancellationToken cancellationToken + ) { using var nativeOptions = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxSshServer( - cancelId, - sandboxHandle, - nativeOptions.Pointer, - buffer, - length), - cancellationToken).ConfigureAwait(false); - return await ParseOwnedHandleAsync(json, "server_handle", SshServerCloseAsync).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxSshServer( + cancelId, + sandboxHandle, + nativeOptions.Pointer, + buffer, + length + ), + cancellationToken + ) + .ConfigureAwait(false); + return await ParseOwnedHandleAsync(json, "server_handle", SshServerCloseAsync) + .ConfigureAwait(false); } internal async Task SshClientExecAsync( ulong clientHandle, string command, string optionsJson, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var nativeCommand = new Utf8String(command); using var nativeOptions = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sshClientExec( - cancelId, - clientHandle, - nativeCommand.Pointer, - nativeOptions.Pointer, - buffer, - length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _sshClientExec( + cancelId, + clientHandle, + nativeCommand.Pointer, + nativeOptions.Pointer, + buffer, + length + ), + cancellationToken + ) + .ConfigureAwait(false); return ParseSshOutput(json); } internal async Task SshClientAttachAsync( ulong clientHandle, string optionsJson, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var nativeOptions = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sshClientAttach( - cancelId, - clientHandle, - nativeOptions.Pointer, - buffer, - length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _sshClientAttach(cancelId, clientHandle, nativeOptions.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); return Deserialize(json).Status; } - internal async Task SshClientSftpAsync(ulong clientHandle, CancellationToken cancellationToken) + internal async Task SshClientSftpAsync( + ulong clientHandle, + CancellationToken cancellationToken + ) { - var json = await InvokeHandleAsync(_sshClientSftp, clientHandle, cancellationToken).ConfigureAwait(false); - return await ParseOwnedHandleAsync(json, "sftp_handle", SftpCloseAsync).ConfigureAwait(false); + var json = await InvokeHandleAsync(_sshClientSftp, clientHandle, cancellationToken) + .ConfigureAwait(false); + return await ParseOwnedHandleAsync(json, "sftp_handle", SftpCloseAsync) + .ConfigureAwait(false); } internal Task SshClientCloseAsync(ulong handle, CancellationToken cancellationToken) => @@ -678,75 +923,158 @@ internal Task SshClientCloseAsync(ulong handle, CancellationToken cancellationTo internal Task SshServerCloseAsync(ulong handle, CancellationToken cancellationToken) => InvokeConsumingHandleAsync(_sshServerClose, handle, cancellationToken); - internal Task SshServerServeConnectionAsync(ulong handle, CancellationToken cancellationToken) => - InvokeHandleAsync(_sshServerServeConnection, handle, cancellationToken); + internal Task SshServerServeConnectionAsync( + ulong handle, + CancellationToken cancellationToken + ) => InvokeHandleAsync(_sshServerServeConnection, handle, cancellationToken); - internal Task SshServerServeStandardIoAsync(ulong handle, CancellationToken cancellationToken) => - InvokeHandleAsync(_sshServerServeStandardIo, handle, cancellationToken); + internal Task SshServerServeStandardIoAsync( + ulong handle, + CancellationToken cancellationToken + ) => InvokeHandleAsync(_sshServerServeStandardIo, handle, cancellationToken); - internal async Task SftpReadAsync(ulong handle, string path, CancellationToken cancellationToken) + internal async Task SftpReadAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) { - var json = await InvokeHandleStringAsync(_sftpRead, handle, path, cancellationToken).ConfigureAwait(false); + var json = await InvokeHandleStringAsync(_sftpRead, handle, path, cancellationToken) + .ConfigureAwait(false); return Convert.FromBase64String(Deserialize(json).Data); } - internal Task SftpWriteAsync(ulong handle, string path, ReadOnlyMemory data, CancellationToken cancellationToken) => - InvokeHandleTwoStringsAsync(_sftpWrite, handle, path, Convert.ToBase64String(data.Span), cancellationToken); + internal Task SftpWriteAsync( + ulong handle, + string path, + ReadOnlyMemory data, + CancellationToken cancellationToken + ) => + InvokeHandleTwoStringsAsync( + _sftpWrite, + handle, + path, + Convert.ToBase64String(data.Span), + cancellationToken + ); internal Task SftpMkdirAsync(ulong handle, string path, CancellationToken cancellationToken) => InvokeHandleStringAsync(_sftpMkdir, handle, path, cancellationToken); - internal Task SftpRemoveFileAsync(ulong handle, string path, CancellationToken cancellationToken) => - InvokeHandleStringAsync(_sftpRemoveFile, handle, path, cancellationToken); + internal Task SftpRemoveFileAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) => InvokeHandleStringAsync(_sftpRemoveFile, handle, path, cancellationToken); - internal Task SftpRemoveDirectoryAsync(ulong handle, string path, CancellationToken cancellationToken) => - InvokeHandleStringAsync(_sftpRemoveDir, handle, path, cancellationToken); + internal Task SftpRemoveDirectoryAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) => InvokeHandleStringAsync(_sftpRemoveDir, handle, path, cancellationToken); internal Task SftpRenameAsync( ulong handle, string oldPath, string newPath, - CancellationToken cancellationToken) => - InvokeHandleTwoStringsAsync(_sftpRename, handle, oldPath, newPath, cancellationToken); + CancellationToken cancellationToken + ) => InvokeHandleTwoStringsAsync(_sftpRename, handle, oldPath, newPath, cancellationToken); - internal async Task SftpRealPathAsync(ulong handle, string path, CancellationToken cancellationToken) => + internal async Task SftpRealPathAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) => Deserialize( - await InvokeHandleStringAsync(_sftpRealPath, handle, path, cancellationToken).ConfigureAwait(false)).Path; + await InvokeHandleStringAsync(_sftpRealPath, handle, path, cancellationToken) + .ConfigureAwait(false) + ).Path; - internal async Task SftpReadLinkAsync(ulong handle, string path, CancellationToken cancellationToken) => + internal async Task SftpReadLinkAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) => Deserialize( - await InvokeHandleStringAsync(_sftpReadLink, handle, path, cancellationToken).ConfigureAwait(false)).Target; + await InvokeHandleStringAsync(_sftpReadLink, handle, path, cancellationToken) + .ConfigureAwait(false) + ).Target; internal Task SftpSymlinkAsync( ulong handle, string target, string linkPath, - CancellationToken cancellationToken) => - InvokeHandleTwoStringsAsync(_sftpSymlink, handle, target, linkPath, cancellationToken); + CancellationToken cancellationToken + ) => InvokeHandleTwoStringsAsync(_sftpSymlink, handle, target, linkPath, cancellationToken); internal Task SftpCloseAsync(ulong handle, CancellationToken cancellationToken) => InvokeConsumingHandleAsync(_sftpClose, handle, cancellationToken); - internal async Task FsReadAsync(ulong handle, string path, CancellationToken cancellationToken) + internal async Task FsReadAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) { - var json = await InvokeHandleStringAsync(_fsRead, handle, path, cancellationToken).ConfigureAwait(false); + var json = await InvokeHandleStringAsync(_fsRead, handle, path, cancellationToken) + .ConfigureAwait(false); return Convert.FromBase64String(Deserialize(json).Data); } - internal Task FsWriteAsync(ulong handle, string path, byte[] data, CancellationToken cancellationToken) => - InvokeHandleTwoStringsAsync(_fsWrite, handle, path, Convert.ToBase64String(data), cancellationToken); - - internal async Task> FsListAsync(ulong handle, string path, CancellationToken cancellationToken) => - Deserialize>(await InvokeHandleStringAsync(_fsList, handle, path, cancellationToken).ConfigureAwait(false)); - - internal async Task FsStatAsync(ulong handle, string path, CancellationToken cancellationToken) => - Deserialize(await InvokeHandleStringAsync(_fsStat, handle, path, cancellationToken).ConfigureAwait(false)); - - internal Task FsCopyFromHostAsync(ulong handle, string hostPath, string guestPath, CancellationToken cancellationToken) => - InvokeHandleTwoStringsAsync(_fsCopyFromHost, handle, hostPath, guestPath, cancellationToken); - - internal Task FsCopyToHostAsync(ulong handle, string guestPath, string hostPath, CancellationToken cancellationToken) => - InvokeHandleTwoStringsAsync(_fsCopyToHost, handle, guestPath, hostPath, cancellationToken); + internal Task FsWriteAsync( + ulong handle, + string path, + byte[] data, + CancellationToken cancellationToken + ) => + InvokeHandleTwoStringsAsync( + _fsWrite, + handle, + path, + Convert.ToBase64String(data), + cancellationToken + ); + + internal async Task> FsListAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) => + Deserialize>( + await InvokeHandleStringAsync(_fsList, handle, path, cancellationToken) + .ConfigureAwait(false) + ); + + internal async Task FsStatAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) => + Deserialize( + await InvokeHandleStringAsync(_fsStat, handle, path, cancellationToken) + .ConfigureAwait(false) + ); + + internal Task FsCopyFromHostAsync( + ulong handle, + string hostPath, + string guestPath, + CancellationToken cancellationToken + ) => + InvokeHandleTwoStringsAsync( + _fsCopyFromHost, + handle, + hostPath, + guestPath, + cancellationToken + ); + + internal Task FsCopyToHostAsync( + ulong handle, + string guestPath, + string hostPath, + CancellationToken cancellationToken + ) => InvokeHandleTwoStringsAsync(_fsCopyToHost, handle, guestPath, hostPath, cancellationToken); internal Task FsMkdirAsync(ulong handle, string path, CancellationToken cancellationToken) => InvokeHandleStringAsync(_fsMkdir, handle, path, cancellationToken); @@ -754,32 +1082,64 @@ internal Task FsMkdirAsync(ulong handle, string path, CancellationToken cancella internal Task FsRemoveAsync(ulong handle, string path, CancellationToken cancellationToken) => InvokeHandleStringAsync(_fsRemove, handle, path, cancellationToken); - internal Task FsRemoveDirAsync(ulong handle, string path, CancellationToken cancellationToken) => - InvokeHandleStringAsync(_fsRemoveDir, handle, path, cancellationToken); - - internal Task FsCopyAsync(ulong handle, string source, string destination, CancellationToken cancellationToken) => - InvokeHandleTwoStringsAsync(_fsCopy, handle, source, destination, cancellationToken); + internal Task FsRemoveDirAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) => InvokeHandleStringAsync(_fsRemoveDir, handle, path, cancellationToken); - internal Task FsRenameAsync(ulong handle, string source, string destination, CancellationToken cancellationToken) => - InvokeHandleTwoStringsAsync(_fsRename, handle, source, destination, cancellationToken); + internal Task FsCopyAsync( + ulong handle, + string source, + string destination, + CancellationToken cancellationToken + ) => InvokeHandleTwoStringsAsync(_fsCopy, handle, source, destination, cancellationToken); - internal async Task FsExistsAsync(ulong handle, string path, CancellationToken cancellationToken) => - Deserialize(await InvokeHandleStringAsync(_fsExists, handle, path, cancellationToken).ConfigureAwait(false)).Exists; + internal Task FsRenameAsync( + ulong handle, + string source, + string destination, + CancellationToken cancellationToken + ) => InvokeHandleTwoStringsAsync(_fsRename, handle, source, destination, cancellationToken); - internal async Task FsReadStreamAsync(ulong handle, string path, CancellationToken cancellationToken) + internal async Task FsExistsAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) => + Deserialize( + await InvokeHandleStringAsync(_fsExists, handle, path, cancellationToken) + .ConfigureAwait(false) + ).Exists; + + internal async Task FsReadStreamAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) { - var json = await InvokeHandleStringAsync(_fsReadStream, handle, path, cancellationToken).ConfigureAwait(false); - return await ParseOwnedHandleAsync(json, "stream_handle", FsReadStreamCloseAsync).ConfigureAwait(false); + var json = await InvokeHandleStringAsync(_fsReadStream, handle, path, cancellationToken) + .ConfigureAwait(false); + return await ParseOwnedHandleAsync(json, "stream_handle", FsReadStreamCloseAsync) + .ConfigureAwait(false); } - internal async Task FsReadStreamReceiveAsync(ulong handle, CancellationToken cancellationToken) + internal async Task FsReadStreamReceiveAsync( + ulong handle, + CancellationToken cancellationToken + ) { var json = await InvokeAsync( - (cancelId, buffer, length) => _fsReadStreamReceive(cancelId, handle, buffer, length), - cancellationToken, - bufferSize: FilesystemStreamBufferSize).ConfigureAwait(false); + (cancelId, buffer, length) => + _fsReadStreamReceive(cancelId, handle, buffer, length), + cancellationToken, + bufferSize: FilesystemStreamBufferSize + ) + .ConfigureAwait(false); var response = Deserialize(json); - return response.Done ? null : Convert.FromBase64String(response.ChunkBase64 ?? string.Empty); + return response.Done + ? null + : Convert.FromBase64String(response.ChunkBase64 ?? string.Empty); } internal Task FsReadStreamCloseAsync(ulong handle, CancellationToken cancellationToken) @@ -789,140 +1149,222 @@ internal Task FsReadStreamCloseAsync(ulong handle, CancellationToken cancellatio return Task.CompletedTask; } - internal async Task FsWriteStreamAsync(ulong handle, string path, CancellationToken cancellationToken) + internal async Task FsWriteStreamAsync( + ulong handle, + string path, + CancellationToken cancellationToken + ) { - var json = await InvokeHandleStringAsync(_fsWriteStream, handle, path, cancellationToken).ConfigureAwait(false); - return await ParseOwnedHandleAsync(json, "stream_handle", FsWriteStreamCloseAsync).ConfigureAwait(false); + var json = await InvokeHandleStringAsync(_fsWriteStream, handle, path, cancellationToken) + .ConfigureAwait(false); + return await ParseOwnedHandleAsync(json, "stream_handle", FsWriteStreamCloseAsync) + .ConfigureAwait(false); } - internal async Task FsWriteStreamWriteAsync(ulong handle, ReadOnlyMemory data, CancellationToken cancellationToken) + internal async Task FsWriteStreamWriteAsync( + ulong handle, + ReadOnlyMemory data, + CancellationToken cancellationToken + ) { using var encoded = new Utf8String(Convert.ToBase64String(data.Span)); await InvokeAsync( - (cancelId, buffer, length) => _fsWriteStreamWrite(cancelId, handle, encoded.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + _fsWriteStreamWrite(cancelId, handle, encoded.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } internal Task FsWriteStreamCloseAsync(ulong handle, CancellationToken cancellationToken) => InvokeAsync( (cancelId, buffer, length) => _fsWriteStreamClose(cancelId, handle, buffer, length), cancellationToken, - checkInitialCancellation: false); + checkInitialCancellation: false + ); internal async Task> LogsAsync( ulong handle, string optionsJson, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var options = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxLogs(cancelId, handle, options.Pointer, buffer, length), - cancellationToken, - bufferSize: LogsBufferSize).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxLogs(cancelId, handle, options.Pointer, buffer, length), + cancellationToken, + bufferSize: LogsBufferSize + ) + .ConfigureAwait(false); return ParseLogEntries(json); } internal async Task> LogsByNameAsync( string name, string optionsJson, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var nativeName = new Utf8String(name); using var options = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxHandleLogs( - cancelId, - nativeName.Pointer, - options.Pointer, - buffer, - length), - cancellationToken, - bufferSize: LogsBufferSize).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxHandleLogs( + cancelId, + nativeName.Pointer, + options.Pointer, + buffer, + length + ), + cancellationToken, + bufferSize: LogsBufferSize + ) + .ConfigureAwait(false); return ParseLogEntries(json); } - internal async Task LogStreamAsync(ulong handle, string optionsJson, CancellationToken cancellationToken) + internal async Task LogStreamAsync( + ulong handle, + string optionsJson, + CancellationToken cancellationToken + ) { using var options = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxLogStream(cancelId, handle, options.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); - return await ParseOwnedHandleAsync(json, "stream_handle", LogCloseAsync).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxLogStream(cancelId, handle, options.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); + return await ParseOwnedHandleAsync(json, "stream_handle", LogCloseAsync) + .ConfigureAwait(false); } - internal async Task LogStreamByNameAsync(string name, string optionsJson, CancellationToken cancellationToken) + internal async Task LogStreamByNameAsync( + string name, + string optionsJson, + CancellationToken cancellationToken + ) { using var nativeName = new Utf8String(name); using var options = new Utf8String(optionsJson); var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxHandleLogStream( - cancelId, - nativeName.Pointer, - options.Pointer, - buffer, - length), - cancellationToken).ConfigureAwait(false); - return await ParseOwnedHandleAsync(json, "stream_handle", LogCloseAsync).ConfigureAwait(false); - } - - internal async Task LogReceiveAsync(ulong handle, CancellationToken cancellationToken) + (cancelId, buffer, length) => + _sandboxHandleLogStream( + cancelId, + nativeName.Pointer, + options.Pointer, + buffer, + length + ), + cancellationToken + ) + .ConfigureAwait(false); + return await ParseOwnedHandleAsync(json, "stream_handle", LogCloseAsync) + .ConfigureAwait(false); + } + + internal async Task LogReceiveAsync( + ulong handle, + CancellationToken cancellationToken + ) { var json = await InvokeAsync( - (cancelId, buffer, length) => _logReceive(cancelId, handle, buffer, length), - cancellationToken, - bufferSize: LogsBufferSize).ConfigureAwait(false); + (cancelId, buffer, length) => _logReceive(cancelId, handle, buffer, length), + cancellationToken, + bufferSize: LogsBufferSize + ) + .ConfigureAwait(false); return ParseLogEntry(json); } internal Task LogCloseAsync(ulong handle, CancellationToken cancellationToken) => InvokeSynchronousCloseAsync(_logClose, handle, cancellationToken); - internal async Task MetricsAsync(ulong handle, CancellationToken cancellationToken) => - ParseMetrics(await InvokeHandleAsync(_sandboxMetrics, handle, cancellationToken).ConfigureAwait(false)); - - internal async Task MetricsStreamAsync(ulong handle, ulong intervalMilliseconds, CancellationToken cancellationToken) + internal async Task MetricsAsync( + ulong handle, + CancellationToken cancellationToken + ) => + ParseMetrics( + await InvokeHandleAsync(_sandboxMetrics, handle, cancellationToken) + .ConfigureAwait(false) + ); + + internal async Task MetricsStreamAsync( + ulong handle, + ulong intervalMilliseconds, + CancellationToken cancellationToken + ) { var json = await InvokeAsync( - (cancelId, buffer, length) => _sandboxMetricsStream( - cancelId, - handle, - intervalMilliseconds, - buffer, - length), - cancellationToken).ConfigureAwait(false); - return await ParseOwnedHandleAsync(json, "stream_handle", MetricsCloseAsync).ConfigureAwait(false); + (cancelId, buffer, length) => + _sandboxMetricsStream(cancelId, handle, intervalMilliseconds, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); + return await ParseOwnedHandleAsync(json, "stream_handle", MetricsCloseAsync) + .ConfigureAwait(false); } - internal async Task MetricsReceiveAsync(ulong handle, CancellationToken cancellationToken) + internal async Task MetricsReceiveAsync( + ulong handle, + CancellationToken cancellationToken + ) { var json = await InvokeAsync( - (cancelId, buffer, length) => _metricsReceive(cancelId, handle, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => _metricsReceive(cancelId, handle, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); return Deserialize(json).Done ? null : ParseMetrics(json); } internal Task MetricsCloseAsync(ulong handle, CancellationToken cancellationToken) => InvokeSynchronousCloseAsync(_metricsClose, handle, cancellationToken); - internal async Task> AllMetricsAsync(CancellationToken cancellationToken) + internal async Task> AllMetricsAsync( + CancellationToken cancellationToken + ) { var json = await InvokeAsync( - (cancelId, buffer, length) => _allSandboxMetrics(cancelId, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => _allSandboxMetrics(cancelId, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); return Deserialize(json).Sandboxes; } - internal async Task MetricsByNameAsync(string name, CancellationToken cancellationToken) => - ParseMetrics(await InvokeByNameWithResultAsync(_sandboxHandleMetrics, name, cancellationToken).ConfigureAwait(false)); - - internal Task CreateVolumeAsync(string name, string optionsJson, CancellationToken cancellationToken) => - InvokeTwoStringsAndParseAsync(_volumeCreate, name, optionsJson, cancellationToken); + internal async Task MetricsByNameAsync( + string name, + CancellationToken cancellationToken + ) => + ParseMetrics( + await InvokeByNameWithResultAsync(_sandboxHandleMetrics, name, cancellationToken) + .ConfigureAwait(false) + ); + + internal Task CreateVolumeAsync( + string name, + string optionsJson, + CancellationToken cancellationToken + ) => + InvokeTwoStringsAndParseAsync( + _volumeCreate, + name, + optionsJson, + cancellationToken + ); internal Task GetVolumeAsync(string name, CancellationToken cancellationToken) => InvokeStringAndParseAsync(_volumeGet, name, cancellationToken); - internal async Task> ListVolumesAsync(CancellationToken cancellationToken) => - Deserialize>(await InvokeNoArgAsync(_volumeList, cancellationToken).ConfigureAwait(false)); + internal async Task> ListVolumesAsync( + CancellationToken cancellationToken + ) => + Deserialize>( + await InvokeNoArgAsync(_volumeList, cancellationToken).ConfigureAwait(false) + ); internal Task RemoveVolumeAsync(string name, CancellationToken cancellationToken) => InvokeStringAsync(_volumeRemove, name, cancellationToken); @@ -930,63 +1372,146 @@ internal Task RemoveVolumeAsync(string name, CancellationToken cancellationToken internal Task GetImageAsync(string reference, CancellationToken cancellationToken) => InvokeStringAndParseAsync(_imageGet, reference, cancellationToken); - internal async Task> ListImagesAsync(CancellationToken cancellationToken) => - Deserialize>(await InvokeNoArgAsync(_imageList, cancellationToken).ConfigureAwait(false)); + internal async Task> ListImagesAsync( + CancellationToken cancellationToken + ) => + Deserialize>( + await InvokeNoArgAsync(_imageList, cancellationToken).ConfigureAwait(false) + ); - internal Task InspectImageAsync(string reference, CancellationToken cancellationToken) => - InvokeStringAndParseAsync(_imageInspect, reference, cancellationToken); + internal Task InspectImageAsync( + string reference, + CancellationToken cancellationToken + ) => InvokeStringAndParseAsync(_imageInspect, reference, cancellationToken); - internal Task RemoveImageAsync(string reference, bool force, CancellationToken cancellationToken) => - InvokeStringBoolAsync(_imageRemove, reference, force, cancellationToken); + internal Task RemoveImageAsync( + string reference, + bool force, + CancellationToken cancellationToken + ) => InvokeStringBoolAsync(_imageRemove, reference, force, cancellationToken); internal async Task PruneImagesAsync(CancellationToken cancellationToken) => - Deserialize(await InvokeNoArgAsync(_imagePrune, cancellationToken).ConfigureAwait(false)); - - internal async Task> LoadImagesAsync(string inputPath, string tagsJson, CancellationToken cancellationToken) => - Deserialize>(await InvokeTwoStringsAsync(_imageLoad, inputPath, tagsJson, cancellationToken).ConfigureAwait(false)); - - internal Task SaveImagesAsync(string referencesJson, string outputPath, string format, CancellationToken cancellationToken) => - InvokeThreeStringsAsync(_imageSave, referencesJson, outputPath, format, cancellationToken); - - internal Task CreateSnapshotAsync(string sourceSandbox, string optionsJson, CancellationToken cancellationToken) => - InvokeTwoStringsAndParseAsync(_snapshotCreate, sourceSandbox, optionsJson, cancellationToken); - - internal Task OpenSnapshotAsync(string pathOrName, CancellationToken cancellationToken) => - InvokeStringAndParseAsync(_snapshotOpen, pathOrName, cancellationToken); - - internal Task VerifySnapshotAsync(string pathOrName, CancellationToken cancellationToken) => - InvokeStringAndParseAsync(_snapshotVerify, pathOrName, cancellationToken); - - internal Task GetSnapshotAsync(string nameOrDigest, CancellationToken cancellationToken) => - InvokeStringAndParseAsync(_snapshotGet, nameOrDigest, cancellationToken); - - internal async Task> ListSnapshotsAsync(CancellationToken cancellationToken) => - Deserialize>(await InvokeNoArgAsync(_snapshotList, cancellationToken).ConfigureAwait(false)); - - internal async Task> ListSnapshotDirectoryAsync(string directory, CancellationToken cancellationToken) => - Deserialize>(await InvokeStringAsync(_snapshotListDir, directory, cancellationToken).ConfigureAwait(false)); - - internal Task RemoveSnapshotAsync(string pathOrName, bool force, CancellationToken cancellationToken) => - InvokeStringBoolAsync(_snapshotRemove, pathOrName, force, cancellationToken); - - internal async Task ReindexSnapshotsAsync(string directory, CancellationToken cancellationToken) => - Deserialize(await InvokeStringAsync(_snapshotReindex, directory, cancellationToken).ConfigureAwait(false)).Indexed; - - internal Task ExportSnapshotAsync(string nameOrPath, string outputPath, string optionsJson, CancellationToken cancellationToken) => - InvokeThreeStringsAsync(_snapshotExport, nameOrPath, outputPath, optionsJson, cancellationToken); - - internal Task ImportSnapshotAsync(string archive, string destination, CancellationToken cancellationToken) => - InvokeTwoStringsAndParseAsync(_snapshotImport, archive, destination, cancellationToken); + Deserialize( + await InvokeNoArgAsync(_imagePrune, cancellationToken).ConfigureAwait(false) + ); + + internal async Task> LoadImagesAsync( + string inputPath, + string tagsJson, + CancellationToken cancellationToken + ) => + Deserialize>( + await InvokeTwoStringsAsync(_imageLoad, inputPath, tagsJson, cancellationToken) + .ConfigureAwait(false) + ); + + internal Task SaveImagesAsync( + string referencesJson, + string outputPath, + string format, + CancellationToken cancellationToken + ) => InvokeThreeStringsAsync(_imageSave, referencesJson, outputPath, format, cancellationToken); + + internal Task CreateSnapshotAsync( + string sourceSandbox, + string optionsJson, + CancellationToken cancellationToken + ) => + InvokeTwoStringsAndParseAsync( + _snapshotCreate, + sourceSandbox, + optionsJson, + cancellationToken + ); + + internal Task OpenSnapshotAsync( + string pathOrName, + CancellationToken cancellationToken + ) => InvokeStringAndParseAsync(_snapshotOpen, pathOrName, cancellationToken); + + internal Task VerifySnapshotAsync( + string pathOrName, + CancellationToken cancellationToken + ) => + InvokeStringAndParseAsync( + _snapshotVerify, + pathOrName, + cancellationToken + ); + + internal Task GetSnapshotAsync( + string nameOrDigest, + CancellationToken cancellationToken + ) => InvokeStringAndParseAsync(_snapshotGet, nameOrDigest, cancellationToken); + + internal async Task> ListSnapshotsAsync( + CancellationToken cancellationToken + ) => + Deserialize>( + await InvokeNoArgAsync(_snapshotList, cancellationToken).ConfigureAwait(false) + ); + + internal async Task> ListSnapshotDirectoryAsync( + string directory, + CancellationToken cancellationToken + ) => + Deserialize>( + await InvokeStringAsync(_snapshotListDir, directory, cancellationToken) + .ConfigureAwait(false) + ); + + internal Task RemoveSnapshotAsync( + string pathOrName, + bool force, + CancellationToken cancellationToken + ) => InvokeStringBoolAsync(_snapshotRemove, pathOrName, force, cancellationToken); + + internal async Task ReindexSnapshotsAsync( + string directory, + CancellationToken cancellationToken + ) => + Deserialize( + await InvokeStringAsync(_snapshotReindex, directory, cancellationToken) + .ConfigureAwait(false) + ).Indexed; + + internal Task ExportSnapshotAsync( + string nameOrPath, + string outputPath, + string optionsJson, + CancellationToken cancellationToken + ) => + InvokeThreeStringsAsync( + _snapshotExport, + nameOrPath, + outputPath, + optionsJson, + cancellationToken + ); + + internal Task ImportSnapshotAsync( + string archive, + string destination, + CancellationToken cancellationToken + ) => + InvokeTwoStringsAndParseAsync( + _snapshotImport, + archive, + destination, + cancellationToken + ); internal Task SnapshotByNameAsync( string sandboxName, string snapshotName, - CancellationToken cancellationToken) => + CancellationToken cancellationToken + ) => InvokeTwoStringsAndParseAsync( _sandboxHandleSnapshot, sandboxName, snapshotName, - cancellationToken); + cancellationToken + ); internal string AgentSocketPath(string name) { @@ -1005,7 +1530,8 @@ internal async Task AgentRequestAsync( ulong handle, byte flags, ReadOnlyMemory body, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { var input = body.ToArray(); var pinned = input.Length == 0 ? default : GCHandle.Alloc(input, GCHandleType.Pinned); @@ -1016,17 +1542,21 @@ internal async Task AgentRequestAsync( try { await InvokeRawAsync( - cancelId => _agentRequest( - cancelId, - handle, - flags, - input.Length == 0 ? 0 : pinned.AddrOfPinnedObject(), - checked((nuint)input.Length), - out id, - out outputFlags, - out output, - out outputLength), - cancellationToken).ConfigureAwait(false); + cancelId => + _agentRequest( + cancelId, + handle, + flags, + input.Length == 0 ? 0 : pinned.AddrOfPinnedObject(), + checked((nuint)input.Length), + out id, + out outputFlags, + out output, + out outputLength + ), + cancellationToken + ) + .ConfigureAwait(false); return new RawFrame(id, outputFlags, CopyRustBytes(output, outputLength)); } finally @@ -1043,7 +1573,8 @@ await InvokeRawAsync( ulong handle, byte flags, ReadOnlyMemory body, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { var input = body.ToArray(); var pinned = input.Length == 0 ? default : GCHandle.Alloc(input, GCHandleType.Pinned); @@ -1052,18 +1583,24 @@ await InvokeRawAsync( try { await InvokeRawAsync( - cancelId => _agentStreamOpen( - cancelId, - handle, - flags, - input.Length == 0 ? 0 : pinned.AddrOfPinnedObject(), - checked((nuint)input.Length), - out id, - out streamHandle), - cancellationToken).ConfigureAwait(false); + cancelId => + _agentStreamOpen( + cancelId, + handle, + flags, + input.Length == 0 ? 0 : pinned.AddrOfPinnedObject(), + checked((nuint)input.Length), + out id, + out streamHandle + ), + cancellationToken + ) + .ConfigureAwait(false); if (streamHandle == 0) { - throw new InvalidDataException("The native ABI returned an invalid agent stream handle."); + throw new InvalidDataException( + "The native ABI returned an invalid agent stream handle." + ); } return (id, streamHandle); @@ -1080,7 +1617,8 @@ await InvokeRawAsync( internal async Task AgentStreamNextAsync( ulong agentHandle, ulong streamHandle, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { nint output = 0; nuint outputLength = 0; @@ -1090,16 +1628,20 @@ await InvokeRawAsync( try { await InvokeRawAsync( - cancelId => _agentStreamNext( - cancelId, - agentHandle, - streamHandle, - out present, - out id, - out flags, - out output, - out outputLength), - cancellationToken).ConfigureAwait(false); + cancelId => + _agentStreamNext( + cancelId, + agentHandle, + streamHandle, + out present, + out id, + out flags, + out output, + out outputLength + ), + cancellationToken + ) + .ConfigureAwait(false); return present ? new RawFrame(id, flags, CopyRustBytes(output, outputLength)) : null; } finally @@ -1111,32 +1653,39 @@ await InvokeRawAsync( internal Task AgentStreamCloseAsync( ulong agentHandle, ulong streamHandle, - CancellationToken cancellationToken) => + CancellationToken cancellationToken + ) => InvokeRawAsync( cancelId => _agentStreamClose(cancelId, agentHandle, streamHandle), cancellationToken, - checkInitialCancellation: false); + checkInitialCancellation: false + ); internal async Task AgentSendAsync( ulong handle, uint id, byte flags, ReadOnlyMemory body, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { var input = body.ToArray(); var pinned = input.Length == 0 ? default : GCHandle.Alloc(input, GCHandleType.Pinned); try { await InvokeRawAsync( - cancelId => _agentSend( - cancelId, - handle, - id, - flags, - input.Length == 0 ? 0 : pinned.AddrOfPinnedObject(), - checked((nuint)input.Length)), - cancellationToken).ConfigureAwait(false); + cancelId => + _agentSend( + cancelId, + handle, + id, + flags, + input.Length == 0 ? 0 : pinned.AddrOfPinnedObject(), + checked((nuint)input.Length) + ), + cancellationToken + ) + .ConfigureAwait(false); } finally { @@ -1166,66 +1715,117 @@ internal Task AgentCloseAsync(ulong handle, CancellationToken cancellationToken) InvokeRawAsync( cancelId => _agentClose(cancelId, handle), cancellationToken, - checkInitialCancellation: false); + checkInitialCancellation: false + ); - private async Task InvokeStringAndParseAsync(StringFn call, string value, CancellationToken cancellationToken) => - Deserialize(await InvokeStringAsync(call, value, cancellationToken).ConfigureAwait(false)); + private async Task InvokeStringAndParseAsync( + StringFn call, + string value, + CancellationToken cancellationToken + ) => + Deserialize( + await InvokeStringAsync(call, value, cancellationToken).ConfigureAwait(false) + ); private async Task OpenAgentAsync( AgentOpenFn call, string value, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var nativeValue = new Utf8String(value); ulong handle = 0; await InvokeRawAsync( - cancelId => call(cancelId, nativeValue.Pointer, 0, out handle), - cancellationToken).ConfigureAwait(false); + cancelId => call(cancelId, nativeValue.Pointer, 0, out handle), + cancellationToken + ) + .ConfigureAwait(false); return handle != 0 ? handle : throw new InvalidDataException("The native ABI returned an invalid agent handle."); } - private async Task InvokeTwoStringsAndParseAsync(TwoStringsFn call, string first, string second, CancellationToken cancellationToken) => - Deserialize(await InvokeTwoStringsAsync(call, first, second, cancellationToken).ConfigureAwait(false)); - - private Task InvokeNoArgAsync(CancellableNoArgFn call, CancellationToken cancellationToken) => - InvokeAsync((cancelId, buffer, length) => call(cancelId, buffer, length), cancellationToken); + private async Task InvokeTwoStringsAndParseAsync( + TwoStringsFn call, + string first, + string second, + CancellationToken cancellationToken + ) => + Deserialize( + await InvokeTwoStringsAsync(call, first, second, cancellationToken) + .ConfigureAwait(false) + ); + + private Task InvokeNoArgAsync( + CancellableNoArgFn call, + CancellationToken cancellationToken + ) => + InvokeAsync( + (cancelId, buffer, length) => call(cancelId, buffer, length), + cancellationToken + ); - private Task InvokeExecAsync(ExecHandleFn call, ulong handle, CancellationToken cancellationToken) => - InvokeAsync((cancelId, buffer, length) => call(cancelId, handle, buffer, length), cancellationToken); + private Task InvokeExecAsync( + ExecHandleFn call, + ulong handle, + CancellationToken cancellationToken + ) => + InvokeAsync( + (cancelId, buffer, length) => call(cancelId, handle, buffer, length), + cancellationToken + ); - private Task InvokeSynchronousCloseAsync(StreamCloseFn call, ulong handle, CancellationToken cancellationToken) + private Task InvokeSynchronousCloseAsync( + StreamCloseFn call, + ulong handle, + CancellationToken cancellationToken + ) { cancellationToken.ThrowIfCancellationRequested(); Invoke((buffer, length) => call(handle, buffer, length)); return Task.CompletedTask; } - private Task InvokeConsumingHandleAsync( + private Task InvokeConsumingHandleAsync( SandboxHandleFn call, ulong handle, - CancellationToken cancellationToken) => + CancellationToken cancellationToken + ) => InvokeAsync( (cancelId, buffer, length) => call(cancelId, handle, buffer, length), cancellationToken, - checkInitialCancellation: false); + checkInitialCancellation: false + ); - private async Task InvokeStringAsync(StringFn call, string value, CancellationToken cancellationToken) + private async Task InvokeStringAsync( + StringFn call, + string value, + CancellationToken cancellationToken + ) { using var nativeValue = new Utf8String(value); return await InvokeAsync( - (cancelId, buffer, length) => call(cancelId, nativeValue.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => call(cancelId, nativeValue.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } - private async Task InvokeTwoStringsAsync(TwoStringsFn call, string first, string second, CancellationToken cancellationToken) + private async Task InvokeTwoStringsAsync( + TwoStringsFn call, + string first, + string second, + CancellationToken cancellationToken + ) { using var nativeFirst = new Utf8String(first); using var nativeSecond = new Utf8String(second); return await InvokeAsync( - (cancelId, buffer, length) => call(cancelId, nativeFirst.Pointer, nativeSecond.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + call(cancelId, nativeFirst.Pointer, nativeSecond.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } private async Task InvokeThreeStringsAsync( @@ -1233,44 +1833,57 @@ private async Task InvokeThreeStringsAsync( string first, string second, string third, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var nativeFirst = new Utf8String(first); using var nativeSecond = new Utf8String(second); using var nativeThird = new Utf8String(third); return await InvokeAsync( - (cancelId, buffer, length) => call( - cancelId, - nativeFirst.Pointer, - nativeSecond.Pointer, - nativeThird.Pointer, - buffer, - length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + call( + cancelId, + nativeFirst.Pointer, + nativeSecond.Pointer, + nativeThird.Pointer, + buffer, + length + ), + cancellationToken + ) + .ConfigureAwait(false); } private async Task InvokeStringBoolAsync( StringBoolFn call, string value, bool flag, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var nativeValue = new Utf8String(value); return await InvokeAsync( - (cancelId, buffer, length) => call(cancelId, nativeValue.Pointer, flag, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + call(cancelId, nativeValue.Pointer, flag, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } private async Task InvokeHandleStringAsync( SandboxHandleStringFn call, ulong handle, string value, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var nativeValue = new Utf8String(value); return await InvokeAsync( - (cancelId, buffer, length) => call(cancelId, handle, nativeValue.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + call(cancelId, handle, nativeValue.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } private async Task InvokeHandleTwoStringsAsync( @@ -1278,16 +1891,30 @@ private async Task InvokeHandleTwoStringsAsync( ulong handle, string first, string second, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var nativeFirst = new Utf8String(first); using var nativeSecond = new Utf8String(second); return await InvokeAsync( - (cancelId, buffer, length) => call(cancelId, handle, nativeFirst.Pointer, nativeSecond.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); - } - - private async Task AcquireHandleAsync(CancellableNativeCall call, CancellationToken cancellationToken) + (cancelId, buffer, length) => + call( + cancelId, + handle, + nativeFirst.Pointer, + nativeSecond.Pointer, + buffer, + length + ), + cancellationToken + ) + .ConfigureAwait(false); + } + + private async Task AcquireHandleAsync( + CancellableNativeCall call, + CancellationToken cancellationToken + ) { var json = await InvokeAsync(call, cancellationToken).ConfigureAwait(false); try @@ -1313,10 +1940,11 @@ private async Task AcquireHandleAsync(CancellableNativeCall call, Cancell } } - private async Task ParseOwnedHandleAsync( + private static async Task ParseOwnedHandleAsync( string json, string propertyName, - Func closeAsync) + Func closeAsync + ) { try { @@ -1324,9 +1952,17 @@ private async Task ParseOwnedHandleAsync( var handle = document.RootElement.GetProperty(propertyName).GetUInt64(); return handle != 0 ? handle - : throw new InvalidDataException($"The native ABI returned an invalid {propertyName}."); + : throw new InvalidDataException( + $"The native ABI returned an invalid {propertyName}." + ); } - catch (Exception exception) when (exception is JsonException or InvalidOperationException or KeyNotFoundException or InvalidDataException) + catch (Exception exception) + when (exception + is JsonException + or InvalidOperationException + or KeyNotFoundException + or InvalidDataException + ) { var handle = SalvageHandle(json, propertyName); if (handle != 0) @@ -1345,31 +1981,51 @@ private async Task ParseOwnedHandleAsync( } } - private async Task InvokeByNameAsync(SandboxByNameFn call, string name, CancellationToken cancellationToken) => - _ = await InvokeByNameWithResultAsync(call, name, cancellationToken).ConfigureAwait(false); + private async Task InvokeByNameAsync( + SandboxByNameFn call, + string name, + CancellationToken cancellationToken + ) => _ = await InvokeByNameWithResultAsync(call, name, cancellationToken).ConfigureAwait(false); - private async Task InvokeByNameWithResultAsync(SandboxByNameFn call, string name, CancellationToken cancellationToken) + private async Task InvokeByNameWithResultAsync( + SandboxByNameFn call, + string name, + CancellationToken cancellationToken + ) { using var nativeName = new Utf8String(name); return await InvokeAsync( - (cancelId, buffer, length) => call(cancelId, nativeName.Pointer, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => call(cancelId, nativeName.Pointer, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } private async Task InvokeByNameAsync( SandboxByNameTimeoutFn call, string name, ulong timeoutMilliseconds, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { using var nativeName = new Utf8String(name); await InvokeAsync( - (cancelId, buffer, length) => call(cancelId, nativeName.Pointer, timeoutMilliseconds, buffer, length), - cancellationToken).ConfigureAwait(false); + (cancelId, buffer, length) => + call(cancelId, nativeName.Pointer, timeoutMilliseconds, buffer, length), + cancellationToken + ) + .ConfigureAwait(false); } - private Task InvokeHandleAsync(SandboxHandleFn call, ulong handle, CancellationToken cancellationToken) => - InvokeAsync((cancelId, buffer, length) => call(cancelId, handle, buffer, length), cancellationToken); + private Task InvokeHandleAsync( + SandboxHandleFn call, + ulong handle, + CancellationToken cancellationToken + ) => + InvokeAsync( + (cancelId, buffer, length) => call(cancelId, handle, buffer, length), + cancellationToken + ); private string Invoke(NativeCall call) { @@ -1390,65 +2046,73 @@ private Task InvokeAsync( CancellableNativeCall call, CancellationToken cancellationToken, bool checkInitialCancellation = true, - int bufferSize = BufferSize) => Task.Run(() => - { - if (checkInitialCancellation) - { - cancellationToken.ThrowIfCancellationRequested(); - } - var buffer = new byte[bufferSize]; - var pinned = GCHandle.Alloc(buffer, GCHandleType.Pinned); - var cancelId = _cancelAlloc(); - using var registration = cancellationToken.Register(() => _cancelTrigger(cancelId)); - try + int bufferSize = BufferSize + ) => + Task.Run(() => { - var errorPointer = call(cancelId, pinned.AddrOfPinnedObject(), (nuint)buffer.Length); - if (errorPointer != 0 && cancellationToken.IsCancellationRequested) + if (checkInitialCancellation) { - _freeString(errorPointer); - throw new OperationCanceledException(cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); } + var buffer = new byte[bufferSize]; + var pinned = GCHandle.Alloc(buffer, GCHandleType.Pinned); + var cancelId = _cancelAlloc(); + using var registration = cancellationToken.Register(() => _cancelTrigger(cancelId)); + try + { + var errorPointer = call( + cancelId, + pinned.AddrOfPinnedObject(), + (nuint)buffer.Length + ); + if (errorPointer != 0 && cancellationToken.IsCancellationRequested) + { + _freeString(errorPointer); + throw new OperationCanceledException(cancellationToken); + } - ThrowIfError(errorPointer); - return ReadBuffer(buffer); - } - finally - { - _cancelUnregister(cancelId); - pinned.Free(); - } - }); + ThrowIfError(errorPointer); + return ReadBuffer(buffer); + } + finally + { + _cancelUnregister(cancelId); + pinned.Free(); + } + }); private Task InvokeRawAsync( RawNativeCall call, CancellationToken cancellationToken, - bool checkInitialCancellation = true) => Task.Run(() => - { - if (checkInitialCancellation) - { - cancellationToken.ThrowIfCancellationRequested(); - } - - var cancelId = _cancelAlloc(); - using var registration = cancellationToken.Register(() => _cancelTrigger(cancelId)); - try + bool checkInitialCancellation = true + ) => + Task.Run(() => { - var errorPointer = call(cancelId); - if (errorPointer != 0 && cancellationToken.IsCancellationRequested) + if (checkInitialCancellation) { - _freeString(errorPointer); - throw new OperationCanceledException(cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); } - ThrowIfError(errorPointer); - } - finally - { - _cancelUnregister(cancelId); - } - }); + var cancelId = _cancelAlloc(); + using var registration = cancellationToken.Register(() => _cancelTrigger(cancelId)); + try + { + var errorPointer = call(cancelId); + if (errorPointer != 0 && cancellationToken.IsCancellationRequested) + { + _freeString(errorPointer); + throw new OperationCanceledException(cancellationToken); + } - private byte[] CopyRustBytes(nint pointer, nuint length) + ThrowIfError(errorPointer); + } + finally + { + _cancelUnregister(cancelId); + } + }); + + private static byte[] CopyRustBytes(nint pointer, nuint length) { if (length == 0) { @@ -1457,7 +2121,9 @@ private byte[] CopyRustBytes(nint pointer, nuint length) if (pointer == 0) { - throw new InvalidDataException("The native ABI returned a null byte pointer with a non-zero length."); + throw new InvalidDataException( + "The native ABI returned a null byte pointer with a non-zero length." + ); } var result = new byte[checked((int)length)]; @@ -1496,9 +2162,12 @@ private void ThrowIfError(nint errorPointer) private static T Deserialize(string json) => JsonSerializer.Deserialize(json, JsonDefaults.Options) - ?? throw new InvalidDataException($"The native ABI returned an empty {typeof(T).Name} response."); + ?? throw new InvalidDataException( + $"The native ABI returned an empty {typeof(T).Name} response." + ); - internal static SandboxMetadata ParseMetadata(string json) => Deserialize(json).ToMetadata(); + internal static SandboxMetadata ParseMetadata(string json) => + Deserialize(json).ToMetadata(); internal static string ParseVersion(string json) => Deserialize(json).Version; @@ -1507,7 +2176,8 @@ internal static void ValidateVersion(string nativeVersion, string managedVersion if (!string.Equals(nativeVersion, managedVersion, StringComparison.Ordinal)) { throw new InvalidDataException( - $"The microsandbox native library version '{nativeVersion}' does not match managed SDK version '{managedVersion}'."); + $"The microsandbox native library version '{nativeVersion}' does not match managed SDK version '{managedVersion}'." + ); } } @@ -1520,13 +2190,17 @@ internal static SandboxStopResult ParseStopResult(string json) response.ExitCode, response.Signal, DateTimeOffset.FromUnixTimeSeconds(response.ObservedAtUnix), - response.Source); + response.Source + ); } internal static SandboxPingResult ParsePingResult(string json) { var response = Deserialize(json); - return new SandboxPingResult(response.Name, TimeSpan.FromMilliseconds(response.LatencyMilliseconds)); + return new SandboxPingResult( + response.Name, + TimeSpan.FromMilliseconds(response.LatencyMilliseconds) + ); } internal static SandboxTouchResult ParseTouchResult(string json) @@ -1538,12 +2212,15 @@ internal static SandboxTouchResult ParseTouchResult(string json) internal static IReadOnlyList ParseLogEntries(string json) { var entries = Deserialize>(json); - return entries.Select(entry => new LogEntry( - entry.Source, - entry.SessionId, - DateTimeOffset.FromUnixTimeMilliseconds(entry.TimestampMs), - Convert.FromBase64String(entry.DataBase64), - entry.Cursor)).ToArray(); + return entries + .Select(entry => new LogEntry( + entry.Source, + entry.SessionId, + DateTimeOffset.FromUnixTimeMilliseconds(entry.TimestampMs), + Convert.FromBase64String(entry.DataBase64), + entry.Cursor + )) + .ToArray(); } internal static LogEntry? ParseLogEntry(string json) @@ -1559,7 +2236,8 @@ internal static IReadOnlyList ParseLogEntries(string json) entry.SessionId, DateTimeOffset.FromUnixTimeMilliseconds(entry.TimestampMs), Convert.FromBase64String(entry.DataBase64), - entry.Cursor); + entry.Cursor + ); } internal static ExecEvent ParseExecEvent(string json) @@ -1568,13 +2246,19 @@ internal static ExecEvent ParseExecEvent(string json) return response.Event switch { "started" => new ExecStartedEvent(response.Pid), - "stdout" => new ExecStandardOutputEvent(Convert.FromBase64String(response.Data ?? string.Empty)), - "stderr" => new ExecStandardErrorEvent(Convert.FromBase64String(response.Data ?? string.Empty)), + "stdout" => new ExecStandardOutputEvent( + Convert.FromBase64String(response.Data ?? string.Empty) + ), + "stderr" => new ExecStandardErrorEvent( + Convert.FromBase64String(response.Data ?? string.Empty) + ), "exited" => new ExecExitedEvent(response.Code), "failed" => new ExecFailedEvent(ParseExecFailure(response.Error)), "stdin_error" => new ExecStdinErrorEvent(ParseExecFailure(response.Error)), "done" => ExecDoneEvent.Instance, - _ => throw new InvalidDataException($"The native ABI returned an unknown exec event '{response.Event}'."), + _ => throw new InvalidDataException( + $"The native ABI returned an unknown exec event '{response.Event}'." + ), }; } @@ -1584,7 +2268,8 @@ internal static ExecResult ParseExecCollect(string json) return new ExecResult( Encoding.UTF8.GetString(Convert.FromBase64String(response.StandardOutputBase64)), Encoding.UTF8.GetString(Convert.FromBase64String(response.StandardErrorBase64)), - response.ExitCode); + response.ExitCode + ); } internal static SshOutput ParseSshOutput(string json) @@ -1593,7 +2278,8 @@ internal static SshOutput ParseSshOutput(string json) return new SshOutput( response.Status, Convert.FromBase64String(response.StandardOutputBase64), - Convert.FromBase64String(response.StandardErrorBase64)); + Convert.FromBase64String(response.StandardErrorBase64) + ); } private static ExecFailure ParseExecFailure(JsonElement? error) @@ -1619,13 +2305,15 @@ private static ExecFailure ParseExecFailure(JsonElement? error) internal static IReadOnlyList ParseFilesystemEntries(string json) => Deserialize>(json); - internal static FilesystemStat ParseFilesystemStat(string json) => Deserialize(json); + internal static FilesystemStat ParseFilesystemStat(string json) => + Deserialize(json); internal static ImageDetail ParseImageDetail(string json) => Deserialize(json); internal static VolumeInfo ParseVolumeInfo(string json) => Deserialize(json); - internal static SnapshotArtifact ParseSnapshotArtifact(string json) => Deserialize(json); + internal static SnapshotArtifact ParseSnapshotArtifact(string json) => + Deserialize(json); internal static SnapshotInfo ParseSnapshotInfo(string json) => Deserialize(json); @@ -1642,19 +2330,26 @@ internal static ulong SalvageHandle(string json, string propertyName) var match = Regex.Match( json, $"\\\"{Regex.Escape(propertyName)}\\\"\\s*:\\s*(?[0-9]+)", - RegexOptions.CultureInvariant); - return match.Success && ulong.TryParse(match.Groups["handle"].Value, out var handle) ? handle : 0; + RegexOptions.CultureInvariant + ); + return match.Success && ulong.TryParse(match.Groups["handle"].Value, out var handle) + ? handle + : 0; } - private static T GetExport(nint library, string name) where T : Delegate => + private static T GetExport(nint library, string name) + where T : Delegate => Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(library, name)); private static string GetManagedVersion() { - var version = typeof(NativeApi).Assembly - .GetCustomAttribute()? - .InformationalVersion - ?? throw new InvalidOperationException("The Microsandbox assembly does not declare an informational version."); + var version = + typeof(NativeApi) + .Assembly.GetCustomAttribute() + ?.InformationalVersion + ?? throw new InvalidOperationException( + "The Microsandbox assembly does not declare an informational version." + ); return NormalizeManagedVersion(version); } @@ -1675,79 +2370,110 @@ private static IEnumerable CandidatePaths(string? explicitPath) yield return Path.GetFullPath(environmentPath); } - var fileName = OperatingSystem.IsWindows() - ? "microsandbox_go_ffi.dll" - : OperatingSystem.IsMacOS() ? "libmicrosandbox_go_ffi.dylib" : "libmicrosandbox_go_ffi.so"; - yield return Path.Combine(AppContext.BaseDirectory, "runtimes", RuntimeInformation.RuntimeIdentifier, "native", fileName); + var fileName = + OperatingSystem.IsWindows() ? "microsandbox_go_ffi.dll" + : OperatingSystem.IsMacOS() ? "libmicrosandbox_go_ffi.dylib" + : "libmicrosandbox_go_ffi.so"; + yield return Path.Combine( + AppContext.BaseDirectory, + "runtimes", + RuntimeInformation.RuntimeIdentifier, + "native", + fileName + ); yield return Path.Combine(AppContext.BaseDirectory, fileName); yield return fileName; } private sealed record CreateResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("handle")] ulong Handle); + [property: System.Text.Json.Serialization.JsonPropertyName("handle")] ulong Handle + ); private sealed record ExecResponse( [property: System.Text.Json.Serialization.JsonPropertyName("stdout")] string Stdout, [property: System.Text.Json.Serialization.JsonPropertyName("stderr")] string Stderr, - [property: System.Text.Json.Serialization.JsonPropertyName("exit_code")] int? ExitCode); + [property: System.Text.Json.Serialization.JsonPropertyName("exit_code")] int? ExitCode + ); private sealed record WaitResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("exit_code")] int? ExitCode); + [property: System.Text.Json.Serialization.JsonPropertyName("exit_code")] int? ExitCode + ); private sealed record IdResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("id")] string Id); + [property: System.Text.Json.Serialization.JsonPropertyName("id")] string Id + ); private sealed record ExecWaitResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("exit_code")] int ExitCode); + [property: System.Text.Json.Serialization.JsonPropertyName("exit_code")] int ExitCode + ); private sealed record ExecCollectResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("stdout_b64")] string StandardOutputBase64, - [property: System.Text.Json.Serialization.JsonPropertyName("stderr_b64")] string StandardErrorBase64, - [property: System.Text.Json.Serialization.JsonPropertyName("exit_code")] int ExitCode); + [property: System.Text.Json.Serialization.JsonPropertyName("stdout_b64")] + string StandardOutputBase64, + [property: System.Text.Json.Serialization.JsonPropertyName("stderr_b64")] + string StandardErrorBase64, + [property: System.Text.Json.Serialization.JsonPropertyName("exit_code")] int ExitCode + ); private sealed record SshOutputResponse( [property: System.Text.Json.Serialization.JsonPropertyName("status")] int Status, - [property: System.Text.Json.Serialization.JsonPropertyName("stdout")] string StandardOutputBase64, - [property: System.Text.Json.Serialization.JsonPropertyName("stderr")] string StandardErrorBase64); + [property: System.Text.Json.Serialization.JsonPropertyName("stdout")] + string StandardOutputBase64, + [property: System.Text.Json.Serialization.JsonPropertyName("stderr")] + string StandardErrorBase64 + ); private sealed record SshAttachResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("status")] int Status); + [property: System.Text.Json.Serialization.JsonPropertyName("status")] int Status + ); private sealed record SftpReadResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("data")] string Data); + [property: System.Text.Json.Serialization.JsonPropertyName("data")] string Data + ); private sealed record SftpPathResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("path")] string Path); + [property: System.Text.Json.Serialization.JsonPropertyName("path")] string Path + ); private sealed record SftpTargetResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("target")] string Target); + [property: System.Text.Json.Serialization.JsonPropertyName("target")] string Target + ); private sealed record AgentSocketPathResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("path")] string Path); + [property: System.Text.Json.Serialization.JsonPropertyName("path")] string Path + ); private sealed record ExecEventResponse( [property: System.Text.Json.Serialization.JsonPropertyName("event")] string Event, [property: System.Text.Json.Serialization.JsonPropertyName("pid")] uint Pid, [property: System.Text.Json.Serialization.JsonPropertyName("data")] string? Data, [property: System.Text.Json.Serialization.JsonPropertyName("code")] int Code, - [property: System.Text.Json.Serialization.JsonPropertyName("error")] JsonElement? Error); + [property: System.Text.Json.Serialization.JsonPropertyName("error")] JsonElement? Error + ); private sealed record OwnsLifecycleResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("owns")] bool Owns); + [property: System.Text.Json.Serialization.JsonPropertyName("owns")] bool Owns + ); private sealed record SandboxMetadataResponse( [property: System.Text.Json.Serialization.JsonPropertyName("name")] string Name, [property: System.Text.Json.Serialization.JsonPropertyName("status")] SandboxStatus Status, - [property: System.Text.Json.Serialization.JsonPropertyName("config_json")] string ConfigJson, - [property: System.Text.Json.Serialization.JsonPropertyName("created_at_unix")] long? CreatedAtUnix, - [property: System.Text.Json.Serialization.JsonPropertyName("updated_at_unix")] long? UpdatedAtUnix) - { - internal SandboxMetadata ToMetadata() => new( - Name, - Status, - ConfigJson, - CreatedAtUnix is { } created ? DateTimeOffset.FromUnixTimeSeconds(created) : null, - UpdatedAtUnix is { } updated ? DateTimeOffset.FromUnixTimeSeconds(updated) : null); + [property: System.Text.Json.Serialization.JsonPropertyName("config_json")] + string ConfigJson, + [property: System.Text.Json.Serialization.JsonPropertyName("created_at_unix")] + long? CreatedAtUnix, + [property: System.Text.Json.Serialization.JsonPropertyName("updated_at_unix")] + long? UpdatedAtUnix + ) + { + internal SandboxMetadata ToMetadata() => + new( + Name, + Status, + ConfigJson, + CreatedAtUnix is { } created ? DateTimeOffset.FromUnixTimeSeconds(created) : null, + UpdatedAtUnix is { } updated ? DateTimeOffset.FromUnixTimeSeconds(updated) : null + ); } private sealed record StopResponse( @@ -1755,50 +2481,66 @@ private sealed record StopResponse( [property: System.Text.Json.Serialization.JsonPropertyName("status")] SandboxStatus Status, [property: System.Text.Json.Serialization.JsonPropertyName("exit_code")] int? ExitCode, [property: System.Text.Json.Serialization.JsonPropertyName("signal")] int? Signal, - [property: System.Text.Json.Serialization.JsonPropertyName("observed_at_unix")] long ObservedAtUnix, - [property: System.Text.Json.Serialization.JsonPropertyName("source")] string? Source); + [property: System.Text.Json.Serialization.JsonPropertyName("observed_at_unix")] + long ObservedAtUnix, + [property: System.Text.Json.Serialization.JsonPropertyName("source")] string? Source + ); private sealed record PingResponse( [property: System.Text.Json.Serialization.JsonPropertyName("name")] string Name, - [property: System.Text.Json.Serialization.JsonPropertyName("latency_ms")] double LatencyMilliseconds); + [property: System.Text.Json.Serialization.JsonPropertyName("latency_ms")] + double LatencyMilliseconds + ); private sealed record TouchResponse( [property: System.Text.Json.Serialization.JsonPropertyName("name")] string Name, - [property: System.Text.Json.Serialization.JsonPropertyName("activity_seq")] ulong ActivitySequence); + [property: System.Text.Json.Serialization.JsonPropertyName("activity_seq")] + ulong ActivitySequence + ); private sealed record ErrorResponse( [property: System.Text.Json.Serialization.JsonPropertyName("kind")] string Kind, - [property: System.Text.Json.Serialization.JsonPropertyName("message")] string Message); + [property: System.Text.Json.Serialization.JsonPropertyName("message")] string Message + ); private sealed record FsReadResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("data")] string Data); + [property: System.Text.Json.Serialization.JsonPropertyName("data")] string Data + ); private sealed record ExistsResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("exists")] bool Exists); + [property: System.Text.Json.Serialization.JsonPropertyName("exists")] bool Exists + ); private sealed record FsReadStreamResponse( [property: System.Text.Json.Serialization.JsonPropertyName("done")] bool Done, - [property: System.Text.Json.Serialization.JsonPropertyName("chunk_b64")] string? ChunkBase64); + [property: System.Text.Json.Serialization.JsonPropertyName("chunk_b64")] string? ChunkBase64 + ); private sealed record DoneResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("done")] bool Done); + [property: System.Text.Json.Serialization.JsonPropertyName("done")] bool Done + ); private sealed record LogEntryWire( [property: System.Text.Json.Serialization.JsonPropertyName("source")] LogSource Source, [property: System.Text.Json.Serialization.JsonPropertyName("session_id")] ulong? SessionId, - [property: System.Text.Json.Serialization.JsonPropertyName("timestamp_ms")] long TimestampMs, + [property: System.Text.Json.Serialization.JsonPropertyName("timestamp_ms")] + long TimestampMs, [property: System.Text.Json.Serialization.JsonPropertyName("data_b64")] string DataBase64, - [property: System.Text.Json.Serialization.JsonPropertyName("cursor")] string Cursor); + [property: System.Text.Json.Serialization.JsonPropertyName("cursor")] string Cursor + ); private sealed record AllMetricsResponse( [property: System.Text.Json.Serialization.JsonPropertyName("sandboxes")] - Dictionary Sandboxes); + Dictionary Sandboxes + ); private sealed record ReindexResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("indexed")] uint Indexed); + [property: System.Text.Json.Serialization.JsonPropertyName("indexed")] uint Indexed + ); private sealed record VersionResponse( - [property: System.Text.Json.Serialization.JsonPropertyName("version")] string Version); + [property: System.Text.Json.Serialization.JsonPropertyName("version")] string Version + ); private delegate nint NativeCall(nint buffer, nuint length); private delegate nint CancellableNativeCall(ulong cancelId, nint buffer, nuint length); @@ -1820,7 +2562,13 @@ private sealed record VersionResponse( private delegate void CancelUnregisterFn(ulong cancelId); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint SandboxCreateFn(ulong cancelId, nint name, nint optionsJson, nint buffer, nuint length); + private delegate nint SandboxCreateFn( + ulong cancelId, + nint name, + nint optionsJson, + nint buffer, + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint SandboxLookupFn(ulong cancelId, nint name, nint buffer, nuint length); @@ -1834,7 +2582,8 @@ private delegate nint SandboxStartFn( nint name, [MarshalAs(UnmanagedType.I1)] bool detached, nint buffer, - nuint length); + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint SandboxByNameFn(ulong cancelId, nint name, nint buffer, nuint length); @@ -1845,13 +2594,21 @@ private delegate nint SandboxByNameTimeoutFn( nint name, ulong timeoutMilliseconds, nint buffer, - nuint length); + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint SandboxListFn(ulong cancelId, nint filterJson, nint buffer, nuint length); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint SandboxExecFn(ulong cancelId, ulong handle, nint command, nint optionsJson, nint buffer, nuint length); + private delegate nint SandboxExecFn( + ulong cancelId, + ulong handle, + nint command, + nint optionsJson, + nint buffer, + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint ExecHandleFn(ulong cancelId, ulong execHandle, nint buffer, nuint length); @@ -1860,7 +2617,13 @@ private delegate nint SandboxByNameTimeoutFn( private delegate nint ExecIdFn(ulong execHandle, nint buffer, nuint length); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint ExecSignalFn(ulong cancelId, ulong execHandle, int signal, nint buffer, nuint length); + private delegate nint ExecSignalFn( + ulong cancelId, + ulong execHandle, + int signal, + nint buffer, + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint ExecResizeFn( @@ -1869,7 +2632,8 @@ private delegate nint ExecResizeFn( ushort rows, ushort columns, nint buffer, - nuint length); + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint ExecStdinWriteFn( @@ -1877,10 +2641,17 @@ private delegate nint ExecStdinWriteFn( ulong execHandle, nint dataBase64, nint buffer, - nuint length); + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint SandboxStopFn(ulong cancelId, ulong handle, ulong timeoutMilliseconds, nint buffer, nuint length); + private delegate nint SandboxStopFn( + ulong cancelId, + ulong handle, + ulong timeoutMilliseconds, + nint buffer, + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint SandboxHandleFn(ulong cancelId, ulong handle, nint buffer, nuint length); @@ -1892,7 +2663,13 @@ private delegate nint ExecStdinWriteFn( private delegate nint SandboxCloseFn(ulong cancelId, ulong handle, nint buffer, nuint length); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint SandboxHandleStringFn(ulong cancelId, ulong handle, nint value, nint buffer, nuint length); + private delegate nint SandboxHandleStringFn( + ulong cancelId, + ulong handle, + nint value, + nint buffer, + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint SandboxHandleTwoStringsFn( @@ -1901,22 +2678,46 @@ private delegate nint SandboxHandleTwoStringsFn( nint first, nint second, nint buffer, - nuint length); + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint SandboxHandleOptionsFn(ulong cancelId, ulong handle, nint optionsJson, nint buffer, nuint length); + private delegate nint SandboxHandleOptionsFn( + ulong cancelId, + ulong handle, + nint optionsJson, + nint buffer, + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint SandboxByNameOptionsFn(ulong cancelId, nint name, nint optionsJson, nint buffer, nuint length); + private delegate nint SandboxByNameOptionsFn( + ulong cancelId, + nint name, + nint optionsJson, + nint buffer, + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint StreamHandleFn(ulong cancelId, ulong streamHandle, nint buffer, nuint length); + private delegate nint StreamHandleFn( + ulong cancelId, + ulong streamHandle, + nint buffer, + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint StreamCloseFn(ulong streamHandle, nint buffer, nuint length); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint StreamWriteFn(ulong cancelId, ulong streamHandle, nint dataBase64, nint buffer, nuint length); + private delegate nint StreamWriteFn( + ulong cancelId, + ulong streamHandle, + nint dataBase64, + nint buffer, + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint MetricsStreamStartFn( @@ -1924,7 +2725,8 @@ private delegate nint MetricsStreamStartFn( ulong sandboxHandle, ulong intervalMilliseconds, nint buffer, - nuint length); + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint CancellableNoArgFn(ulong cancelId, nint buffer, nuint length); @@ -1933,10 +2735,23 @@ private delegate nint MetricsStreamStartFn( private delegate nint StringFn(ulong cancelId, nint value, nint buffer, nuint length); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint TwoStringsFn(ulong cancelId, nint first, nint second, nint buffer, nuint length); + private delegate nint TwoStringsFn( + ulong cancelId, + nint first, + nint second, + nint buffer, + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint ThreeStringsFn(ulong cancelId, nint first, nint second, nint third, nint buffer, nuint length); + private delegate nint ThreeStringsFn( + ulong cancelId, + nint first, + nint second, + nint third, + nint buffer, + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint StringBoolFn( @@ -1944,7 +2759,8 @@ private delegate nint StringBoolFn( nint value, [MarshalAs(UnmanagedType.I1)] bool flag, nint buffer, - nuint length); + nuint length + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint VersionFn(nint buffer, nuint length); @@ -1953,7 +2769,12 @@ private delegate nint StringBoolFn( private delegate nint AgentSocketPathFn(nint name, nint buffer, nuint length); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint AgentOpenFn(ulong cancelId, nint value, ulong timeoutMilliseconds, out ulong handle); + private delegate nint AgentOpenFn( + ulong cancelId, + nint value, + ulong timeoutMilliseconds, + out ulong handle + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint AgentRequestFn( @@ -1965,7 +2786,8 @@ private delegate nint AgentRequestFn( out uint id, out byte outputFlags, out nint outputBody, - out nuint outputBodyLength); + out nuint outputBodyLength + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint AgentStreamOpenFn( @@ -1975,7 +2797,8 @@ private delegate nint AgentStreamOpenFn( nint body, nuint bodyLength, out uint id, - out ulong streamHandle); + out ulong streamHandle + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint AgentStreamNextFn( @@ -1986,7 +2809,8 @@ private delegate nint AgentStreamNextFn( out uint id, out byte flags, out nint outputBody, - out nuint outputBodyLength); + out nuint outputBodyLength + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint AgentStreamCloseFn(ulong cancelId, ulong agentHandle, ulong streamHandle); @@ -1998,10 +2822,15 @@ private delegate nint AgentSendFn( uint id, byte flags, nint body, - nuint bodyLength); + nuint bodyLength + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private delegate nint AgentReadyBytesFn(ulong agentHandle, out nint outputBody, out nuint outputBodyLength); + private delegate nint AgentReadyBytesFn( + ulong agentHandle, + out nint outputBody, + out nuint outputBodyLength + ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint AgentCloseFn(ulong cancelId, ulong agentHandle); diff --git a/src/Microsandbox/RetryableCompletionState.cs b/src/Microsandbox/RetryableCompletionState.cs index 8efdd19..93a3cc4 100644 --- a/src/Microsandbox/RetryableCompletionState.cs +++ b/src/Microsandbox/RetryableCompletionState.cs @@ -9,13 +9,13 @@ internal sealed class RetryableCompletionState internal void EnsureOpen(string owner) { - if (!IsOpen) - { - throw new ObjectDisposedException(owner); - } + ObjectDisposedException.ThrowIf(!IsOpen, owner); } - internal async Task CompleteAsync(Func completeAsync, CancellationToken cancellationToken) + internal async Task CompleteAsync( + Func completeAsync, + CancellationToken cancellationToken + ) { await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); try diff --git a/src/Microsandbox/Sandbox.cs b/src/Microsandbox/Sandbox.cs index 10a4b06..c21452d 100644 --- a/src/Microsandbox/Sandbox.cs +++ b/src/Microsandbox/Sandbox.cs @@ -32,39 +32,52 @@ internal Sandbox(NativeApi native, string name, ulong handle) public Task ExecuteAsync( string command, ExecOptions? options = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentException.ThrowIfNullOrWhiteSpace(command); - return _native.ExecAsync(GetHandle(), command, (options ?? new ExecOptions()).ToJson(), cancellationToken); + return _native.ExecAsync( + GetHandle(), + command, + (options ?? new ExecOptions()).ToJson(), + cancellationToken + ); } /// Starts a command and returns a live streaming exec handle. public async Task ExecuteStreamingAsync( string command, ExecOptions? options = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentException.ThrowIfNullOrWhiteSpace(command); options ??= new ExecOptions(); - var handle = await _native.ExecStreamAsync(GetHandle(), command, options.ToJson(), cancellationToken).ConfigureAwait(false); + var handle = await _native + .ExecStreamAsync(GetHandle(), command, options.ToJson(), cancellationToken) + .ConfigureAwait(false); return new ExecHandle(_native, handle, options.StdinPipe); } /// Reads persisted sandbox logs into memory. public Task> LogsAsync( LogOptions? options = null, - CancellationToken cancellationToken = default) => - _native.LogsAsync(GetHandle(), (options ?? new LogOptions()).ToJson(), cancellationToken); + CancellationToken cancellationToken = default + ) => _native.LogsAsync(GetHandle(), (options ?? new LogOptions()).ToJson(), cancellationToken); /// Starts a persisted log stream, optionally following new entries. public async Task LogStreamAsync( LogStreamOptions? options = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var handle = await _native.LogStreamAsync( - GetHandle(), - (options ?? new LogStreamOptions()).ToJson(), - cancellationToken).ConfigureAwait(false); + var handle = await _native + .LogStreamAsync( + GetHandle(), + (options ?? new LogStreamOptions()).ToJson(), + cancellationToken + ) + .ConfigureAwait(false); return new LogStream(_native, handle); } @@ -75,32 +88,42 @@ public Task MetricsAsync(CancellationToken cancellationToken = d /// Starts a metrics stream at the requested polling interval. public async Task MetricsStreamAsync( TimeSpan interval, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { if (interval < TimeSpan.Zero) { throw new ArgumentOutOfRangeException(nameof(interval), "Interval cannot be negative."); } - var milliseconds = interval > TimeSpan.Zero - ? checked((ulong)Math.Ceiling(interval.TotalMilliseconds)) - : 0; - var handle = await _native.MetricsStreamAsync(GetHandle(), milliseconds, cancellationToken).ConfigureAwait(false); + var milliseconds = + interval > TimeSpan.Zero ? checked((ulong)Math.Ceiling(interval.TotalMilliseconds)) : 0; + var handle = await _native + .MetricsStreamAsync(GetHandle(), milliseconds, cancellationToken) + .ConfigureAwait(false); return new MetricsStream(_native, handle); } /// Runs a shell command through /bin/sh -c. - public Task ShellAsync(string command, CancellationToken cancellationToken = default) + public Task ShellAsync( + string command, + CancellationToken cancellationToken = default + ) { ArgumentException.ThrowIfNullOrWhiteSpace(command); - return ExecuteAsync("/bin/sh", new ExecOptions { Arguments = ["-c", command] }, cancellationToken); + return ExecuteAsync( + "/bin/sh", + new ExecOptions { Arguments = ["-c", command] }, + cancellationToken + ); } /// Starts a command through /bin/sh -c and returns a live streaming exec handle. public Task ShellStreamingAsync( string command, ExecOptions? options = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentException.ThrowIfNullOrWhiteSpace(command); options = (options ?? new ExecOptions()) with { Arguments = ["-c", command] }; @@ -146,8 +169,9 @@ public Task RequestDrainAsync(CancellationToken cancellationToken = default) => _native.WaitAsync(GetHandle(), cancellationToken); /// Waits until persisted state reports a terminal sandbox status. - public Task WaitUntilStoppedAsync(CancellationToken cancellationToken = default) => - _native.WaitUntilStoppedAsync(GetHandle(), cancellationToken); + public Task WaitUntilStoppedAsync( + CancellationToken cancellationToken = default + ) => _native.WaitUntilStoppedAsync(GetHandle(), cancellationToken); /// Checks agent reachability without refreshing idle activity. public Task PingAsync(CancellationToken cancellationToken = default) => @@ -161,10 +185,14 @@ public Task TouchAsync(CancellationToken cancellationToken = public Task AttachAsync( string command, IReadOnlyList? arguments = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentException.ThrowIfNullOrWhiteSpace(command); - var options = JsonSerializer.Serialize(new { args = arguments ?? [] }, JsonDefaults.Options); + var options = JsonSerializer.Serialize( + new { args = arguments ?? [] }, + JsonDefaults.Options + ); return _native.AttachAsync(GetHandle(), command, options, cancellationToken); } @@ -175,17 +203,22 @@ public Task AttachShellAsync(CancellationToken cancellationToken = default) /// Opens a low-level raw agent client for this sandbox. public async Task ConnectAgentAsync(CancellationToken cancellationToken = default) { - var handle = await _native.OpenAgentSandboxAsync(Name, cancellationToken).ConfigureAwait(false); + var handle = await _native + .OpenAgentSandboxAsync(Name, cancellationToken) + .ConfigureAwait(false); return new AgentClient(_native, handle); } /// Plans or applies a modification through this live handle. public async Task ModifyAsync( SandboxModificationOptions options, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentNullException.ThrowIfNull(options); - var json = await _native.ModifyAsync(GetHandle(), options.ToJson(), cancellationToken).ConfigureAwait(false); + var json = await _native + .ModifyAsync(GetHandle(), options.ToJson(), cancellationToken) + .ConfigureAwait(false); return SandboxModificationPlan.Parse(json); } diff --git a/src/Microsandbox/SandboxHandle.cs b/src/Microsandbox/SandboxHandle.cs index 0ddeb26..57985dc 100644 --- a/src/Microsandbox/SandboxHandle.cs +++ b/src/Microsandbox/SandboxHandle.cs @@ -15,8 +15,10 @@ internal SandboxHandle(NativeApi native, SandboxMetadata metadata) /// Gets the latest metadata captured for this handle. public SandboxMetadata Metadata { get; } + /// Gets the sandbox name. public string Name => Metadata.Name; + /// Gets the last-known lifecycle status. public SandboxStatus Status => Metadata.Status; @@ -37,16 +39,20 @@ public Task StartDetachedAsync(CancellationToken cancellationToken = de _native.StartAsync(Name, true, cancellationToken); /// Gracefully stops the sandbox by name. - public Task StopAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default) => - _native.StopByNameAsync(Name, StopTimeoutMilliseconds(timeout), cancellationToken); + public Task StopAsync( + TimeSpan? timeout = null, + CancellationToken cancellationToken = default + ) => _native.StopByNameAsync(Name, StopTimeoutMilliseconds(timeout), cancellationToken); /// Requests graceful shutdown by name and returns after the request is sent. public Task RequestStopAsync(CancellationToken cancellationToken = default) => _native.RequestStopByNameAsync(Name, cancellationToken); /// Force-kills the sandbox by name. - public Task KillAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default) => - _native.KillByNameAsync(Name, KillTimeoutMilliseconds(timeout), cancellationToken); + public Task KillAsync( + TimeSpan? timeout = null, + CancellationToken cancellationToken = default + ) => _native.KillByNameAsync(Name, KillTimeoutMilliseconds(timeout), cancellationToken); /// Requests immediate termination by name and returns after the request is sent. public Task RequestKillAsync(CancellationToken cancellationToken = default) => @@ -57,8 +63,9 @@ public Task RequestDrainAsync(CancellationToken cancellationToken = default) => _native.RequestDrainByNameAsync(Name, cancellationToken); /// Waits until the sandbox reaches a terminal state. - public Task WaitUntilStoppedAsync(CancellationToken cancellationToken = default) => - _native.WaitUntilStoppedByNameAsync(Name, cancellationToken); + public Task WaitUntilStoppedAsync( + CancellationToken cancellationToken = default + ) => _native.WaitUntilStoppedByNameAsync(Name, cancellationToken); /// Checks agent reachability without refreshing idle activity. public Task PingAsync(CancellationToken cancellationToken = default) => @@ -71,28 +78,35 @@ public Task TouchAsync(CancellationToken cancellationToken = /// Plans or applies a modification by persisted sandbox name. public async Task ModifyAsync( SandboxModificationOptions options, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentNullException.ThrowIfNull(options); - var json = await _native.ModifyByNameAsync(Name, options.ToJson(), cancellationToken).ConfigureAwait(false); + var json = await _native + .ModifyByNameAsync(Name, options.ToJson(), cancellationToken) + .ConfigureAwait(false); return SandboxModificationPlan.Parse(json); } /// Reads persisted sandbox logs into memory without requiring a live handle. public Task> LogsAsync( LogOptions? options = null, - CancellationToken cancellationToken = default) => - _native.LogsByNameAsync(Name, (options ?? new LogOptions()).ToJson(), cancellationToken); + CancellationToken cancellationToken = default + ) => _native.LogsByNameAsync(Name, (options ?? new LogOptions()).ToJson(), cancellationToken); /// Starts a persisted log stream without requiring a live handle. public async Task LogStreamAsync( LogStreamOptions? options = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var handle = await _native.LogStreamByNameAsync( - Name, - (options ?? new LogStreamOptions()).ToJson(), - cancellationToken).ConfigureAwait(false); + var handle = await _native + .LogStreamByNameAsync( + Name, + (options ?? new LogStreamOptions()).ToJson(), + cancellationToken + ) + .ConfigureAwait(false); return new LogStream(_native, handle); } @@ -103,7 +117,8 @@ public Task MetricsAsync(CancellationToken cancellationToken = d /// Creates a named snapshot without opening a live sandbox handle. public Task SnapshotAsync( string snapshotName, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentException.ThrowIfNullOrWhiteSpace(snapshotName); return _native.SnapshotByNameAsync(Name, snapshotName, cancellationToken); @@ -137,4 +152,5 @@ public sealed record SandboxMetadata( SandboxStatus Status, string ConfigJson, DateTimeOffset? CreatedAt, - DateTimeOffset? UpdatedAt); + DateTimeOffset? UpdatedAt +); diff --git a/src/Microsandbox/SandboxLifecycle.cs b/src/Microsandbox/SandboxLifecycle.cs index 84fcbc2..0f775df 100644 --- a/src/Microsandbox/SandboxLifecycle.cs +++ b/src/Microsandbox/SandboxLifecycle.cs @@ -8,16 +8,22 @@ public enum SandboxStatus { /// The sandbox record has been created. Created, + /// The sandbox is starting. Starting, + /// The sandbox is running. Running, + /// The sandbox is draining. Draining, + /// The sandbox is paused. Paused, + /// The sandbox stopped normally. Stopped, + /// The sandbox process crashed. Crashed, } @@ -28,7 +34,8 @@ public sealed record SandboxFilter /// Gets labels that every returned sandbox must match. public IReadOnlyDictionary? Labels { get; init; } - internal string ToJson() => JsonSerializer.Serialize(new FilterPayload { Labels = Labels }, JsonDefaults.Options); + internal string ToJson() => + JsonSerializer.Serialize(new FilterPayload { Labels = Labels }, JsonDefaults.Options); private sealed record FilterPayload { @@ -44,7 +51,8 @@ public sealed record SandboxStopResult( int? ExitCode, int? Signal, DateTimeOffset ObservedAt, - string? Source); + string? Source +); /// Describes a successful agent reachability check. public sealed record SandboxPingResult(string Name, TimeSpan Latency); @@ -58,9 +66,11 @@ public sealed record SandboxInitOptions /// Gets the init command. [JsonPropertyName("cmd")] public required string Command { get; init; } + /// Gets init command arguments. [JsonPropertyName("args")] public IReadOnlyList? Arguments { get; init; } + /// Gets init environment entries as key/value pairs. [JsonPropertyName("env")] public IReadOnlyList>? Environment { get; init; } diff --git a/src/Microsandbox/SandboxModification.cs b/src/Microsandbox/SandboxModification.cs index 577d539..cf51652 100644 --- a/src/Microsandbox/SandboxModification.cs +++ b/src/Microsandbox/SandboxModification.cs @@ -8,8 +8,10 @@ public enum ModificationPolicy { /// Applies only changes that can complete without restarting. NoRestart, + /// Persists changes for the next start without changing a running VM. NextStart, + /// Restarts the sandbox when restart-required changes are present. Restart, } @@ -32,12 +34,15 @@ public sealed record SandboxModificationOptions internal string ToJson() { Patch.Validate(); - return JsonSerializer.Serialize(new ModificationRequest - { - Patch = Patch.ToWire(), - Policy = Policy, - DryRun = DryRun, - }, JsonDefaults.Options); + return JsonSerializer.Serialize( + new ModificationRequest + { + Patch = Patch.ToWire(), + Policy = Policy, + DryRun = DryRun, + }, + JsonDefaults.Options + ); } private sealed record ModificationRequest @@ -92,46 +97,68 @@ public sealed record SandboxModificationPatch /// Gets secret names to remove. public IReadOnlyList? SecretsRemove { get; init; } - internal object ToWire() => new PatchWire - { - CPUs = CPUs, - MaxCPUs = MaxCPUs, - MemoryMiB = MemoryMiB, - MaxMemoryMiB = MaxMemoryMiB, - RootDiskSizeMiB = RootDiskSizeMiB, - Environment = Environment?.OrderBy(item => item.Key, StringComparer.Ordinal) - .Select(item => new EnvironmentWire(item.Key, item.Value)).ToArray(), - EnvironmentRemove = EnvironmentRemove, - Labels = Labels?.OrderBy(item => item.Key, StringComparer.Ordinal) - .Select(item => new[] { item.Key, item.Value }).ToArray(), - LabelsRemove = LabelsRemove, - Workdir = Workdir, - Secrets = Secrets?.OrderBy(item => item.Key, StringComparer.Ordinal) - .Select(item => item.Value.ToWire(item.Key)).ToArray(), - SecretsRemove = SecretsRemove, - }; + internal object ToWire() => + new PatchWire + { + CPUs = CPUs, + MaxCPUs = MaxCPUs, + MemoryMiB = MemoryMiB, + MaxMemoryMiB = MaxMemoryMiB, + RootDiskSizeMiB = RootDiskSizeMiB, + Environment = Environment + ?.OrderBy(item => item.Key, StringComparer.Ordinal) + .Select(item => new EnvironmentWire(item.Key, item.Value)) + .ToArray(), + EnvironmentRemove = EnvironmentRemove, + Labels = Labels + ?.OrderBy(item => item.Key, StringComparer.Ordinal) + .Select(item => new[] { item.Key, item.Value }) + .ToArray(), + LabelsRemove = LabelsRemove, + Workdir = Workdir, + Secrets = Secrets + ?.OrderBy(item => item.Key, StringComparer.Ordinal) + .Select(item => item.Value.ToWire(item.Key)) + .ToArray(), + SecretsRemove = SecretsRemove, + }; internal void Validate() { if (CPUs == 0) { - throw new ArgumentOutOfRangeException(nameof(CPUs), "CPU count must be greater than zero."); + throw new ArgumentOutOfRangeException( + nameof(CPUs), + "CPU count must be greater than zero." + ); } if (MaxCPUs == 0) { - throw new ArgumentOutOfRangeException(nameof(MaxCPUs), "Maximum CPU count must be greater than zero."); + throw new ArgumentOutOfRangeException( + nameof(MaxCPUs), + "Maximum CPU count must be greater than zero." + ); } if (MemoryMiB == 0) { - throw new ArgumentOutOfRangeException(nameof(MemoryMiB), "Memory must be greater than zero."); + throw new ArgumentOutOfRangeException( + nameof(MemoryMiB), + "Memory must be greater than zero." + ); } if (MaxMemoryMiB == 0) { - throw new ArgumentOutOfRangeException(nameof(MaxMemoryMiB), "Maximum memory must be greater than zero."); + throw new ArgumentOutOfRangeException( + nameof(MaxMemoryMiB), + "Maximum memory must be greater than zero." + ); } if (RootDiskSizeMiB == 0) { - throw new ArgumentOutOfRangeException(nameof(RootDiskSizeMiB), "Root disk size must be greater than zero."); + throw new ArgumentOutOfRangeException( + nameof(RootDiskSizeMiB), + "Root disk size must be greater than zero." + ); } if (Secrets is not null) @@ -148,33 +175,45 @@ private sealed record PatchWire { [JsonPropertyName("cpus")] public byte? CPUs { get; init; } + [JsonPropertyName("max_cpus")] public byte? MaxCPUs { get; init; } + [JsonPropertyName("memory_mib")] public uint? MemoryMiB { get; init; } + [JsonPropertyName("max_memory_mib")] public uint? MaxMemoryMiB { get; init; } + [JsonPropertyName("root_disk_size_mib")] public uint? RootDiskSizeMiB { get; init; } + [JsonPropertyName("env")] public IReadOnlyList? Environment { get; init; } + [JsonPropertyName("env_remove")] public IReadOnlyList? EnvironmentRemove { get; init; } + [JsonPropertyName("labels")] public IReadOnlyList>? Labels { get; init; } + [JsonPropertyName("labels_remove")] public IReadOnlyList? LabelsRemove { get; init; } + [JsonPropertyName("workdir")] public string? Workdir { get; init; } + [JsonPropertyName("secrets")] public IReadOnlyList? Secrets { get; init; } + [JsonPropertyName("secrets_remove")] public IReadOnlyList? SecretsRemove { get; init; } } private sealed record EnvironmentWire( [property: JsonPropertyName("key")] string Key, - [property: JsonPropertyName("value")] string Value); + [property: JsonPropertyName("value")] string Value + ); } /// Describes the desired state of one modified secret. @@ -195,29 +234,33 @@ public sealed record SandboxSecretModification /// Gets desired allowed host patterns. public IReadOnlyList? AllowedHosts { get; init; } - internal object ToWire(string name) => new SecretWire - { - Name = name, - Source = !string.IsNullOrEmpty(EnvironmentVariable) - ? new SourceWire { Kind = "env", Variable = EnvironmentVariable } - : !string.IsNullOrEmpty(StoreReference) - ? new SourceWire { Kind = "store", Reference = StoreReference } + internal object ToWire(string name) => + new SecretWire + { + Name = name, + Source = + !string.IsNullOrEmpty(EnvironmentVariable) + ? new SourceWire { Kind = "env", Variable = EnvironmentVariable } + : !string.IsNullOrEmpty(StoreReference) + ? new SourceWire { Kind = "store", Reference = StoreReference } : null, - Value = string.IsNullOrEmpty(Value) ? null : Value, - Placeholder = string.IsNullOrEmpty(Placeholder) ? null : Placeholder, - AllowedHosts = AllowedHosts, - }; + Value = string.IsNullOrEmpty(Value) ? null : Value, + Placeholder = string.IsNullOrEmpty(Placeholder) ? null : Placeholder, + AllowedHosts = AllowedHosts, + }; internal void Validate(string name) { - var sources = (string.IsNullOrEmpty(EnvironmentVariable) ? 0 : 1) + var sources = + (string.IsNullOrEmpty(EnvironmentVariable) ? 0 : 1) + (string.IsNullOrEmpty(Value) ? 0 : 1) + (string.IsNullOrEmpty(StoreReference) ? 0 : 1); if (sources > 1) { throw new ArgumentException( $"Secret '{name}' environment variable, value, and store reference are mutually exclusive.", - nameof(name)); + nameof(name) + ); } } @@ -225,12 +268,16 @@ private sealed record SecretWire { [JsonPropertyName("name")] public required string Name { get; init; } + [JsonPropertyName("source")] public SourceWire? Source { get; init; } + [JsonPropertyName("value")] public string? Value { get; init; } + [JsonPropertyName("placeholder")] public string? Placeholder { get; init; } + [JsonPropertyName("allowed_hosts")] public IReadOnlyList? AllowedHosts { get; init; } } @@ -239,8 +286,10 @@ private sealed record SourceWire { [JsonPropertyName("kind")] public required string Kind { get; init; } + [JsonPropertyName("var")] public string? Variable { get; init; } + [JsonPropertyName("reference")] public string? Reference { get; init; } } @@ -283,7 +332,9 @@ public sealed record SandboxModificationPlan internal static SandboxModificationPlan Parse(string json) => JsonSerializer.Deserialize(json, JsonDefaults.Options) - ?? throw new InvalidDataException("The native ABI returned an empty sandbox modification plan."); + ?? throw new InvalidDataException( + "The native ABI returned an empty sandbox modification plan." + ); } /// Contains one planned config or secret change. @@ -292,33 +343,43 @@ public sealed record SandboxPlannedChange /// Gets config or secret. [JsonPropertyName("kind")] public required string Kind { get; init; } + /// Gets the modified field. [JsonPropertyName("field")] public required string Field { get; init; } + /// Gets the secret name for secret changes. [JsonPropertyName("name")] public string? Name { get; init; } + /// Gets the natural change classification. [JsonPropertyName("change")] public required string Change { get; init; } + /// Gets the previous visible config state. [JsonPropertyName("before")] public string? Before { get; init; } + /// Gets the desired visible config state. [JsonPropertyName("after")] public string? After { get; init; } + /// Gets the previous guest-visible secret reference. [JsonPropertyName("before_ref")] public string? BeforeReference { get; init; } + /// Gets the desired guest-visible secret reference. [JsonPropertyName("after_ref")] public string? AfterReference { get; init; } + /// Gets when or whether the change can take effect. [JsonPropertyName("disposition")] public required string Disposition { get; init; } + /// Gets allowed hosts after a secret change. [JsonPropertyName("allow_hosts")] public IReadOnlyList AllowedHosts { get; init; } = []; + /// Gets a human-readable classification reason. [JsonPropertyName("reason")] public string? Reason { get; init; } @@ -327,7 +388,8 @@ public sealed record SandboxPlannedChange /// Contains a field-associated modification conflict or warning. public sealed record SandboxModificationMessage( [property: JsonPropertyName("field")] string Field, - [property: JsonPropertyName("message")] string Message); + [property: JsonPropertyName("message")] string Message +); /// Reports convergence for one live resource resize. public sealed record SandboxResourceResizeStatus( @@ -335,4 +397,5 @@ public sealed record SandboxResourceResizeStatus( [property: JsonPropertyName("requested")] string Requested, [property: JsonPropertyName("actual")] string Actual, [property: JsonPropertyName("enforced")] string Enforced, - [property: JsonPropertyName("state")] string State); + [property: JsonPropertyName("state")] string State +); diff --git a/src/Microsandbox/SandboxOptions.cs b/src/Microsandbox/SandboxOptions.cs index 89dcbd3..48dedb8 100644 --- a/src/Microsandbox/SandboxOptions.cs +++ b/src/Microsandbox/SandboxOptions.cs @@ -121,45 +121,48 @@ internal string ToJson() ValidateDuration(MaxDuration, nameof(MaxDuration)); ValidateDuration(IdleTimeout, nameof(IdleTimeout)); - return JsonSerializer.Serialize(new CreatePayload - { - Image = Image, - ImageFileSystem = ImageFileSystem, - ImageBind = ImageBind, - RootDisk = RootDisk, - Snapshot = Snapshot, - MemoryMiB = MemoryMiB, - CPUs = CPUs, - MaxMemoryMiB = MaxMemoryMiB, - MaxCPUs = MaxCPUs, - Workdir = Workdir, - Shell = Shell, - SecurityProfile = SecurityProfile, - Hostname = Hostname, - User = User, - Replace = Replace, - ReplaceTimeoutMilliseconds = ToMilliseconds(ReplaceTimeout), - Detached = Detached, - Ephemeral = Ephemeral, - MaxDurationSeconds = ToSeconds(MaxDuration), - IdleTimeoutSeconds = ToSeconds(IdleTimeout), - Entrypoint = Entrypoint, - Init = Init, - PullPolicy = PullPolicy, - LogLevel = LogLevel, - QuietLogs = QuietLogs, - Scripts = Scripts, - Environment = Environment, - Labels = Labels, - RegistryAuth = RegistryAuth, - Ports = Ports, - UdpPorts = UdpPorts, - PortBindings = PortBindings, - Network = Network, - Secrets = Secrets, - Patches = Patches, - VolumeMounts = VolumeMounts, - }, JsonDefaults.Options); + return JsonSerializer.Serialize( + new CreatePayload + { + Image = Image, + ImageFileSystem = ImageFileSystem, + ImageBind = ImageBind, + RootDisk = RootDisk, + Snapshot = Snapshot, + MemoryMiB = MemoryMiB, + CPUs = CPUs, + MaxMemoryMiB = MaxMemoryMiB, + MaxCPUs = MaxCPUs, + Workdir = Workdir, + Shell = Shell, + SecurityProfile = SecurityProfile, + Hostname = Hostname, + User = User, + Replace = Replace, + ReplaceTimeoutMilliseconds = ToMilliseconds(ReplaceTimeout), + Detached = Detached, + Ephemeral = Ephemeral, + MaxDurationSeconds = ToSeconds(MaxDuration), + IdleTimeoutSeconds = ToSeconds(IdleTimeout), + Entrypoint = Entrypoint, + Init = Init, + PullPolicy = PullPolicy, + LogLevel = LogLevel, + QuietLogs = QuietLogs, + Scripts = Scripts, + Environment = Environment, + Labels = Labels, + RegistryAuth = RegistryAuth, + Ports = Ports, + UdpPorts = UdpPorts, + PortBindings = PortBindings, + Network = Network, + Secrets = Secrets, + Patches = Patches, + VolumeMounts = VolumeMounts, + }, + JsonDefaults.Options + ); } private static void ValidateDuration(TimeSpan? value, string parameterName) @@ -170,13 +173,11 @@ private static void ValidateDuration(TimeSpan? value, string parameterName) } } - private static ulong? ToMilliseconds(TimeSpan? value) => value is { } duration - ? checked((ulong)Math.Ceiling(duration.TotalMilliseconds)) - : null; + private static ulong? ToMilliseconds(TimeSpan? value) => + value is { } duration ? checked((ulong)Math.Ceiling(duration.TotalMilliseconds)) : null; - private static ulong? ToSeconds(TimeSpan? value) => value is { } duration - ? checked((ulong)Math.Ceiling(duration.TotalSeconds)) - : null; + private static ulong? ToSeconds(TimeSpan? value) => + value is { } duration ? checked((ulong)Math.Ceiling(duration.TotalSeconds)) : null; private sealed record CreatePayload { @@ -296,15 +297,19 @@ public sealed record SandboxRootDiskOptions /// Gets managed, tmpfs, or disk-image. [JsonPropertyName("kind")] public required string Kind { get; init; } + /// Gets the managed or tmpfs size in MiB. [JsonPropertyName("size_mib")] public uint? SizeMiB { get; init; } + /// Gets the host path for a disk-image root. [JsonPropertyName("path")] public string? Path { get; init; } + /// Gets the disk image format hint. [JsonPropertyName("format")] public string? Format { get; init; } + /// Gets the inner filesystem type hint. [JsonPropertyName("fstype")] public string? FileSystem { get; init; } @@ -316,6 +321,7 @@ public sealed record SandboxRegistryAuthOptions /// Gets the registry username. [JsonPropertyName("username")] public required string Username { get; init; } + /// Gets the registry password. [JsonPropertyName("password")] public required string Password { get; init; } @@ -327,14 +333,17 @@ public sealed record SandboxPortBindingOptions /// Gets the host bind address. [JsonPropertyName("bind")] public string? BindAddress { get; init; } + /// Gets the host port. [JsonPropertyName("host_port")] [JsonIgnore(Condition = JsonIgnoreCondition.Never)] public ushort HostPort { get; init; } + /// Gets the guest port. [JsonPropertyName("guest_port")] [JsonIgnore(Condition = JsonIgnoreCondition.Never)] public ushort GuestPort { get; init; } + /// Gets tcp or udp. [JsonPropertyName("protocol")] public string? Protocol { get; init; } @@ -346,42 +355,55 @@ public sealed record SandboxNetworkOptions /// Gets a preset such as public-only or allow-all. [JsonPropertyName("policy")] public string? Policy { get; init; } + /// Gets an ordered custom policy. [JsonPropertyName("custom_policy")] public SandboxCustomNetworkPolicy? CustomPolicy { get; init; } + /// Gets DNS proxy configuration. [JsonPropertyName("dns")] public SandboxDnsOptions? Dns { get; init; } + /// Gets the legacy flat DNS rebinding switch. [JsonPropertyName("dns_rebind_protection")] public bool? DnsRebindProtection { get; init; } + /// Gets exact domains denied by DNS. [JsonPropertyName("deny_domains")] public IReadOnlyList? DenyDomains { get; init; } + /// Gets domain suffixes denied by DNS. [JsonPropertyName("deny_domain_suffixes")] public IReadOnlyList? DenyDomainSuffixes { get; init; } + /// Gets transparent TLS interception configuration. [JsonPropertyName("tls")] public SandboxTlsOptions? Tls { get; init; } + /// Gets nested TCP port mappings. [JsonPropertyName("ports")] public IReadOnlyDictionary? Ports { get; init; } + /// Gets nested explicit port bindings. [JsonPropertyName("port_bindings")] public IReadOnlyList? PortBindings { get; init; } + /// Gets the IPv4 allocation pool. [JsonPropertyName("ipv4_pool")] public string? IPv4Pool { get; init; } + /// Gets the IPv6 allocation pool. [JsonPropertyName("ipv6_pool")] public string? IPv6Pool { get; init; } + /// Gets the concurrent connection limit. [JsonPropertyName("max_connections")] public uint? MaxConnections { get; init; } + /// Gets the sandbox-wide secret-violation action. [JsonPropertyName("on_secret_violation")] public string? OnSecretViolation { get; init; } + /// Gets whether host extra CA bundles are trusted in the guest. [JsonPropertyName("trust_host_cas")] public bool? TrustHostCertificateAuthorities { get; init; } @@ -393,9 +415,11 @@ public sealed record SandboxDnsOptions /// Gets whether DNS rebinding protection is enabled. [JsonPropertyName("rebind_protection")] public bool? RebindProtection { get; init; } + /// Gets upstream resolver addresses. [JsonPropertyName("nameservers")] public IReadOnlyList? NameServers { get; init; } + /// Gets the DNS query timeout in milliseconds. [JsonPropertyName("query_timeout_ms")] public ulong? QueryTimeoutMilliseconds { get; init; } @@ -407,9 +431,11 @@ public sealed record SandboxCustomNetworkPolicy /// Gets the unmatched egress action. [JsonPropertyName("default_egress")] public string? DefaultEgress { get; init; } + /// Gets the unmatched ingress action. [JsonPropertyName("default_ingress")] public string? DefaultIngress { get; init; } + /// Gets ordered firewall rules. [JsonPropertyName("rules")] public IReadOnlyList? Rules { get; init; } @@ -421,21 +447,27 @@ public sealed record SandboxNetworkRule /// Gets allow or deny. [JsonPropertyName("action")] public required string Action { get; init; } + /// Gets egress, ingress, or any. [JsonPropertyName("direction")] public string? Direction { get; init; } + /// Gets the destination matcher. [JsonPropertyName("destination")] public string? Destination { get; init; } + /// Gets a legacy single protocol. [JsonPropertyName("protocol")] public string? Protocol { get; init; } + /// Gets multiple protocol matchers. [JsonPropertyName("protocols")] public IReadOnlyList? Protocols { get; init; } + /// Gets a single port or range. [JsonPropertyName("port")] public string? Port { get; init; } + /// Gets multiple ports or ranges. [JsonPropertyName("ports")] public IReadOnlyList? Ports { get; init; } @@ -447,27 +479,35 @@ public sealed record SandboxTlsOptions /// Gets hosts that bypass interception. [JsonPropertyName("bypass")] public IReadOnlyList? Bypass { get; init; } + /// Gets whether upstream certificates are verified. [JsonPropertyName("verify_upstream")] public bool? VerifyUpstream { get; init; } + /// Gets intercepted TCP ports. [JsonPropertyName("intercepted_ports")] public IReadOnlyList? InterceptedPorts { get; init; } + /// Gets whether QUIC is blocked on intercepted ports. [JsonPropertyName("block_quic")] public bool? BlockQuic { get; init; } + /// Gets the interception CA certificate path. [JsonPropertyName("ca_cert")] public string? CertificateAuthorityCertificate { get; init; } + /// Gets the interception CA private-key path. [JsonPropertyName("ca_key")] public string? CertificateAuthorityKey { get; init; } + /// Gets extra upstream CA bundle paths. [JsonPropertyName("upstream_ca_certs")] public IReadOnlyList? UpstreamCertificateAuthorities { get; init; } + /// Gets host-scoped upstream CA bundles. [JsonPropertyName("scoped_upstream_ca_certs")] public IReadOnlyList? ScopedUpstreamCertificateAuthorities { get; init; } + /// Gets host-scoped upstream verification overrides. [JsonPropertyName("scoped_verify_upstream")] public IReadOnlyList? ScopedVerifyUpstream { get; init; } @@ -476,13 +516,16 @@ public sealed record SandboxTlsOptions /// Associates an upstream CA bundle with a host pattern. public sealed record SandboxScopedUpstreamCertificateAuthority( [property: JsonPropertyName("pattern")] string Pattern, - [property: JsonPropertyName("path")] string Path); + [property: JsonPropertyName("path")] string Path +); /// Overrides upstream certificate verification for a host pattern. public sealed record SandboxScopedVerifyUpstream( [property: JsonPropertyName("pattern")] string Pattern, [property: JsonPropertyName("verify")] - [property: JsonIgnore(Condition = JsonIgnoreCondition.Never)] bool Verify); + [property: JsonIgnore(Condition = JsonIgnoreCondition.Never)] + bool Verify +); /// Configures one transport-substituted secret. public sealed record SandboxSecretOptions @@ -490,21 +533,27 @@ public sealed record SandboxSecretOptions /// Gets the guest environment variable containing the placeholder. [JsonPropertyName("env_var")] public required string EnvironmentVariable { get; init; } + /// Gets the host-side secret value. [JsonPropertyName("value")] public required string Value { get; init; } + /// Gets exact allowed hosts. [JsonPropertyName("allow_hosts")] public IReadOnlyList? AllowedHosts { get; init; } + /// Gets wildcard allowed-host patterns. [JsonPropertyName("allow_host_patterns")] public IReadOnlyList? AllowedHostPatterns { get; init; } + /// Gets an explicit guest-visible placeholder. [JsonPropertyName("placeholder")] public string? Placeholder { get; init; } + /// Gets whether verified TLS is required for substitution. [JsonPropertyName("require_tls")] public bool? RequireTls { get; init; } + /// Gets the secret-violation action. [JsonPropertyName("on_violation")] public string? OnViolation { get; init; } @@ -516,27 +565,35 @@ public sealed record SandboxPatchOptions /// Gets the patch discriminator. [JsonPropertyName("kind")] public required string Kind { get; init; } + /// Gets the target path for text, append, mkdir, or remove. [JsonPropertyName("path")] public string? Path { get; init; } + /// Gets text patch content. [JsonPropertyName("content")] public string? Content { get; init; } + /// Gets an optional Unix mode. [JsonPropertyName("mode")] public uint? Mode { get; init; } + /// Gets whether an existing target is replaced. [JsonPropertyName("replace")] public bool Replace { get; init; } + /// Gets a host copy source. [JsonPropertyName("src")] public string? Source { get; init; } + /// Gets a guest copy destination. [JsonPropertyName("dst")] public string? Destination { get; init; } + /// Gets a symbolic-link target. [JsonPropertyName("target")] public string? Target { get; init; } + /// Gets a symbolic-link path. [JsonPropertyName("link")] public string? Link { get; init; } @@ -548,48 +605,63 @@ public sealed record SandboxMountOptions /// Gets a host bind path. [JsonPropertyName("bind")] public string? Bind { get; init; } + /// Gets a named volume. [JsonPropertyName("named")] public string? Named { get; init; } + /// Gets named-volume creation behavior. [JsonPropertyName("named_mode")] public string? NamedMode { get; init; } + /// Gets the named-volume kind. [JsonPropertyName("named_kind")] public string? NamedKind { get; init; } + /// Gets whether this is a tmpfs mount. [JsonPropertyName("tmpfs")] public bool Tmpfs { get; init; } + /// Gets a host disk-image path. [JsonPropertyName("disk")] public string? Disk { get; init; } + /// Gets the disk image format hint. [JsonPropertyName("format")] public string? Format { get; init; } + /// Gets the inner filesystem type hint. [JsonPropertyName("fstype")] public string? FileSystem { get; init; } + /// Gets whether the mount is read-only. [JsonPropertyName("readonly")] public bool ReadOnly { get; init; } + /// Gets whether executable files are disabled. [JsonPropertyName("noexec")] public bool NoExec { get; init; } + /// Gets whether set-user-ID and set-group-ID are disabled. [JsonPropertyName("nosuid")] public bool NoSuid { get; init; } + /// Gets whether device nodes are disabled. [JsonPropertyName("nodev")] public bool NoDev { get; init; } + /// Gets the requested size in MiB. [JsonPropertyName("size_mib")] public uint? SizeMiB { get; init; } + /// Gets the guest-write quota in MiB. [JsonPropertyName("quota_mib")] public uint? QuotaMiB { get; init; } + /// Gets strict, relaxed, or off. [JsonPropertyName("stat_virtualization")] public string? StatVirtualization { get; init; } + /// Gets private or mirror. [JsonPropertyName("host_permissions")] public string? HostPermissions { get; init; } diff --git a/src/Microsandbox/Snapshots.cs b/src/Microsandbox/Snapshots.cs index 823e891..9098aa4 100644 --- a/src/Microsandbox/Snapshots.cs +++ b/src/Microsandbox/Snapshots.cs @@ -11,53 +11,72 @@ public sealed class SnapshotService public Task CreateAsync( SnapshotCreateOptions options, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentNullException.ThrowIfNull(options); ArgumentException.ThrowIfNullOrWhiteSpace(options.Name); ArgumentException.ThrowIfNullOrWhiteSpace(options.SourceSandbox); - return _native.CreateSnapshotAsync(options.SourceSandbox, options.ToJson(), cancellationToken); + return _native.CreateSnapshotAsync( + options.SourceSandbox, + options.ToJson(), + cancellationToken + ); } - public Task OpenAsync(string pathOrName, CancellationToken cancellationToken = default) => - _native.OpenSnapshotAsync(Required(pathOrName), cancellationToken); + public Task OpenAsync( + string pathOrName, + CancellationToken cancellationToken = default + ) => _native.OpenSnapshotAsync(Required(pathOrName), cancellationToken); - public Task VerifyAsync(string pathOrName, CancellationToken cancellationToken = default) => - _native.VerifySnapshotAsync(Required(pathOrName), cancellationToken); + public Task VerifyAsync( + string pathOrName, + CancellationToken cancellationToken = default + ) => _native.VerifySnapshotAsync(Required(pathOrName), cancellationToken); - public Task GetAsync(string nameOrDigest, CancellationToken cancellationToken = default) => - _native.GetSnapshotAsync(Required(nameOrDigest), cancellationToken); + public Task GetAsync( + string nameOrDigest, + CancellationToken cancellationToken = default + ) => _native.GetSnapshotAsync(Required(nameOrDigest), cancellationToken); - public Task> ListAsync(CancellationToken cancellationToken = default) => - _native.ListSnapshotsAsync(cancellationToken); + public Task> ListAsync( + CancellationToken cancellationToken = default + ) => _native.ListSnapshotsAsync(cancellationToken); public Task> ListDirectoryAsync( string directory, - CancellationToken cancellationToken = default) => - _native.ListSnapshotDirectoryAsync(Required(directory), cancellationToken); + CancellationToken cancellationToken = default + ) => _native.ListSnapshotDirectoryAsync(Required(directory), cancellationToken); - public Task RemoveAsync(string pathOrName, bool force = false, CancellationToken cancellationToken = default) => - _native.RemoveSnapshotAsync(Required(pathOrName), force, cancellationToken); + public Task RemoveAsync( + string pathOrName, + bool force = false, + CancellationToken cancellationToken = default + ) => _native.RemoveSnapshotAsync(Required(pathOrName), force, cancellationToken); - public Task ReindexAsync(string directory, CancellationToken cancellationToken = default) => - _native.ReindexSnapshotsAsync(Required(directory), cancellationToken); + public Task ReindexAsync( + string directory, + CancellationToken cancellationToken = default + ) => _native.ReindexSnapshotsAsync(Required(directory), cancellationToken); public Task ExportAsync( string nameOrPath, string outputPath, SnapshotExportOptions? options = null, - CancellationToken cancellationToken = default) => + CancellationToken cancellationToken = default + ) => _native.ExportSnapshotAsync( Required(nameOrPath), Required(outputPath), (options ?? new SnapshotExportOptions()).ToJson(), - cancellationToken); + cancellationToken + ); public Task ImportAsync( string archive, string destination, - CancellationToken cancellationToken = default) => - _native.ImportSnapshotAsync(Required(archive), Required(destination), cancellationToken); + CancellationToken cancellationToken = default + ) => _native.ImportSnapshotAsync(Required(archive), Required(destination), cancellationToken); private static string Required(string value) { @@ -76,15 +95,19 @@ public sealed class SnapshotCreateOptions public bool RecordIntegrity { get; init; } public bool Resumable { get; init; } - internal string ToJson() => JsonSerializer.Serialize(new Payload - { - Name = Name, - DestinationDirectory = DestinationDirectory, - Labels = Labels, - Force = Force, - RecordIntegrity = RecordIntegrity, - Resumable = Resumable, - }, JsonDefaults.Options); + internal string ToJson() => + JsonSerializer.Serialize( + new Payload + { + Name = Name, + DestinationDirectory = DestinationDirectory, + Labels = Labels, + Force = Force, + RecordIntegrity = RecordIntegrity, + Resumable = Resumable, + }, + JsonDefaults.Options + ); private sealed class Payload { @@ -114,12 +137,16 @@ public sealed class SnapshotExportOptions public bool WithImage { get; init; } public bool PlainTar { get; init; } - internal string ToJson() => JsonSerializer.Serialize(new Payload - { - WithParents = WithParents, - WithImage = WithImage, - PlainTar = PlainTar, - }, JsonDefaults.Options); + internal string ToJson() => + JsonSerializer.Serialize( + new Payload + { + WithParents = WithParents, + WithImage = WithImage, + PlainTar = PlainTar, + }, + JsonDefaults.Options + ); private sealed class Payload { @@ -146,7 +173,8 @@ public sealed record SnapshotArtifact( [property: JsonPropertyName("parent")] string? Parent, [property: JsonPropertyName("created_at")] string CreatedAt, [property: JsonPropertyName("labels")] IReadOnlyDictionary Labels, - [property: JsonPropertyName("source_sandbox")] string? SourceSandbox); + [property: JsonPropertyName("source_sandbox")] string? SourceSandbox +); public sealed record SnapshotInfo( [property: JsonPropertyName("digest")] string Digest, @@ -157,7 +185,8 @@ public sealed record SnapshotInfo( [property: JsonPropertyName("format")] string Format, [property: JsonPropertyName("size_bytes")] ulong? SizeBytes, [property: JsonPropertyName("created_at_unix")] long CreatedAtUnix, - [property: JsonPropertyName("path")] string Path) + [property: JsonPropertyName("path")] string Path +) { public DateTimeOffset CreatedAt => DateTimeOffset.FromUnixTimeSeconds(CreatedAtUnix); } @@ -165,9 +194,11 @@ public sealed record SnapshotInfo( public sealed record SnapshotVerifyReport( [property: JsonPropertyName("digest")] string Digest, [property: JsonPropertyName("path")] string Path, - [property: JsonPropertyName("upper")] SnapshotUpperVerifyStatus Upper); + [property: JsonPropertyName("upper")] SnapshotUpperVerifyStatus Upper +); public sealed record SnapshotUpperVerifyStatus( [property: JsonPropertyName("kind")] string Kind, [property: JsonPropertyName("algorithm")] string? Algorithm, - [property: JsonPropertyName("digest")] string? Digest); + [property: JsonPropertyName("digest")] string? Digest +); diff --git a/src/Microsandbox/Ssh.cs b/src/Microsandbox/Ssh.cs index f98330e..273f508 100644 --- a/src/Microsandbox/Ssh.cs +++ b/src/Microsandbox/Ssh.cs @@ -19,24 +19,32 @@ internal SandboxSsh(Sandbox sandbox, NativeApi native) /// Opens an SSH client connected to the sandbox. public async Task OpenClientAsync( SshClientOptions? options = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var handle = await _native.SshConnectAsync( - _sandbox.GetHandle(), - (options ?? new SshClientOptions()).ToJson(), - cancellationToken).ConfigureAwait(false); + var handle = await _native + .SshConnectAsync( + _sandbox.GetHandle(), + (options ?? new SshClientOptions()).ToJson(), + cancellationToken + ) + .ConfigureAwait(false); return new SshClient(_native, handle); } /// Prepares a reusable SSH server endpoint for the sandbox. public async Task PrepareServerAsync( SshServerOptions? options = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var handle = await _native.SshServerAsync( - _sandbox.GetHandle(), - (options ?? new SshServerOptions()).ToJson(), - cancellationToken).ConfigureAwait(false); + var handle = await _native + .SshServerAsync( + _sandbox.GetHandle(), + (options ?? new SshServerOptions()).ToJson(), + cancellationToken + ) + .ConfigureAwait(false); return new SshServer(_native, handle); } } @@ -134,29 +142,35 @@ internal SshClient(NativeApi native, ulong handle) public Task ExecuteAsync( string command, SshExecOptions? options = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentException.ThrowIfNullOrWhiteSpace(command); return _native.SshClientExecAsync( GetHandle(), command, (options ?? new SshExecOptions()).ToJson(), - cancellationToken); + cancellationToken + ); } /// Bridges the process console to an interactive SSH shell until it exits or detaches. public Task AttachConsoleAsync( SshAttachOptions? options = null, - CancellationToken cancellationToken = default) => + CancellationToken cancellationToken = default + ) => _native.SshClientAttachAsync( GetHandle(), (options ?? new SshAttachOptions()).ToJson(), - cancellationToken); + cancellationToken + ); /// Opens an SFTP session over this SSH connection. public async Task OpenSftpAsync(CancellationToken cancellationToken = default) { - var handle = await _native.SshClientSftpAsync(GetHandle(), cancellationToken).ConfigureAwait(false); + var handle = await _native + .SshClientSftpAsync(GetHandle(), cancellationToken) + .ConfigureAwait(false); return new SftpClient(_native, handle); } @@ -165,7 +179,8 @@ public Task CloseAsync(CancellationToken cancellationToken = default) => _state.CloseAsync(_native.SshClientCloseAsync, cancellationToken); /// - public async ValueTask DisposeAsync() => await CloseAsync(CancellationToken.None).ConfigureAwait(false); + public async ValueTask DisposeAsync() => + await CloseAsync(CancellationToken.None).ConfigureAwait(false); private ulong GetHandle() => _state.GetHandle(nameof(SshClient)); @@ -189,21 +204,24 @@ public Task ReadAsync(string path, CancellationToken cancellationToken = _native.SftpReadAsync(GetHandle(), Required(path), cancellationToken); /// Reads a UTF-8 file into a string. - public async Task ReadStringAsync(string path, CancellationToken cancellationToken = default) => - Encoding.UTF8.GetString(await ReadAsync(path, cancellationToken).ConfigureAwait(false)); + public async Task ReadStringAsync( + string path, + CancellationToken cancellationToken = default + ) => Encoding.UTF8.GetString(await ReadAsync(path, cancellationToken).ConfigureAwait(false)); /// Creates or truncates a file with the supplied bytes. public Task WriteAsync( string path, ReadOnlyMemory data, - CancellationToken cancellationToken = default) => - _native.SftpWriteAsync(GetHandle(), Required(path), data, cancellationToken); + CancellationToken cancellationToken = default + ) => _native.SftpWriteAsync(GetHandle(), Required(path), data, cancellationToken); /// Creates or truncates a UTF-8 file. public Task WriteStringAsync( string path, string content, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { ArgumentNullException.ThrowIfNull(content); return WriteAsync(path, Encoding.UTF8.GetBytes(content), cancellationToken); @@ -225,12 +243,20 @@ public Task RemoveDirectoryAsync(string path, CancellationToken cancellationToke public Task RenameAsync( string oldPath, string newPath, - CancellationToken cancellationToken = default) => - _native.SftpRenameAsync(GetHandle(), Required(oldPath), Required(newPath), cancellationToken); + CancellationToken cancellationToken = default + ) => + _native.SftpRenameAsync( + GetHandle(), + Required(oldPath), + Required(newPath), + cancellationToken + ); /// Resolves a path to its canonical absolute form. - public Task GetRealPathAsync(string path, CancellationToken cancellationToken = default) => - _native.SftpRealPathAsync(GetHandle(), Required(path), cancellationToken); + public Task GetRealPathAsync( + string path, + CancellationToken cancellationToken = default + ) => _native.SftpRealPathAsync(GetHandle(), Required(path), cancellationToken); /// Reads a symbolic-link target. public Task ReadLinkAsync(string path, CancellationToken cancellationToken = default) => @@ -240,15 +266,22 @@ public Task ReadLinkAsync(string path, CancellationToken cancellationTok public Task CreateSymbolicLinkAsync( string target, string linkPath, - CancellationToken cancellationToken = default) => - _native.SftpSymlinkAsync(GetHandle(), Required(target), Required(linkPath), cancellationToken); + CancellationToken cancellationToken = default + ) => + _native.SftpSymlinkAsync( + GetHandle(), + Required(target), + Required(linkPath), + cancellationToken + ); /// Closes and consumes the native SFTP handle. public Task CloseAsync(CancellationToken cancellationToken = default) => _state.CloseAsync(_native.SftpCloseAsync, cancellationToken); /// - public async ValueTask DisposeAsync() => await CloseAsync(CancellationToken.None).ConfigureAwait(false); + public async ValueTask DisposeAsync() => + await CloseAsync(CancellationToken.None).ConfigureAwait(false); private ulong GetHandle() => _state.GetHandle(nameof(SftpClient)); @@ -290,7 +323,8 @@ public Task CloseAsync(CancellationToken cancellationToken = default) => _state.CloseAsync(_native.SshServerCloseAsync, cancellationToken); /// - public async ValueTask DisposeAsync() => await CloseAsync(CancellationToken.None).ConfigureAwait(false); + public async ValueTask DisposeAsync() => + await CloseAsync(CancellationToken.None).ConfigureAwait(false); private ulong GetHandle() => _state.GetHandle(nameof(SshServer)); diff --git a/src/Microsandbox/Volumes.cs b/src/Microsandbox/Volumes.cs index 6611c98..1c61438 100644 --- a/src/Microsandbox/Volumes.cs +++ b/src/Microsandbox/Volumes.cs @@ -12,14 +12,20 @@ public sealed class VolumeService public Task CreateAsync( string name, VolumeCreateOptions? options = null, - CancellationToken cancellationToken = default) => - _native.CreateVolumeAsync(Required(name), (options ?? new VolumeCreateOptions()).ToJson(), cancellationToken); + CancellationToken cancellationToken = default + ) => + _native.CreateVolumeAsync( + Required(name), + (options ?? new VolumeCreateOptions()).ToJson(), + cancellationToken + ); public Task GetAsync(string name, CancellationToken cancellationToken = default) => _native.GetVolumeAsync(Required(name), cancellationToken); - public Task> ListAsync(CancellationToken cancellationToken = default) => - _native.ListVolumesAsync(cancellationToken); + public Task> ListAsync( + CancellationToken cancellationToken = default + ) => _native.ListVolumesAsync(cancellationToken); public Task RemoveAsync(string name, CancellationToken cancellationToken = default) => _native.RemoveVolumeAsync(Required(name), cancellationToken); @@ -44,13 +50,17 @@ public sealed class VolumeCreateOptions public uint SizeMiB { get; init; } public IReadOnlyDictionary? Labels { get; init; } - internal string ToJson() => JsonSerializer.Serialize(new Payload - { - QuotaMiB = QuotaMiB, - Kind = Kind, - SizeMiB = SizeMiB, - Labels = Labels, - }, JsonDefaults.Options); + internal string ToJson() => + JsonSerializer.Serialize( + new Payload + { + QuotaMiB = QuotaMiB, + Kind = Kind, + SizeMiB = SizeMiB, + Labels = Labels, + }, + JsonDefaults.Options + ); private sealed class Payload { @@ -78,7 +88,9 @@ public sealed record VolumeInfo( [property: JsonPropertyName("disk_format")] string? DiskFormat, [property: JsonPropertyName("disk_fstype")] string? DiskFilesystem, [property: JsonPropertyName("labels")] IReadOnlyDictionary Labels, - [property: JsonPropertyName("created_at_unix")] long? CreatedAtUnix) + [property: JsonPropertyName("created_at_unix")] long? CreatedAtUnix +) { - public DateTimeOffset? CreatedAt => CreatedAtUnix is { } value ? DateTimeOffset.FromUnixTimeSeconds(value) : null; + public DateTimeOffset? CreatedAt => + CreatedAtUnix is { } value ? DateTimeOffset.FromUnixTimeSeconds(value) : null; } diff --git a/tests/Microsandbox.Tests/Microsandbox.Tests.csproj b/tests/Microsandbox.Tests/Microsandbox.Tests.csproj index 1a49616..51be088 100644 --- a/tests/Microsandbox.Tests/Microsandbox.Tests.csproj +++ b/tests/Microsandbox.Tests/Microsandbox.Tests.csproj @@ -1,13 +1,10 @@  - - - Exe net10.0 @@ -16,5 +13,4 @@ true false - diff --git a/tests/Microsandbox.Tests/SdkTests.cs b/tests/Microsandbox.Tests/SdkTests.cs index 3c3ed75..325b0d1 100644 --- a/tests/Microsandbox.Tests/SdkTests.cs +++ b/tests/Microsandbox.Tests/SdkTests.cs @@ -55,7 +55,11 @@ public void ExtendedSandboxOptionsUseTheGoCreateContract() FileSystem = "ext4", }, SecurityProfile = "restricted", - RegistryAuth = new SandboxRegistryAuthOptions { Username = "user", Password = "secret" }, + RegistryAuth = new SandboxRegistryAuthOptions + { + Username = "user", + Password = "secret", + }, Ports = new Dictionary { [8080] = 80 }, UdpPorts = new Dictionary { [5353] = 53 }, PortBindings = @@ -80,13 +84,23 @@ public void ExtendedSandboxOptionsUseTheGoCreateContract() CustomPolicy = new SandboxCustomNetworkPolicy { DefaultEgress = "deny", - Rules = [new SandboxNetworkRule { Action = "allow", Destination = "api.example.com" }], + Rules = + [ + new SandboxNetworkRule + { + Action = "allow", + Destination = "api.example.com", + }, + ], }, Tls = new SandboxTlsOptions { VerifyUpstream = true, BlockQuic = false, - ScopedVerifyUpstream = [new SandboxScopedVerifyUpstream("internal.example.com", false)], + ScopedVerifyUpstream = + [ + new SandboxScopedVerifyUpstream("internal.example.com", false), + ], }, MaxConnections = 100, }, @@ -135,14 +149,33 @@ public void ExtendedSandboxOptionsUseTheGoCreateContract() Equal(80, root.GetProperty("ports").GetProperty("8080").GetUInt16()); Equal(53, root.GetProperty("ports_udp").GetProperty("5353").GetUInt16()); Equal("127.0.0.1", root.GetProperty("port_bindings")[0].GetProperty("bind").GetString()); - False(root.GetProperty("network").GetProperty("dns").GetProperty("rebind_protection").GetBoolean()); - False(root.GetProperty("network").GetProperty("tls").GetProperty("scoped_verify_upstream")[0] - .GetProperty("verify").GetBoolean()); - Equal("allow", root.GetProperty("network").GetProperty("custom_policy").GetProperty("rules")[0] - .GetProperty("action").GetString()); + False( + root.GetProperty("network") + .GetProperty("dns") + .GetProperty("rebind_protection") + .GetBoolean() + ); + False( + root.GetProperty("network") + .GetProperty("tls") + .GetProperty("scoped_verify_upstream")[0] + .GetProperty("verify") + .GetBoolean() + ); + Equal( + "allow", + root.GetProperty("network") + .GetProperty("custom_policy") + .GetProperty("rules")[0] + .GetProperty("action") + .GetString() + ); Equal("API_KEY", root.GetProperty("secrets")[0].GetProperty("env_var").GetString()); Equal("text", root.GetProperty("patches")[0].GetProperty("kind").GetString()); - Equal("data", root.GetProperty("volumes").GetProperty("/data").GetProperty("named").GetString()); + Equal( + "data", + root.GetProperty("volumes").GetProperty("/data").GetProperty("named").GetString() + ); } [Test] @@ -161,11 +194,9 @@ public void ExecOptionsRoundTimeoutUpToWholeSeconds() [Test] public void StreamingExecOptionsUseTheExactStdinContract() { - using var document = JsonDocument.Parse(new ExecOptions - { - StdinPipe = true, - Tty = true, - }.ToJson()); + using var document = JsonDocument.Parse( + new ExecOptions { StdinPipe = true, Tty = true }.ToJson() + ); True(document.RootElement.GetProperty("stdin_pipe").GetBoolean()); True(document.RootElement.GetProperty("tty").GetBoolean()); @@ -177,10 +208,12 @@ public void StreamingExecEventsDecodeTypedBase64Payloads() var started = NativeApi.ParseExecEvent("""{"event":"started","pid":42}"""); var stdout = NativeApi.ParseExecEvent("""{"event":"stdout","data":"AAH/"}"""); var failed = NativeApi.ParseExecEvent( - """{"event":"failed","error":{"kind":"not_found","errno":2,"errno_name":"ENOENT","message":"missing","path":"/bin/nope"}}"""); + """{"event":"failed","error":{"kind":"not_found","errno":2,"errno_name":"ENOENT","message":"missing","path":"/bin/nope"}}""" + ); var done = NativeApi.ParseExecEvent("""{"event":"done"}"""); var collected = NativeApi.ParseExecCollect( - """{"stdout_b64":"aGVsbG8=","stderr_b64":"d2FybmluZw==","exit_code":7}"""); + """{"stdout_b64":"aGVsbG8=","stderr_b64":"d2FybmluZw==","exit_code":7}""" + ); Equal(42U, ((ExecStartedEvent)started).ProcessId); True(((ExecStandardOutputEvent)stdout).Data.SequenceEqual(new byte[] { 0, 1, 255 })); @@ -195,7 +228,9 @@ public void StreamingExecEventsDecodeTypedBase64Payloads() public void SandboxNamesAreLimitedByUtf8Bytes() { MicrosandboxClient.ValidateName(new string('a', 128)); - Throws(() => MicrosandboxClient.ValidateName(new string('é', 65))); + Throws(() => + MicrosandboxClient.ValidateName(new string('é', 65)) + ); } [Test] @@ -209,9 +244,11 @@ public void ExecResultReportsSuccessFromExitCode() public void NativeLifecycleResponsesUseTheExactJsonContract() { var metadata = NativeApi.ParseMetadata( - """{"name":"demo","status":"running","config_json":"{}","created_at_unix":10,"updated_at_unix":null}"""); + """{"name":"demo","status":"running","config_json":"{}","created_at_unix":10,"updated_at_unix":null}""" + ); var stopped = NativeApi.ParseStopResult( - """{"name":"demo","status":"stopped","exit_code":0,"signal":null,"observed_at_unix":20,"source":"wait"}"""); + """{"name":"demo","status":"stopped","exit_code":0,"signal":null,"observed_at_unix":20,"source":"wait"}""" + ); var ping = NativeApi.ParsePingResult("""{"name":"demo","latency_ms":1.25}"""); var touch = NativeApi.ParseTouchResult("""{"name":"demo","activity_seq":42}"""); @@ -235,8 +272,10 @@ public void NativeVersionResponseUsesTheExactJsonContract() [Arguments("0.6.7", "0.6.7")] [Arguments("0.6.7+abcdef", "0.6.7")] [Arguments("0.6.7-rc.1+abcdef", "0.6.7-rc.1")] - public void ManagedVersionPreservesPrereleaseIdentifiers(string informationalVersion, string expected) => - Equal(expected, NativeApi.NormalizeManagedVersion(informationalVersion)); + public void ManagedVersionPreservesPrereleaseIdentifiers( + string informationalVersion, + string expected + ) => Equal(expected, NativeApi.NormalizeManagedVersion(informationalVersion)); [Test] public async Task RetryableCompletionStateRestoresOpenAfterNativeFailure() @@ -246,25 +285,29 @@ public async Task RetryableCompletionStateRestoresOpenAfterNativeFailure() try { - await state.CompleteAsync(_ => - { - calls++; - throw new MicrosandboxException("io", "close failed"); - }, CancellationToken.None); + await state.CompleteAsync( + _ => + { + calls++; + throw new MicrosandboxException("io", "close failed"); + }, + CancellationToken.None + ); throw new InvalidOperationException("Expected close failure."); } - catch (MicrosandboxException) - { - } + catch (MicrosandboxException) { } True(state.IsOpen); state.EnsureOpen("test"); - await state.CompleteAsync(token => - { - calls++; - False(token.CanBeCanceled); - return Task.CompletedTask; - }, CancellationToken.None); + await state.CompleteAsync( + token => + { + calls++; + False(token.CanBeCanceled); + return Task.CompletedTask; + }, + CancellationToken.None + ); Equal(2, calls); False(state.IsOpen); @@ -281,16 +324,17 @@ public async Task RetryableCompletionStateHonorsCancellationBeforeDispatch() try { - await state.CompleteAsync(_ => - { - calls++; - return Task.CompletedTask; - }, cancellation.Token); + await state.CompleteAsync( + _ => + { + calls++; + return Task.CompletedTask; + }, + cancellation.Token + ); throw new InvalidOperationException("Expected cancellation."); } - catch (OperationCanceledException) - { - } + catch (OperationCanceledException) { } Equal(0, calls); True(state.IsOpen); @@ -329,23 +373,27 @@ public async Task ConsumingCloseStateDoesNotRestoreOwnershipAfterFailure() try { - await state.CloseAsync((handle, _) => - { - Equal(42UL, handle); - calls++; - throw new InvalidOperationException("close failed"); - }, CancellationToken.None); + await state.CloseAsync( + (handle, _) => + { + Equal(42UL, handle); + calls++; + throw new InvalidOperationException("close failed"); + }, + CancellationToken.None + ); throw new InvalidOperationException("Expected close failure."); } - catch (InvalidOperationException exception) when (exception.Message == "close failed") - { - } + catch (InvalidOperationException exception) when (exception.Message == "close failed") { } - await state.CloseAsync((handle, _) => - { - calls++; - return Task.CompletedTask; - }, CancellationToken.None); + await state.CloseAsync( + (handle, _) => + { + calls++; + return Task.CompletedTask; + }, + CancellationToken.None + ); Equal(1, calls); False(state.IsOpen); @@ -362,16 +410,17 @@ public async Task ConsumingCloseStateHonorsCancellationBeforeDispatch() try { - await state.CloseAsync((_, _) => - { - calls++; - return Task.CompletedTask; - }, cancellation.Token); + await state.CloseAsync( + (_, _) => + { + calls++; + return Task.CompletedTask; + }, + cancellation.Token + ); throw new InvalidOperationException("Expected cancellation."); } - catch (OperationCanceledException) - { - } + catch (OperationCanceledException) { } Equal(0, calls); Equal(42UL, state.GetHandle("test")); @@ -449,19 +498,25 @@ public void StreamingNativeHandleOwnershipCanOnlyBeConsumedOnce() [Test] public void SshContractsDecodeBinaryOutputAndConsumeHandlesOnce() { - using var clientOptions = JsonDocument.Parse(new SshClientOptions - { - User = "root", - Terminal = "xterm-256color", - EnableSftp = false, - }.ToJson()); - using var serverOptions = JsonDocument.Parse(new SshServerOptions - { - HostKeyPath = "/tmp/host-key", - AuthorizedKeysPath = "/tmp/authorized_keys", - EnableSftp = true, - }.ToJson()); - var output = NativeApi.ParseSshOutput("""{"status":7,"stdout":"AAH/","stderr":"d2FybmluZw=="}"""); + using var clientOptions = JsonDocument.Parse( + new SshClientOptions + { + User = "root", + Terminal = "xterm-256color", + EnableSftp = false, + }.ToJson() + ); + using var serverOptions = JsonDocument.Parse( + new SshServerOptions + { + HostKeyPath = "/tmp/host-key", + AuthorizedKeysPath = "/tmp/authorized_keys", + EnableSftp = true, + }.ToJson() + ); + var output = NativeApi.ParseSshOutput( + """{"status":7,"stdout":"AAH/","stderr":"d2FybmluZw=="}""" + ); Equal("xterm-256color", clientOptions.RootElement.GetProperty("term").GetString()); False(clientOptions.RootElement.GetProperty("sftp").GetBoolean()); @@ -486,7 +541,11 @@ public void SshContractsDecodeBinaryOutputAndConsumeHandlesOnce() [Test] public void RawAgentContractsPreserveBytesFlagsAndAtomicOwnership() { - var frame = new RawFrame(42, AgentFrameFlags.Terminal | AgentFrameFlags.SessionStart, [0, 1, 255]); + var frame = new RawFrame( + 42, + AgentFrameFlags.Terminal | AgentFrameFlags.SessionStart, + [0, 1, 255] + ); Equal(42U, frame.Id); Equal((byte)3, frame.Flags); True(frame.Body.SequenceEqual(new byte[] { 0, 1, 255 })); @@ -537,25 +596,31 @@ public void SandboxModificationUsesTheCanonicalPatchAndPlanContracts() Equal("A", patch.GetProperty("env")[0].GetProperty("key").GetString()); Equal("env", patch.GetProperty("labels")[0][0].GetString()); Equal("API_KEY", patch.GetProperty("secrets")[0].GetProperty("name").GetString()); - Equal("env", patch.GetProperty("secrets")[0].GetProperty("source").GetProperty("kind").GetString()); + Equal( + "env", + patch.GetProperty("secrets")[0].GetProperty("source").GetProperty("kind").GetString() + ); var plan = SandboxModificationPlan.Parse( - """{"sandbox":"demo","status":"running","applied":false,"policy":"no_restart","changes":[{"kind":"config","field":"cpus","change":"updated","before":"1","after":"2","disposition":"live"}],"conflicts":[],"warnings":[],"resize_status":[{"resource":"cpus","requested":"2","actual":"2","enforced":"2","state":"applied"}]}"""); + """{"sandbox":"demo","status":"running","applied":false,"policy":"no_restart","changes":[{"kind":"config","field":"cpus","change":"updated","before":"1","after":"2","disposition":"live"}],"conflicts":[],"warnings":[],"resize_status":[{"resource":"cpus","requested":"2","actual":"2","enforced":"2","state":"applied"}]}""" + ); Equal(ModificationPolicy.NoRestart, plan.Policy); Equal("config", plan.Changes[0].Kind); Equal("2", plan.Changes[0].After); Equal("cpus", plan.ResizeStatus[0].Resource); - Throws(() => new SandboxModificationOptions - { - Patch = new SandboxModificationPatch + Throws(() => + new SandboxModificationOptions { - Secrets = new Dictionary + Patch = new SandboxModificationPatch { - ["bad"] = new() { EnvironmentVariable = "ENV", Value = "secret" }, + Secrets = new Dictionary + { + ["bad"] = new() { EnvironmentVariable = "ENV", Value = "secret" }, + }, }, - }, - }.ToJson()); + }.ToJson() + ); } [Test] @@ -574,7 +639,8 @@ public void LogOptionsAndEntriesUseTheExactJsonContract() Equal("stdout", document.RootElement.GetProperty("sources")[0].GetString()); var entries = NativeApi.ParseLogEntries( - """[{"source":"stderr","session_id":null,"timestamp_ms":1500,"data_b64":"aGVsbG8=","cursor":"c1"}]"""); + """[{"source":"stderr","session_id":null,"timestamp_ms":1500,"data_b64":"aGVsbG8=","cursor":"c1"}]""" + ); Equal(LogSource.Stderr, entries[0].Source); Equal(null, entries[0].SessionId); Equal("hello", entries[0].Text); @@ -599,7 +665,8 @@ public void LogStreamOptionsAndCursorEntriesUseTheExactJsonContract() True(document.RootElement.GetProperty("follow").GetBoolean()); var entry = NativeApi.ParseLogEntry( - """{"source":"output","session_id":7,"timestamp_ms":2500,"data_b64":"AAE=","cursor":"cursor-2"}"""); + """{"source":"output","session_id":7,"timestamp_ms":2500,"data_b64":"AAE=","cursor":"cursor-2"}""" + ); Equal("cursor-2", entry?.Cursor); True(entry!.Data.SequenceEqual(new byte[] { 0, 1 })); Equal(null, NativeApi.ParseLogEntry("""{"done":true}""")); @@ -618,9 +685,11 @@ public void FilesystemStreamingTypesAreStreamCompatible() public void FilesystemDtosParseNativeKindsAndNullableTimestamp() { var entries = NativeApi.ParseFilesystemEntries( - """[{"path":"/tmp/a","kind":"dir","size":0,"mode":493}]"""); + """[{"path":"/tmp/a","kind":"dir","size":0,"mode":493}]""" + ); var stat = NativeApi.ParseFilesystemStat( - """{"kind":"file","size":4,"mode":420,"readonly":true,"modified_unix":null}"""); + """{"kind":"file","size":4,"mode":420,"readonly":true,"modified_unix":null}""" + ); Equal(FilesystemEntryKind.Dir, entries[0].Kind); Equal(493U, entries[0].Mode); @@ -633,7 +702,8 @@ public void FilesystemDtosParseNativeKindsAndNullableTimestamp() public void MetricsPreserveEveryNullableNativeField() { var metrics = NativeApi.ParseMetrics( - """{"cpu_percent":1.5,"vcpu_time_ns":2,"memory_bytes":3,"memory_available_bytes":null,"memory_host_resident_bytes":4,"memory_limit_bytes":5,"disk_read_bytes":6,"disk_write_bytes":7,"net_rx_bytes":8,"net_tx_bytes":9,"upper_used_bytes":null,"upper_free_bytes":10,"upper_host_allocated_bytes":null,"uptime_secs":11}"""); + """{"cpu_percent":1.5,"vcpu_time_ns":2,"memory_bytes":3,"memory_available_bytes":null,"memory_host_resident_bytes":4,"memory_limit_bytes":5,"disk_read_bytes":6,"disk_write_bytes":7,"net_rx_bytes":8,"net_tx_bytes":9,"upper_used_bytes":null,"upper_free_bytes":10,"upper_host_allocated_bytes":null,"uptime_secs":11}""" + ); Equal(1.5, metrics.CpuPercent); Equal(null, metrics.MemoryAvailableBytes); @@ -646,13 +716,17 @@ public void MetricsPreserveEveryNullableNativeField() public void ImageVolumeAndSnapshotDtosParseNativeJson() { var image = NativeApi.ParseImageDetail( - """{"reference":"alpine:latest","manifest_digest":"sha256:a","architecture":"arm64","os":"linux","layer_count":1,"size_bytes":null,"created_at_unix":10,"last_used_at_unix":null,"config":{"digest":"sha256:c","env":[],"cmd":["sh"],"entrypoint":[],"working_dir":"/","user":"root","labels":{},"stop_signal":""},"layers":[{"diff_id":"sha256:d","blob_digest":"sha256:b","media_type":"x","compressed_size_bytes":null,"erofs_size_bytes":20,"position":0}]}"""); + """{"reference":"alpine:latest","manifest_digest":"sha256:a","architecture":"arm64","os":"linux","layer_count":1,"size_bytes":null,"created_at_unix":10,"last_used_at_unix":null,"config":{"digest":"sha256:c","env":[],"cmd":["sh"],"entrypoint":[],"working_dir":"/","user":"root","labels":{},"stop_signal":""},"layers":[{"diff_id":"sha256:d","blob_digest":"sha256:b","media_type":"x","compressed_size_bytes":null,"erofs_size_bytes":20,"position":0}]}""" + ); var volume = NativeApi.ParseVolumeInfo( - """{"name":"data","path":"/vol/data","kind":"disk","quota_mib":null,"used_bytes":12,"capacity_bytes":1024,"disk_format":"raw","disk_fstype":"ext4","labels":{},"created_at_unix":null}"""); + """{"name":"data","path":"/vol/data","kind":"disk","quota_mib":null,"used_bytes":12,"capacity_bytes":1024,"disk_format":"raw","disk_fstype":"ext4","labels":{},"created_at_unix":null}""" + ); var artifact = NativeApi.ParseSnapshotArtifact( - """{"path":"/snap/a","digest":"sha256:s","size_bytes":9,"image_ref":"alpine","image_manifest_digest":"sha256:a","scope":"disk","format":"raw","fstype":"ext4","parent":null,"created_at":"2026-01-01T00:00:00Z","labels":{},"source_sandbox":null}"""); + """{"path":"/snap/a","digest":"sha256:s","size_bytes":9,"image_ref":"alpine","image_manifest_digest":"sha256:a","scope":"disk","format":"raw","fstype":"ext4","parent":null,"created_at":"2026-01-01T00:00:00Z","labels":{},"source_sandbox":null}""" + ); var handle = NativeApi.ParseSnapshotInfo( - """{"digest":"sha256:s","name":null,"parent_digest":null,"image_ref":"alpine","scope":"disk","format":"raw","size_bytes":null,"created_at_unix":20,"path":"/snap/a"}"""); + """{"digest":"sha256:s","name":null,"parent_digest":null,"image_ref":"alpine","scope":"disk","format":"raw","size_bytes":null,"created_at_unix":20,"path":"/snap/a"}""" + ); Equal("linux", image.OperatingSystem); Equal(null, image.SizeBytes); @@ -668,24 +742,28 @@ public void ImageVolumeAndSnapshotDtosParseNativeJson() [Test] public void VolumeAndSnapshotOptionsOmitDefaultsAndUseNativeNames() { - using var volume = JsonDocument.Parse(new VolumeCreateOptions - { - Kind = VolumeKind.Dir, - QuotaMiB = 100, - Labels = new Dictionary { ["env"] = "test" }, - }.ToJson()); + using var volume = JsonDocument.Parse( + new VolumeCreateOptions + { + Kind = VolumeKind.Dir, + QuotaMiB = 100, + Labels = new Dictionary { ["env"] = "test" }, + }.ToJson() + ); Equal("dir", volume.RootElement.GetProperty("kind").GetString()); Equal(100U, volume.RootElement.GetProperty("quota_mib").GetUInt32()); False(volume.RootElement.TryGetProperty("size_mib", out _)); - using var snapshot = JsonDocument.Parse(new SnapshotCreateOptions - { - Name = "snap", - SourceSandbox = "box", - DestinationDirectory = "/tmp", - RecordIntegrity = true, - Resumable = true, - }.ToJson()); + using var snapshot = JsonDocument.Parse( + new SnapshotCreateOptions + { + Name = "snap", + SourceSandbox = "box", + DestinationDirectory = "/tmp", + RecordIntegrity = true, + Resumable = true, + }.ToJson() + ); Equal("snap", snapshot.RootElement.GetProperty("name").GetString()); Equal("/tmp", snapshot.RootElement.GetProperty("dest_dir").GetString()); True(snapshot.RootElement.GetProperty("record_integrity").GetBoolean()); @@ -708,8 +786,12 @@ public void NativeAbiSymbolsAndVersionCanBeReadWhenLibraryIsProvided() var native = NativeApi.Load(libraryPath); Throws(() => native.AgentReadyBytes(0)); - Throws(() => native.AgentRequestAsync(0, 0, Array.Empty(), CancellationToken.None) - .GetAwaiter().GetResult()); + Throws(() => + native + .AgentRequestAsync(0, 0, Array.Empty(), CancellationToken.None) + .GetAwaiter() + .GetResult() + ); } private static void Equal(T expected, T actual) @@ -730,7 +812,8 @@ private static void True(bool value) private static void False(bool value) => True(!value); - private static void Throws(Action action) where TException : Exception + private static void Throws(Action action) + where TException : Exception { try {