Continuo
Typed service registry and lifecycle runtime for multi-service Rust applications.
Continuo resolves shared values by Rust type and drives registered components through an ordered lifecycle: boot, validation, execution, reload, drain and finalization. A component declares what it requires as a type; the registry resolves those requirements, derives the boot order from them and hands them to the component. Long-running work is owned by a runtime that starts, stops, restarts and reloads individual services while the process keeps running.
Continuo is a library, not a framework. It does not depend on an HTTP stack, a database or a configuration format, and it does not define the application's state type. The application implements one trait on its own state and retains ownership of everything else.
Layout
Composition and wiring are different concerns and live in different files.
main.rs names the services and the inputs that can fail. application.rs
holds the one type that turns those inputs into a state and hands the
composition to Runtime.
// main.rs
async
// application.rs
with_services records; nothing is registered, read or started until run.
The command line is the only input that can fail before that point, and it is
resolved where it is read. Environment and AppState are the application's
own types; the playground has a complete version of each.
Example
The same shape written out explicitly in one file: the state, a plain value, a component with one dependency and one capability, and the call that runs it.
use SocketAddr;
use Arc;
use async_trait;
use ;
use CancellationToken;
;
/// A plain value, injected without implementing any trait.
/// A component that requires `Settings` and exposes one capability.
;
async
LISTEN=127.0.0.1:9000
Registry
Registry<S> stores values resolvable by type and components participating
in the lifecycle. Each registration call states which of the two an object
joins.
| Call | Resolvable by type | Lifecycle participant |
|---|---|---|
insert(Arc<T>) |
yes | no |
register(Arc<T>) |
yes | yes, T: Component<S> |
resolve::<T>() returns the registered Arc<T> or None. Resolution does
not construct instances. Registering a second value of the same concrete type
is an error.
bind_dyn binds a trait object to an already registered concrete value;
resolve_dyn retrieves it. No second instance is created.
registry.?;
let logger = registry.;
Register<S> is a static registration function. An implementation builds its
instance from the application state and registers it, so a service requires
neither Default nor an empty constructor. Tuples compose registrations in
declaration order, eight members per tuple, nested for larger sets.
Runtime::with_services::<(A, B)>() records the composition; run, serve
and prepare apply it, together with the runtime's ServiceManager, before
anything boots. Recording cannot fail; registration errors surface where the
registry is built.
Registration order is not dependency order. A register function that
resolves another component reads a registry that may not contain it yet.
Requirements are declared in Component::Deps and arrive resolved in boot
and run.
Components
Component<S> identifies a lifecycle participant. It declares its
dependencies as Deps, a diagnostic name, an optional order, and exposes
capabilities through as_* hooks. Capabilities are independent; a component
exposes only those it implements, either on itself or on a separate object.
Dependencies
Deps is a tuple of what the component requires: Arc<T> for a value that
must be registered, Option<Arc<T>> for one that may be absent, () for
none. The registry resolves it before boot and before each run generation
and passes the result in. A registered component named in Deps boots before
the dependent. A missing dependency is one error naming the component and
the missing type, raised before its boot hook or admitted run generation.
Runnable discovery does not resolve dependencies. Process scope and activation policy are checked first; a manual or unavailable service can remain observable without resources it cannot use yet. All initial automatic generations are admitted before any task starts. Later starts and restarts bind the current DI handles before marking the generation running; fleet dispatch shares those bound handles across its slots. No registry lookup is added to the execution hot path.
A dependency is a requirement. A component that uses another service when it is present, and serves without it, does not declare it: it resolves the value at the point of use and answers accordingly. The HTTP service in the playground resolves the counter per request and returns 503 until it is registered; it declares no dependency on it.
Ordering
order places a component relative to a layer or a preparation component:
Network is a marker type that nothing registers. Such a type acts as a
target: a node with no work of its own, complete once every component
ordered before it has completed, and releasing every component ordered
after it. A component can therefore follow the network layer without
naming, or depending on, the components that make it up.
When boot publishes a plain DI value, Deps names that value but cannot infer
which component produces it. Keep an explicit after::<Producer>() barrier
so the value exists before the dependent boots; the producer does not become
the value's lifecycle owner.
boot_priority and run_priority order components that are otherwise
independent: services that use one another without requiring one another.
A priority never moves a component past a dependency or an order edge.
The registry builds one topological plan from dependencies, targets and
priorities and uses it for boot, validation and reload; finalization
traverses it in reverse. Cycles are errors. A Bootable may register
additional components during boot; the plan is rebuilt after each boot so
that newly declared dependencies are honoured before later components run.
| Capability | Hook | Phase |
|---|---|---|
Bootable<S, Deps> |
as_bootable |
finite preparation with resolved dependencies |
Component::validate |
built in | synchronous readiness check after boot |
Runnable<S, Deps> |
as_runnable |
long-running work with resolved dependencies |
Reloadable<S> |
as_reloadable |
application of a change to a live component |
Finalizable<S> |
as_finalizable |
release of named resources, reverse order |
Configurable |
as_configurable |
typed configuration; feature config |
Environmental |
as_environmental |
program environments; feature config |
Phases run in the order register, configure, boot, validate, spawn, run,
drain, finalize. Boot prepares and finalize releases; they are inverses.
Listeners, loops and timers belong exclusively to run. finalize is not a
stop hook: a runnable completes its own work inside run when its context is
cancelled.
The registry stores components as Arc<dyn AnyComponent<S>>, a type-erased
view with dependency resolution folded in. Application code implements
Component; code that inspects the registry receives AnyComponent.
Runtime
Runtime<S> owns the future of every runnable. Each start creates a numbered
generation with its own RunContext, a child of the process shutdown token.
A runnable observes the same cancellation path whether the process is draining
or the service alone was stopped.
ServiceManager is a cloneable control handle registered as an ordinary
value. It sends commands over a bounded channel to the runtime loop and holds
no state of its own.
let manager = state.registry_ref..unwrap;
let services = manager.list.await?;
manager.stop.await?;
manager.start.await?;
manager.reload.await?;
manager.restart.await?;
startcreates a generation. It does not assert protocol readiness.stopcancels the generation and waits for it to return.restartperformsstopfollowed bystart.reloadretains the generation and advances a reload revision.
A Runnable declares its start_policy: Automatic, Manual, or
Unavailable, which also rejects explicit starts. Snapshots report status,
policy, generation, reload revision and the most recent errors.
Commands are applied by the runtime loop sequentially. A lifecycle hook invoked by that loop must not issue manager commands, since the reply would require the loop that is waiting for the hook.
run drives the whole lifecycle: boot_all, validate_all, spawn_all,
wait for shutdown, drain, finalize_all. It refuses to start when
validation fails and returns the finalize outcome for the caller to inspect.
With config-watch, serve adds watch_configurations and prepare in
front of the same sequence. run_prepared is the sequence after boot, for an
application that prepares the registry itself. The individual steps stay
public for applications that need a different order.
Shutdown is initiated by cancelling the state's shutdown token.
wait_until_shutdown returns, cancels every generation and closes the
manager. drain waits for the runnables to complete. After successful
preparation, finalization runs even if validation, admission or execution
fails, so named resources are released before the failure is returned.
Errors during registration, configuration or boot are returned to the
application; cleanup of partial preparation remains its responsibility.
Continuo imposes no deadline; each runnable owns its
graceful drain, and Gate supplies admission control and a caller-defined
deadline where one is required.
Errors
Lifecycle hooks return continuo::Result. Any std::error::Error converts
with ?; the registry attaches the phase and component name when reporting
the failure.
- A missing dependency fails before the component's hook runs, as
Error::Dependencynaming the component and the type. - Boot stops at the first failure.
runandserverefuse to start on validation failures and returnError::Invalidcarrying the complete outcome.- Validation, reload and finalization continue past a failing component and
return
ValidationOutcome,ReloadOutcomeorFinalizeOutcome. The outerOkindicates that the pass ran; the outcome carries each component failure and is#[must_use]. - A runnable failure is fatal by default: the runtime cancels the remaining
generations, closes the manager and returns the error.
Error::recoverablemarks a failure the runtime logs and survives.
continuo::Error does not implement std::error::Error; the blanket From
that enables ? inside hooks precludes it. Error::into_std converts to a
standard error that preserves the cause chain.
State
SharedState is the only required trait; it returns the shutdown token.
Further capabilities are separate traits, so enabling a feature never adds a
required method to an existing implementation.
| Trait | Exposes | Feature |
|---|---|---|
SharedState |
shutdown CancellationToken |
always |
HasRegistry |
&Registry<Self> |
registry |
HasEvents |
&ProcessEventBus |
events |
HasConfigReader |
&congif::ConfigReader |
config |
ReloadState |
application hook preceding reload_all |
always |
Configuration
Requires the config feature. Configuration is provided by
Congif: a typed Config per owner, one
declared source, validation and immutable snapshots. Continuo re-exports
Configurable and defines no second contract.
A component declares its configuration and exposes it through
as_configurable. Runtime::configure reads and validates every declared
owner before boot; Runtime::prepare performs configure followed by
boot_all. A config owner introduced during boot without having been declared
before configuration is rejected. Components without configuration are valid.
Two hooks apply configuration changes. They are distinct:
Reloadable::reloadis a lifecycle command issued by the manager,reload_oneorreload_all. The component applies the prepared snapshot; Continuo acknowledges the candidate to Congif after the hook succeeds. Registry commands obtain the catalog fromReloadState::reload_config_reader.reload_onerequiresReloadStateand prepares only the addressed owner; it does not invoke the application-wideReloadState::reloadhook. Callers that manage preparation and acknowledgement themselves can usereload_hook_one, which requires noReloadStateand invokes only the hook.ConfigObserver::config_changedis a typed notification carrying the newConfig. Withconfig-watchit is invoked for a changed source.
Both may produce the same effect, and a component may implement both. One is a command; the other is an observation.
With config-watch and Runtime::watch_configurations:
- One native watcher covers every source of every observing owner.
- A changed path is mapped to its owners through the registry.
- The affected configurations are prepared and validated as one batch.
- A rejected batch publishes nothing; previous snapshots remain in effect.
- A successful batch publishes, then
config_changedruns for each owner.
The runtime loop consumes these notifications directly, without an additional
task, channel or polling interval. ConfigurationChanged::of::<Owner>() on
the event bus requests the same path explicitly.
A component whose programs start with their own environments, such as a PHP
application or a task process, implements Environmental. Congif maintains
one dotenw node per program, watches those files with the owner's sources,
and the runtime invokes environment_changed when one is re-read.
Events
Requires the events feature. ProcessEventBus is a process-local typed
broadcast. Any Clone + Send + Sync type implementing Event can be emitted
and subscribed to independently.
;
let mut events = state.events.;
state.events.emit;
Events are delivered only to existing subscribers. Channels are bounded and receivers must handle lag. The bus is neither storage nor a cross-process queue.
subscribe_filtered::<E>(predicate) uses the same bounded receiver contract,
but evaluates the predicate synchronously during publication, before queue
admission. Rejected events cannot consume that subscription's capacity or cause
its lag. The predicate may read a shared selection, but must be cheap,
non-blocking and must not re-enter the bus. No forwarding task or polling loop
is created; only subsequent matching publications are delivered. Dropped
receivers are removed on the next publication or filtered registration.
subscribe_filtered_with_capacity::<E>(capacity, predicate) lets a consumer
declare its own backlog bound without resizing other channels. Capacity is a
positive count of retained events, not event types; Tokio rounds storage up to
the next power of two. Matching overflow still reports lag.
Admission control
Requires the support feature. Gate provides admission control for a
service loop with a capacity, an acquire timeout and a graceful deadline, all
supplied by the caller. enter returns an RAII Permit; graceful_shutdown
stops admission and wait_all_done reports whether accepted work completed
within the deadline. GuardGroup is the smaller primitive for in-flight
counting and waiting for an empty group.
Placement
Requires the fleet feature. Scope and Dispatch describe placement in
multi-process applications: which process roles may host a runnable, and
whether it runs in each eligible process, in one, or across a pool. Components
expose them through as_scoped or as_dispatched. The runtime filters local
runnables against SharedState::process_scope and delegates One and Pool
executions to a Dispatcher<S> installed with Runtime::with_dispatcher.
Without a dispatcher those policies are rejected rather than executed as
Each. Membership, leases and transport are the adapter's responsibility.
Dispatched::dispatch_policy() optionally supplies the service's prepared
DispatchPolicy: pool capacity, lease TTL and renewal interval. Each needs
no policy; a lease-based adapter rejects One/Pool without one. The runtime
passes the value in DispatchRequest and each generation keeps its own
immutable snapshot. The type is transport-neutral data, not an Orbit dependency.
Task managers may retain their own task-level policy and controller.
ServiceSnapshot::status() describes the generation controller, not slot
ownership. active_executions() counts actual runnable futures, including
draining executions until they return. With fleet, dispatch() reports the
generation's placement choice. A running One/Pool controller with zero
executions is waiting. The census is generation-owned and is decremented on
return, error, panic or future cancellation; it does not claim protocol readiness.
Playground
examples/playground is a complete application: an HTTP server with
server-sent events, a persisted counter, Unix signal handling, typed JSON
configuration with environment variables, watched sources with validated
reload, and start, stop, restart and reload through ServiceManager.
Its main is the composition:
async
Application is the example's composition: it holds the selected
environment and a Runtime, and its run builds the state and calls
Runtime::serve. The only fallible input, the command line, is resolved
where it is read. ReloadService requires the ServiceManager and declares it in
Deps; the HTTP and signal services use the counter when it is present and
state a start preference through run_priority. The printed address serves
the counter and its controls;
/services lists lifecycle state, generations and reload revisions. Editing
config/counter.json or config/http.json triggers validation and reload;
the HTTP service binds a replacement listener before releasing the current
one.
examples/playground/
├── main.rs # compose and run
├── app.rs # Application: environment, state, Runtime::serve
├── app/
│ ├── state.rs # AppState and its capability traits
│ ├── config.rs # configuration types
│ ├── counter.rs # the counter value; no Continuo dependency
│ ├── services/ # counter, http, signals, reload, other
│ └── handlers.rs # axum handlers
├── config/ # counter.json, http.json, signals.json
├── web/ # page, styles, script
└── storage/ # persisted counter value
Features
= { = "0.9", = ["config-watch"] }
| Feature | Enables |
|---|---|
registry (default) |
HasRegistry, Runtime::with_services, Runtime::run |
config |
Congif integration: Configurable, as_configurable, as_environmental, reload acknowledgement; with registry, Runtime::configure and Runtime::prepare |
config-watch |
native source watching on top of config; includes registry and events |
events |
ProcessEventBus, HasEvents |
support |
Gate, Permit, GuardGroup, Guard |
fleet |
Scope, Dispatch, Dispatcher, as_scoped, as_dispatched |
full |
all of the above |
The registry, components, runtime and manager are available with no features
enabled. Core dependencies are async-trait, Tokio, tokio-util and
tracing; Congif, dashmap and serde are pulled in only by their features.
Native watching supports Linux, macOS and FreeBSD. Diagnostics are emitted
through tracing; the executable installs the subscriber.
License
Licensed under either of:
- MIT license (LICENSE-MIT)
- Apache License, Version 2.0 (LICENSE-APACHE)