etherbird
Keep the client. Replace the connection.
etherbird keeps async clients usable through connection failures. Define how to create, connect, and set up a resource once; the library replaces failed resources, restores their configuration and session, and waits for setup to finish before running application calls. Your application keeps using the same client.
It works with network connections, device handles, and other resources that need more than reconnection to become usable again. Your adapter supplies the protocol logic, such as authentication, subscriptions, or a device handshake.
Useful features
- A stable, typed client:
managed_client!generates ordinary async methods around your resource, keeping acquisition and recovery out of application calls. - Restored configuration: named values and setters apply to existing resources and every replacement; stored values remain readable during an outage.
- Recovery while idle: an optional disconnect watcher detects connection loss even when no operation is running. Old failure reports cannot retire a replacement.
- Bounded recovery: configurable lifecycle deadlines and capped exponential connection backoff prevent callers from managing their own reconnect loops.
- Adapter-controlled failure policies: suspend lifecycle attempts that need corrected configuration, or return a healthy operation error without reconnecting.
- Checked configuration: validate lifecycle backoff and pool bounds before starting work, with field-specific errors from fallible constructors.
- Single-attempt call timeouts: bound readiness, queueing and operation duration without opting into replay. Shutdown takes precedence over timeout expiry.
- Bounded FIFO admission: use
BoundedFifoQueuewith a queue factory to reject excess waiting calls without writing a custom queue. - Adapter cancellation helper (0.4.2):
RetireOnDropclears an incomplete exchange's resource slot and signals connection loss. The adapter explicitly confirms valid replies, including healthy device rejections. - Explicit operation retries: calls run once by default. Safe-to-repeat calls can opt into an attempt limit, overall deadline, and error predicate.
- Observable state and orderly shutdown: connection indicators, state notifications, lifecycle callbacks, and tracing help you monitor resources. Awaited shutdown completes teardown even if another shutdown caller is cancelled.
- Optional pooling: cap resource counts, grow on demand, retire idle resources, and reserve exclusive leases. Schedule operations with FIFO, priority, or a custom queue that can reject excess work. Pooled shutdown cancels and drains tracked work.
Start with direct supervision for a client that supports concurrent calls. Enable pooling when resources need exclusive access, capacity limits, or queued scheduling.
= "0.4.2"
# With pooling:
# etherbird = { version = "0.4.2", features = ["pool"] }
The API is experimental. See the managed client guide for construction and ownership, and the feature guide for lifecycle, cancellation, shutdown, and recovery guarantees.
Read the lifecycle policy guide for failure, timeout, validation and shutdown contracts, and the changelog for release history and migration notes.
Performance
In the local MQTT admission benchmarks, direct supervision performs in roughly the same range as equivalent manual coordination. Pooling adds measurable cost for tiny, high-frequency operations, especially under saturated multithreaded workloads; it also provides exclusive access, scheduling, and tracked operation shutdown. Results depend on workload and runtime.
Read the MQTT performance analysis and pool admission and allocation analysis for methodology, measurements, and raw data. MQTT timings measure local publish admission, not broker acknowledgement or message delivery.
Concrete examples
| Example | What it shows |
|---|---|
| MQTT application comparison | The same telemetry, status, and request code with manual coordination, direct supervision, or pooling. Restores subscriptions and checks readiness, cancellation, and repeated broker outages. |
| Modbus and WebSocket recovery · scenario guide | Bounded device connections, queued register reads, opt-in retries, and restored WebSocket subscriptions after socket failures. |
| Serial instrument · adapter guide | Reopens a serial port, reapplies device gain, and repeats the handshake before admitting calls. |
| Typed client and lifecycle | A small, self-contained introduction to lifecycle hooks, generated methods, direct and pooled clients, and configuration replay. |
| Priority and overload | Urgent work overtakes telemetry, equal priorities retain FIFO order, and a bounded custom queue rejects excess requests. |
| Direct MQTT session | Uses Supervisor directly with a stable receiver, subscription acknowledgements, and restart recovery. |
Run the application examples from a checkout:
# MQTT comparison with local fixtures; no broker required:
# Modbus and WebSocket fixtures; no external service required:
# Serial demo with Unix pseudo-terminals; no hardware required:
MQTT examples also support --broker-demo for real Mosquitto outages through
Docker. See the examples index for all commands and platform
requirements, and the MQTT comparison analysis for the
coordination code each approach requires.
Generic usage
These snippets run inside an async function on a Tokio runtime. They assume a
Hooks adapter implementing Lifecycle, whose resource exposes
async fn read(&self) -> Result<u16, std::io::Error>. Implement create, connect,
and disconnect; use setup for authentication, subscriptions, or a handshake.
Optional hooks add cleanup, destruction, disconnect watching, live connection
status, and error classification. The typed client example
contains a complete adapter.
1. Supervise one resource
execute waits for a ready resource and runs the operation once. By default, an
operation error requests recovery and returns the error to its caller. An adapter
can classify a healthy error with OperationFailurePolicy::Retain.
use ;
let supervisor = new;
let result = supervisor.execute.await;
supervisor.stop.await;
let sample = result?;
2. Give the application ordinary client methods
Declare forwarding signatures once. The underlying resource must support concurrent calls for this direct client.
use ;
managed_client!
let client = new;
let result = client.read.await;
client.managed.stop.await;
let sample = result?;
3. Add bounded, exclusive access
With the pool feature, the same Client declaration can use up to four resources.
Each generated method reserves one resource for its operation.
use ;
let pool = new;
let client = from_pool;
let result = client.read.await;
client.managed.stop.await;
let sample = result?;
4. Combine recovery, configuration, scheduling, and retries
This builds on the same Client and Hooks. The resource additionally provides
short synchronous set_gain(u16) and gain() -> u16 methods. Its adapter's setup
restores the session and watch_disconnect reports idle connection loss.
use ;
use ;
let pool = new;
// Install configuration and callbacks before lazy startup.
pool.set_value;
pool.set_on_resource_created;
let changes = pool.subscribe; // A watch receiver for state/membership changes.
let client = from_pool;
assert_eq!;
let result = async .await;
// Cancel and drain managed work, then tear down every resource, even on error.
client.managed.stop.await;
let readings = result?;
Use a custom queue when you also need overload rejection
or a different scheduling policy; the built-in queues are unbounded. State watchers
can await changes.changed() and inspect pool.state(). Configure a tracing
subscriber to collect lifecycle diagnostics.
Retry only operations that are safe to repeat: a disconnected write may already
have taken effect remotely. Completion retains the underlying client's meaning;
protocol or application acknowledgements belong in the adapter or application.
Resources must be Send + Sync; use interior mutability where their APIs need
mutable access. Direct calls run in their callers, while pooled calls are tracked
and drained by the library during shutdown.
API reference · Engineering tasks · CI · Real broker recovery checks
Licensed under the Apache License 2.0.