Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .config/dotnet-tools.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"csharpier": {
"version": "1.3.0",
"commands": [
"csharpier"
],
"rollForward": false
}
}
}
6 changes: 6 additions & 0 deletions .config/wt.toml
Original file line number Diff line number Diff line change
@@ -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"
77 changes: 77 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -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
9 changes: 9 additions & 0 deletions .githooks/pre-commit
Original file line number Diff line number Diff line change
@@ -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
16 changes: 10 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
14 changes: 14 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -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
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 10 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project>
<PropertyGroup>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-recommended</AnalysisLevel>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<DebugType>portable</DebugType>
<ContinuousIntegrationBuild Condition="'$(CI)' == 'true'">true</ContinuousIntegrationBuild>
</PropertyGroup>
</Project>
12 changes: 6 additions & 6 deletions Microsandbox.slnx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/Microsandbox/Microsandbox.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/Microsandbox.Tests/Microsandbox.Tests.csproj" />
</Folder>
<Folder Name="/src/">
<Project Path="src/Microsandbox/Microsandbox.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/Microsandbox.Tests/Microsandbox.Tests.csproj" />
</Folder>
</Solution>
101 changes: 101 additions & 0 deletions docs/agents/dotnet-style-guide.md
Original file line number Diff line number Diff line change
@@ -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.
46 changes: 31 additions & 15 deletions examples/basic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> { ["GREETING"] = "hello-from-dotnet" },
}, cancellationToken);
sandbox = await client.CreateAsync(
name,
new SandboxOptions
{
Image = "alpine:3.20",
MemoryMiB = 256,
CPUs = 1,
Environment = new Dictionary<string, string> { ["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);
Expand All @@ -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
Expand Down
Loading