Examples
Each example adds exactly one idea to the one before it. Each has its own tests and lives in rustclamp/examples.
00 · Pico Works#
The smallest Clamp application: plain Rust plus one entrypoint. It proves the facade costs nothing when you use nothing else — no allocations, no registries, no threads, zero bytes of binary size over plain Rust in the Phase 1 measurement.
use rustclamp::prelude::*;
fn main() {
Clamp::run(|| {
println!("Hello Clamp");
});
}
The entrypoint really is this small:
pub struct Clamp;
impl Clamp {
#[inline]
pub fn run<F, R>(run: F) -> R
where
F: FnOnce() -> R,
{
run()
}
}
01 · Capability Prototype#
Business code depends on the Clock capability from Core, not on a concrete clock. You pass the implementation in yourself. No Kernel, no facade.
use std::time::SystemTime;
use rustclamp_core::Clock;
use rustclamp_example_capability::Greeter;
struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> SystemTime {
SystemTime::now()
}
}
fn main() {
println!("{}", Greeter::new(SystemClock).greet("world"));
}
02 · Module Prototype#
A GreeterModule declares that it requires a Clock; a FixedClockModule declares that it provides one. Kernel resolves the requirement by type. Missing, ambiguous and cyclic compositions return structured errors. See Modules.
let clock = FixedClockModule(UNIX_EPOCH + std::time::Duration::from_secs(42));
let provisions = [Provision::<ClockCapability>::from_module(&clock)];
let requirement = CapabilityRequirement::<ClockCapability>::from_module::<GreeterModule>();
let clock = Resolver::resolve::<ClockCapability>(
requirement.required_by(),
&provisions,
requirement.selected_provider(),
)?;
let greeter = Greeter::new(clock);
03 · Contribution Prototype#
Modules contribute CLI commands to a typed command target. Core and Kernel only know “a declaration for a target”; the CLI target owns the command rules — unique names, alphabetical order, what an empty tree means. See Contributions.
let target = CliCommandTarget::<PublicCommands>::new();
let commands = TargetComposition::<_, PublicCommands>::new(vec![
(HelloModule::ID, HelloModule::contribution()),
(GoodbyeModule::ID, GoodbyeModule::contribution()),
])
.build(Some(&target))
.expect("the CLI target accepts these declarations")
.expect("a target produces a command tree");
println!("hello: {}", commands.execute("hello", Some(&clock)).unwrap());
04 · Process Prototype#
One application blueprint resolves a CLI process and a Worker process independently. Each gets only the modules it can reach; Worker-only configuration is read only by Worker. The frozen plan can be printed. See Processes.
cargo run --offline --locked --manifest-path examples/a4-process/Cargo.toml --example a4-process -- inspect cli
One recorded inspection run showed the Clock path as:
example.process.cli-root -> example.process.greeting-command -> example.process.clock
05 · Lifecycle Prototype#
A synchronous lifecycle coordinator tested against fake resources: providers initialize first, consumers stop first, readiness is separate from “started”, and shutdown drains before it cancels. Participants opt into Core's phase traits; a caller-owned database survives shutdown. See Lifecycle.
let outcome = shutdown(start(TestControl::default()), ShutdownReason::Requested);
let inspection = outcome.inspection();
for dependency in inspection.dependencies() {
println!(
"{} requires {}",
dependency.consumer().as_str(),
dependency.provider().as_str()
);
}
The default build uses Runtime's executor-free manual driver. --all-features enables tokio-runtime, which runs the Worker task through the optional Tokio adapter:
cargo run --offline --locked --manifest-path examples/a5-lifecycle/Cargo.toml --example a5-lifecycle
cargo test --offline --locked --all-features --manifest-path examples/a5-lifecycle/Cargo.toml
06 · Users Prototype#
One domain service with a domain-owned UserRepository port, used directly, from a console command, and over optional Axum HTTP, with a memory or PostgreSQL repository. UsersHttp contributes routes that Kernel's TargetComposition passes to the HttpRoutes<Public> target; they compile before any listener binds or pool opens. The console build contains no HTTP, PostgreSQL or Tokio. See Integrations.
let target = HttpRoutes::<Public>::new();
let compiled = TargetComposition::<HttpRoutes<Public>, Public>::new(declarations)
.build(Some(&target))
.map_err(|error| format!("route compilation failed: {error:?}"))?
.ok_or_else(|| "HTTP target unexpectedly produced no router".to_owned())?;
# Console, memory repository
cargo run --locked --manifest-path examples/01-users/Cargo.toml --bin users-console -- create Ada
# HTTP on 127.0.0.1:3000 (override with HTTP_ADDR)
cargo run --locked --manifest-path examples/01-users/Cargo.toml --features http --example 01-users-http
JSON, HTML, XML, binary and event-stream output all derive from the same User result; storage failures reach clients as a deliberately generic message.
Where the source is. Examples 00–13 and the clamp CLI are on main, and every package they use is public. Package source availability does not mean crates.io publication; the code shown is the tested source.
07 · Messaging Prototype#
A local UserCreated event has no serialization traits. The application maps it explicitly to a versioned MessageEnvelope at the process boundary; the domain type never learns about the wire format.
08 · Email worker Prototype#
An API calls the domain's EmailSender port; an adapter turns the request into a message; a Worker handler performs the send. It runs combined over the in-memory bus, or as two independent executables — email-api and email-worker — over NATS JetStream, with bounded retries, dead-lettering, deadlines and correlated tracing across both processes.
let handler = HandlerDeclaration::new(SUBJECT, 1, |message: MessageEnvelope| async move {
let email: EmailPayload = serde_json::from_value(message.payload)
.map_err(|error| HandlerFailure::Permanent(Box::new(error)))?;
println!("delivered email to {}: {} — {}", email.to, email.subject, email.body);
Ok(())
});
09 · Create order Prototype#
orders-api create decrements inventory, inserts the order and its outbox message in one PostgreSQL transaction. outbox-publisher publishes pending rows in bounded batches and marks them only after JetStream confirms; several publishers can run side by side. A durable inbox makes redelivery harmless, and unknown payment outcomes are modelled rather than guessed. See Integrations.
10 · Scheduler Prototype#
Job declarations compose through Kernel's target API and run on a controlled Clock through regular and missed intervals. Stopping admission while an active job drains is part of the example. It uses a standard-library executor — no Tokio, no cron.
11 · Device loop Prototype#
Stage 5, and the proof that Clamp is not secretly a server framework. Simulation::step owns update order and uses integer units, so a run with the same seed and inputs replays exactly; the tests run the fixture twice and compare every state. No promise is made about cross-platform floating-point replay.
let mut random = Seeded::new(42);
for delta in [1, -1, 3] {
Simulation::step(&mut state, Input { delta }, &mut random);
println!(
"step={} position={}mm velocity={}mm/step",
state.steps, state.position_mm, state.velocity_mm_per_step
);
}
- Fake device.
FakeSensorvalidates raw readings at ingestion, reports missing and stale samples, survives disconnection, and queues at most eight inputs. Each tick does bounded work, updates a fake display and optionally emits telemetry. - CAN target. Decoders are contributed like routes and compiled into a sorted table; duplicate frame IDs are rejected.
- Two projections. The simulation and a service run as separate processes from one blueprint. Tokio appears only with the
tokio-servicefeature; the default graph is Core, Kernel and Runtime.
LoopRuntime drives the same steps inside Runtime's task context, checking cancellation between ticks. See Loops and devices.
12 · Platform-neutral Prototype#
A #![no_std] library using alloc::Vec and one Core module identity, with no Kernel or Runtime — Core adopted piece by piece in code that never touches std. It shows consumer-side no_std + alloc compatibility; Core itself does not yet build on bare metal, because Clock exposes std::time::SystemTime.
13 · RustClamp site server Prototype#
A small application assembles its static-file routes through Clamp's public HTTP contribution target and serves either site's generated public/ directory. The Python and Rust previews returned identical status codes and response bytes for representative pages, assets and 404 routes. The Python program still generates the pages; synchronous file reads make this a local hosting proof, not a production asset server.
cargo run --offline --manifest-path examples/08-site-server/Cargo.toml \
--example 08-site-server -- rustclamp.com/public