Ensemble.Client
2.8.0
dotnet add package Ensemble.Client --version 2.8.0
NuGet\Install-Package Ensemble.Client -Version 2.8.0
<PackageReference Include="Ensemble.Client" Version="2.8.0" />
<PackageVersion Include="Ensemble.Client" Version="2.8.0" />
<PackageReference Include="Ensemble.Client" />
paket add Ensemble.Client --version 2.8.0
#r "nuget: Ensemble.Client, 2.8.0"
#:package Ensemble.Client@2.8.0
#addin nuget:?package=Ensemble.Client&version=2.8.0
#tool nuget:?package=Ensemble.Client&version=2.8.0
Ensemble.Client
.NET 8 client for the Ensemble
peer-to-peer messaging daemon. Sibling to the Python SDK at
clients/python. Wraps the daemon's gRPC API with idiomatic
async C#: typed records, IAsyncDisposable lifetimes, CancellationToken
propagation, typed exceptions for structured daemon errors.
Install
dotnet add package Ensemble.Client
Targets net8.0. NuGet pulls Google.Protobuf, Grpc.Net.Client,
NSec.Cryptography, and Microsoft.Extensions.Logging.Abstractions
transitively.
Quickstart — identity
using Ensemble.Client;
await using var client = EnsembleClient.FromAdminSeedFile(
"127.0.0.1:9099",
"/run/secrets/ensemble-admin.seed");
var identity = await client.GetIdentityAsync();
Console.WriteLine($"address: {identity.Address}");
EnsembleClient picks plaintext HTTP/2 (http://) for loopback /
unix-socket endpoints and TLS (https://) otherwise. Override by passing
a fully-qualified URI (http://..., https://..., or unix:///path).
Every TCP endpoint, including loopback, is expected to use an admin-keyed
daemon. FromAdminSeedFile accepts either a 32-byte raw Ed25519 seed or 64
hexadecimal characters and signs every RPC with request-bound metadata. On
Unix the seed file must have no group/other permission bits (normally 0600).
For an in-memory secret, use the seed-bearing constructor:
byte[] seed = LoadSecretFromYourStore();
await using var client = new EnsembleClient("127.0.0.1:9099", seed);
The legacy constructor remains intentionally keyless for a 0600 Unix socket,
where filesystem ownership is the authority boundary:
await using var local = new EnsembleClient("unix:///run/ensemble/ensemble.sock");
EnsembleClient.FromEnv() follows the same deployment precedence as the
Python SDK. If ENSEMBLE_SERVICE_TOKEN is present, it opens
ENSEMBLE_SOCKET in supervised-service mode and does not load an admin seed.
Otherwise, if ENSEMBLE_AUTH_SEED names a seed file, it signs every call; with
neither credential it remains the keyless owner-authorized Unix-socket path.
Never put raw seed material in the environment variable—the value is a path.
Quickstart — operator chat (node identity)
Two distinct identities can send a message, and picking the wrong one is the difference between an accepted dial and a rejected one:
- Operator / node identity —
EnsembleClient.ConnectAsync(addr),SendMessageAsync(addr, text),SubscribeAsync(). These dial and sign as the daemon's node master key — the operator's address. Use this when the peer gates on the operator (e.g. an allowlist admitting the operator). - Service identity —
RegisteredService.ConnectPeerAsync/SendChatAsyncon a handle fromRegisterServiceAsync. These dial as the registered service's own ephemeral identity (ConnectAs). The peer's gate sees the service address, not the operator.
using Ensemble.Client;
await using var client = EnsembleClient.FromAdminSeedFile(
"me.example:443",
"/run/secrets/ensemble-admin.seed");
var result = await client.ConnectAsync("Ejeff...");
if (!result.Accepted)
{
Console.Error.WriteLine($"dial refused: {result.Message}");
return;
}
await client.SendMessageAsync("Ejeff...", "hello from the operator");
// The reply returns to the node identity — surface it via the node-level
// event stream. Payloads are JSON (the daemon json-marshals chat.Message).
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
await foreach (var ev in client.SubscribeAsync(cts.Token))
{
if (ev.Type == "chat_message")
{
Console.WriteLine(ev.Payload); // {"From":"E…","Text":"…","Direction":"incoming",…}
break;
}
}
SubscribeAsync is the node-level stream — distinct from a service's
onEvent callback. Each DaemonEvent carries Type plus a JSON Payload.
Quickstart — register a service
using Ensemble.Client;
await using var client = EnsembleClient.FromAdminSeedFile(
"127.0.0.1:9099",
"/run/secrets/ensemble-admin.seed");
var manifest = ServiceManifest.NewBuilder("my-bot")
.Description("a friendly bot")
.Acl(ServiceAcl.Contacts)
.Transport(ServiceTransport.Chat)
.Build();
await using var svc = await client.RegisterServiceAsync(
manifest,
onEvent: async ev =>
{
if (ev is ServiceEvent.ChatMessage cm)
Console.WriteLine($"[{cm.FromAddr}] {cm.Text}");
else if (ev is ServiceEvent.ConnectionRequest cr)
await svc.AcceptConnectionAsync(cr.RequestId);
},
onError: err =>
{
// Daemon-side structured errors. err.AsException() returns a typed
// exception for known codes (payload_too_large, rate_limited) and
// null for unstructured stream errors.
Console.Error.WriteLine($"service error: {err.Message} (code={err.Code})");
return ValueTask.CompletedTask;
});
Console.WriteLine($"my service address: {svc.ServiceAddress}");
Console.WriteLine($"reachable at: {svc.Onion}");
await Task.Delay(TimeSpan.FromMinutes(5));
Registration lifetime
RegisteredService is a logical registration, not a single gRPC call. If the
daemon restarts or replaces its Unix socket, the handle reopens
RegisterService, presents the same manifest and credential, verifies that the
service identity is unchanged, and resumes ordered event delivery. Retry uses
capped exponential backoff; authentication, authorization, manifest and
persistent name-conflict failures are terminal rather than hot-looped.
The cancellation token passed to RegisterServiceAsync governs only the
initial handshake. Dispose the returned handle to stop it. External supervisors
should also observe svc.Completion: it stays pending through transient daemon
outages and faults if re-registration becomes permanently impossible, allowing
the process to exit non-zero instead of remaining apparently healthy but absent
from the network.
Calls made while an outage is already known wait for the replacement stream.
The SDK never replays a write that had already started because the old daemon
may have received it. Correlated operations such as SignDocumentAsync fail
with ServiceDisconnectedException if their particular stream disappears; the
caller decides whether that operation is safe to retry.
Quickstart — RPC transport + introductions
For services that host strangers (matchmaking, marketplaces, group chat
rooms), register under SERVICE_TRANSPORT_RPC to exchange raw protobuf
bytes instead of chat envelopes, and use IntroducePeersAsync to wire
two peers together with a daemon-attested provenance stamp:
var manifest = ServiceManifest.NewBuilder("pong-matchmaker")
.Acl(ServiceAcl.Public)
.Transport(ServiceTransport.Rpc)
.MaxPayloadBytes(256 * 1024)
.RateLimit(requestsPerMinute: 600, burst: 60)
.Build();
await using var svc = await client.RegisterServiceAsync(manifest, onEvent, onError);
// Pair two peers and introduce them.
await svc.IntroducePeersAsync(
toAddr: playerA,
otherAddr: playerB,
sessionId: Guid.NewGuid().ToString(),
expiresAtMs: DateTimeOffset.UtcNow.AddMinutes(2).ToUnixTimeMilliseconds(),
roleHint: "host",
payload: sessionTicket);
Both peers receive a ServiceEvent.PeerIntroduction carrying
FromServiceAddr (daemon-attested — receivers trust the local daemon's
word for provenance, no client-side verification needed),
the other peer's E-address, the session id, and the optional payload.
Typed exceptions
Daemon-side errors with a stable code map to typed exceptions you can
catch (or pattern-match on) without string-matching message:
err => {
if (err.AsException() is PayloadTooLargeException pe)
Console.Error.WriteLine($"too big — service cap is {pe.LimitBytes} bytes");
else if (err.AsException() is RateLimitedException rl)
Console.Error.WriteLine($"throttled — retry after {rl.RetryAfter}");
else
Console.Error.WriteLine($"service error: {err.Message}");
return ValueTask.CompletedTask;
}
Unknown future codes surface as a plain ServiceProtocolException with
the code preserved so callers can branch on it without code changes here.
Stream lifecycle
RegisteredService : IAsyncDisposable. Dispose to deregister:
DisposeAsynchalf-closes the bidi request stream → the daemon sees a clean EOF → the service is dropped from the registry.- A reader task runs for the lifetime of the registration. Mid-flight
transport errors (daemon restart, network blip) synthesise an
unstructured
ServiceError(Code="") toonErrorso the host process doesn't crash on a connectivity loss. - The dispose path waits up to 5 seconds for the reader to drain, then aborts. The bidi stream is always closed exactly once.
EnsembleClient : IAsyncDisposable owns one GrpcChannel. One client
can host many registered services and many independent Subscribe
streams; dispose the client to release the channel.
Repo-side notes (for contributors)
Source: clients/dotnet/ in the
Ensemble repo. The proto at
api/proto/ensemble.proto is included directly via <Protobuf Include=...>
in the csproj — no vendoring; codegen runs every build.
Layout
clients/dotnet/
├── Ensemble.Client.sln
├── global.json pins .NET 8 SDK
├── Ensemble.Client/
│ ├── EnsembleClient.cs basic RPCs (identity, contacts, peer dial)
│ ├── EnsembleClient.Services.cs partial — RegisterServiceAsync
│ ├── RegisteredService.cs bidi-stream handle (IAsyncDisposable)
│ ├── ServiceManifest.cs fluent ManifestBuilder + immutable manifest
│ ├── ServiceTypes.cs enums, ServiceError, ServiceEvent variants
│ ├── Records.cs Identity, Status, Contact, ConnectResult, DaemonEvent
│ └── Errors.cs exception hierarchy
└── tests/Ensemble.Client.Tests/
├── DaemonFixture.cs shared headless daemon per test class
├── IsolatedDaemon.cs one-off daemon for kill scenarios
├── ManifestBuilderTests.cs pure-CLR validation tests
├── BasicRpcTests.cs (SmokeTests.cs) — identity/contacts/subscribe
├── ServiceRegistrationTests.cs chat-transport bidi + lifecycle
├── Phase4PrimitiveTests.cs RPC bytes / introductions / typed errors
└── DaemonLifecycleTests.cs daemon-killed onError pathway
Prerequisites
- .NET 8 SDK —
global.jsonpins this. Newer SDKs side-by-side are fine. - Go 1.22 — needed to build the
ensembledaemon binary integration tests spawn. - Tor binary — system
/usr/bin/tor(Fedora:dnf install tor) or set$ENSEMBLE_TOR_PATHto an alternative. The daemon's auto-download path is currently 404ing on dist.torproject.org; tests bypass it by passing--tor-pathexplicitly.
Build & test
make dotnet-build # restore + build the sln
make dotnet-test # pure-CLR unit tests (no daemon)
make dotnet-test-integration # builds bin/ensemble (build-dev) then runs
# the integration suite against a real daemon
Integration tests spawn ensemble --headless --data-dir <tmp> --api-addr 127.0.0.1:<ephemeral> --admin-key <ephemeral-public-key> --tor-path <found>
per test session. EnsembleDaemonHarness.CreateClient() returns a client
authenticated by the matching private seed without exposing that seed to the
test. The suite waits for Tor bootstrap (~10s on a healthy network) before
exercising RegisterService.
Generated code
Grpc.Tools writes protobuf and gRPC client stubs into
Ensemble.Client/obj/Debug/net8.0/ under the proto's default namespace
(Ensemble.Api). Consumers don't normally need to touch this — the
public SDK surface re-exports the relevant shapes as typed records.
Versioning
Ensemble.Client versions independently from the daemon. Semver. Releases
are cut from tags namespaced client-dotnet/v* so daemon and sibling-SDK
tags don't collide.
connection lifetimes
Connecting a registered service retains a session claim until that registration
ends. Repeated connects with the same owner label and target are idempotent;
independent windows or rooms should use distinct labels. Release the same label
when its consumer finishes (release_peer in Python, ReleasePeerAsync in .NET).
Releasing one claim preserves other consumers and streams already in flight.
disconnect_peer / DisconnectPeerAsync remains the deliberate administrative
kick and may interrupt shared transport paths; use release for ordinary cleanup.
The daemon emits OperatorPresence with an attachment count and monotonically
increasing generation for the current registration. Launched backends can use it
to retain a remote connection while at least one frontend is attached, and release
when the last closes. Outstanding operations may retain their own bounded claim.
These lifecycle actions require a daemon with connection-ownership support;
older daemons do not implement release or emit attachment counts.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- Google.Protobuf (>= 3.27.3)
- Grpc.Net.Client (>= 2.65.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.2)
- NSec.Cryptography (>= 25.4.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 2.8.0 | 169 | 9/9/2026 |
| 2.7.0 | 127 | 9/1/2026 |
| 2.6.1 | 140 | 8/30/2026 |
| 2.6.0 | 141 | 8/30/2026 |
| 2.5.0 | 232 | 6/16/2026 |
| 2.4.0 | 163 | 6/16/2026 |
| 2.3.0 | 150 | 6/16/2026 |
| 2.1.0 | 143 | 6/12/2026 |
| 2.0.1 | 149 | 6/11/2026 |
| 2.0.0 | 135 | 6/11/2026 |
| 1.0.0 | 149 | 6/6/2026 |
| 0.5.0 | 148 | 6/3/2026 |
| 0.4.0 | 143 | 6/2/2026 |
| 0.3.0 | 150 | 6/1/2026 |
| 0.2.1 | 145 | 5/29/2026 |
| 0.2.0 | 138 | 5/27/2026 |
| 0.1.1 | 132 | 5/21/2026 |