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