Expand description
Rust core of the RustStream messaging
framework: broker-agnostic traits, message types, codecs, router runtime, and a
conformance harness for broker authors.
§A service
A handler is an async fn over a decoded payload. The application object mounts it on a
broker, and the attribute writes the main:
use ruststream::memory::prelude::*;
use serde::Deserialize;
#[derive(Deserialize)]
struct Order {
id: u64,
}
#[subscriber("orders")]
async fn handle(order: &Order) -> HandlerOutcome {
println!("got order {}", order.id);
HandlerOutcome::ack()
}
#[ruststream::app]
fn app() -> RustStream {
RustStream::new(AppInfo::new("orders", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
b.include(handle);
})
}cargo run -- run starts it. The broker here is the in-process one; a real broker is a
crate of its own with the same shape, and its prelude replaces memory::prelude.
§Where things are
runtime: everything a service is made of. Subscribers and what a handler may take, replies andOutslots, routers, the per-delivery context and the shared state, typed headers, lifecycle hooks, middleware, failure policies, running beside another server.codec: how payload bytes become values and back, where a codec is chosen, and the byte lanes that need none.memory: the in-process broker, a real broker and the reference implementation.testing: testing the service’s own app, in process or against a running broker.asyncapi: the generated document.metrics,logging,otel: observability.runtime::cli: the generated entry point and theruststreamcommand.conformance: the contract suite a broker crate runs against itself.
The broker crates document their own descriptors and publish policies. Installation, the tutorial and the list of brokers are on the site: https://powersemmi.github.io/ruststream/.
§Cargo features
The core traits, the runtime::RustStream application object, middleware, and dispatch are
always present. The rest is additive and opt-in. Codec features are mutually compatible and
enable only the deserializers you need.
json(default):codec::JsonCodec.msgpack:codec::MsgpackCodec.cbor:codec::CborCodec.memory:memory::MemoryBroker, an in-process broker usable in applications, prototypes and tests.macros: the#[subscriber],#[ruststream::app],#[derive(Outgoing)]and#[derive(MessageInfo)]macros.asyncapi:AsyncAPIdocument generation and the HTML viewer.metrics: Prometheus metrics middleware and exporter.logging: colored,RUST_LOG-driven console logging viatracing-subscriber(logging::init). The generatedcliruncommand installs it automatically.otel: OpenTelemetry SDK integration: OTLP export for traces and metrics viaotel::OtelBuilder::init, plus per-handler dispatch metrics middleware and W3C trace-context propagation (otel::propagation).conformance: theconformance::harnesscontract suite, per-capability suites inconformance::capabilities, the in-process transport held to the server inconformance::in_process, the checks of what a message carries inconformance::message_shape, and broker-agnosticconformance::helpersfor application tests. Generic over any broker’stesting::TestableBroker, so it pulls in no concrete broker (enablememorytoo to run it againstmemory::MemoryBroker).testing: thetesting::TestAppharness, which runs the service’s production app in process or against running brokers.cli: theruststreambinary (run,asyncapi gen,new).poll-diagnostics: every subscription samples the time its handler spends inpolland warns when a handler computes on the app’s runtime (runtime::PollDiagnostics).
Disable defaults (default-features = false) to drop the bundled JSON codec; the core traits,
runtime, and dispatch remain. Add back only what you need.
§Getting the imports
prelude carries what a service writes every time (the application object, the handler
surface, the extractor parameters, the macros): use ruststream::prelude::*;. The broker and
the codec stay explicit, since those are the choices a service makes for itself.
Re-exports§
pub use runtime::RustStream;pub use runtime::OutSlot;pub use schemars;
Modules§
- asyncapi
AsyncAPI3.1 document generation from aRustStreamservice.- codec
- Pluggable serialization codecs.
- conformance
- Conformance harness for broker authors.
- logging
- Colorful, environment-driven console logging built on
tracing_subscriber. - memory
- In-process broker: the bus, and what it keeps of what went over it.
- metrics
- Prometheus metrics for consume and publish paths.
- otel
- OpenTelemetry integration (
otelfeature): W3C trace-context propagation, OTLP export, and per-handler dispatch metrics. - prelude
- The imports a service writes every time, in one glob.
- runtime
- The application object, the handler surface, and dispatch.
- testing
- Application testing support, behind the
testingfeature.
Macros§
- nonzero
- Builds a
NonZerointeger from a literal, rejecting zero at compile time. - register_
testable_ broker - Registers a production broker type with the test harness, so
TestAppruns every broker of that type in process.
Structs§
- Addressed
Copies - The copy path of a subscription whose retries this process publishes, to a destination the descriptor knows: a subject, a topic, a queue, a stream key.
- AppId
- The service’s own identifier, which
AsyncAPIrequires to be a URI. - Broker
Moves - The copy path of a subscription whose deliveries the broker moves itself.
- Buffered
- A
SubscriptionSourceadapter that buffers the wrapped source’s subscriber into aBatchSubscriber. - Buffered
Subscriber - The subscriber
Bufferedopens: the wrapped source’s subscriber plus client-side batching. - Bytes
- The shared byte buffer the message path hands around: a payload, a header value taken with
HeaderMap::get_shared. - Bytes
Mut - The buffer the crate’s byte-producing surfaces speak: what a
Codecreturns, what aSerializedvalue writes into, and the payload a publisher that declaredTakeis handed. - Caller
Name - The destination form of a type declaring no name: the call site names the destination.
- Contact
- Who to contact about the service.
- External
Docs - A pointer at documentation kept outside the generated document.
- Fixed
Name - The destination form of a type declaring one literal name: the name is fixed, so the publish builder resolves the destination without asking the call site.
- Header
Map - Case-insensitive map of broker-message headers.
- Lend
- The declaration of a transport that reads the payload and keeps nothing: it is handed
&[u8]. - License
- The licence the service is published under.
- Name
- The default
SubscriptionSource: subscribe by name string via theSubscribecapability. - Name
Template - The destination form of a type declaring a name template: the call site binds every placeholder through the setters generated from it, and the name is rendered per publish.
- Named
Copies - The copy path of a subscription whose retries this process publishes but cannot address: a wildcard subject, an MQTT filter, a Pulsar pattern, a list of topics.
- NoHeaders
- The header contract of a message that carries no typed headers.
- Outgoing
Message - A message ready to be published: a borrowed destination, a payload in the form its publisher declared, and the header map the publish filled.
- Pair
Error - The error of
PublishPolicy::pair: whatever the broker reported while bringing a publisher alive, type-erased. - RawMessage
- An owned snapshot of a message as it travels through the framework.
- Redelivery
Address - The name a deferred redelivery of one subscription is published to.
- Retry
Declaration - What one registration declared about its retries: how many attempts a delivery gets, and where it goes when they run out.
- Security
Scheme - How clients authenticate to an
AsyncAPIserver, per theAsyncAPIsecurity scheme types. - Server
Spec - How to reach a broker, for the
serverssection of anAsyncAPIdocument. - StartAt
- A source decorator opening the subscription at a chosen position instead of the broker’s default.
- Tag
- A group label: on the service, on a server, on an operation.
- Take
- The declaration of a transport whose client keeps the payload: it is handed a
BytesMutof its own. - Unnamed
- The stand-in a definition carries while its subscription has no name yet.
- With
Headers - The header contract of a message whose headers are the typed struct
H.
Enums§
- AckError
- Errors returned by
IncomingMessage::ackandIncomingMessage::nack. - ApiKey
Location - Where an
apiKeyscheme carries the key, perAsyncAPI. - AppId
Error - Why a string is not an
AppId. - Declare
Retry Error - Errors returned by
Subscribe::declare_retry, where a registration mounted by a bare subscription name declares how its deliveries retry. - Deserialize
Headers Error - Error of the crate-internal
to_typedparse: the header map does not satisfy the typed contract. - Http
ApiKey Location - Where an
httpApiKeyscheme carries the key, perAsyncAPI. - Serialize
Headers Error - Error of
HeaderMap::insert_typed: the value does not fit the flat header-map shape.
Traits§
- Batch
Subscriber - A subscriber that delivers messages in batches.
- Broker
- An unconnected broker: configuration captured, no I/O performed yet.
- Build
Batch Context - Builds a batch handler’s context value from the batch’s first delivery.
- Build
Context - Builds a handler’s per-delivery context value from the broker message.
- Connected
Broker - A connected broker: the typed witness of a live connection.
- Context
Field - A
Field-style key that also names its context type and yields an owned value. - Copy
Path - Who publishes the copies a subscription’s retries are made of, and who names where they go.
- Default
Publish - A connected broker that names its plain publish policy, so the runtime can build a default
reply publisher when a
reply("dest")handler is included without an explicit one. - Describe
Server - A broker that describes itself as an
AsyncAPIserver. - Destination
Form - The closed set of destination forms:
FixedName,NameTemplateandCallerName. - Field
- A compile-time key reading one typed field out of
Src. - Field
Mut - A
Fieldkey middleware can also write, for per-delivery scratch values. - From
Name - A subscription kind identified by a name and nothing else.
- Headers
Contract - The closed set of header contract shapes:
NoHeadersandWithHeaders<H>. - Incoming
Message - A message delivered by a
Subscriber. - Message
Headers - Declares a message type’s typed header contract.
- Message
Info - Metadata about a message type, used to name and describe it in an
AsyncAPIdocument. - Outgoing
Destination - Declares where a message type is sent.
- Owned
Transactions - A publisher that opens caller-owned, client-buffered transactions.
- Partitioned
- Messages or publishers that carry a routing key for broker-side partitioning.
- Payload
Form - How a transport consumes the payload of a publish:
Lendwhere it reads the bytes,Takewhere its client keeps them. - Positioned
- A delivered message that knows its own position in the broker’s replayable log.
- Publish
Policy - The declaration half of a publisher: pure policy, no connection, no publish surface.
- Publisher
- A producer that sends messages into the broker.
- Redelivery
Addressed - A subscription descriptor that knows where a publish reaches it again.
- Request
Reply - A publisher that supports synchronous request / reply messaging.
- Seekable
- A subscriber whose position in a replayable log can be moved.
- Seeker
- A clonable handle that repositions one subscription, minted by
Seekable::seeker. - Subscribe
- A connected broker whose subscriptions are fully determined by a name string.
- Subscriber
- A consumer attached to one or more broker names.
- Subscription
Source - A description of one subscription, resolved against a connected broker at startup.
- Transaction
- A client-buffered transaction that owns its buffer, opened by
OwnedTransactions::transaction. - Transactional
Publisher - A publisher that supports broker-side transactions.
Type Aliases§
- Connected
- Shorthand for a broker’s connected form, so bounds read
S: SubscriptionSource<Connected<B>>instead of spelling the associated type projection. - Outgoing
For - The message a publisher of form
Formis handed:OutgoingMessageover that form’s payload. - Str
- The owned string of the message path: a destination name, a header key.
Attribute Macros§
- app
- Attribute macro that generates a
mainentry point from aRustStreambuilder function. - subscriber
- Attribute macro that turns an
async fninto a mountable subscriber definition.
Derive Macros§
- Deserialized
- Derive macro for a self-deserializing input type
(
Deserialized): a newtype or single-field struct over&'a [u8]gains the construction and theInputspelling; the batch spelling (&[Frame<'_>]) follows from it. - FromRef
- Derive macro that implements
FromReffor each field of an application state, so handlers can inject any field withState<T>. - Message
Info - Derive macro for
MessageInfometadata (type name + doc description). - OutMessages
- Derive macro for a declared message set: an enum whose variants each wrap one message
model, named as the third
Outargument (Out<impl Publisher, Marker, SendSet>). The enum is a type-level declaration and is never constructed. - OutSlot
- Derive macro that makes a unit struct a slot marker (
OutSlot) forOut<impl Publisher, Marker>handler parameters. - Outgoing
- Derive macro declaring everything a message type says about being sent: its destination
(
OutgoingDestination) and its optional header contract (MessageHeaders), plus theMessageInfometadata the generated document reads. - Serialized
- Derive macro for a self-serialized outgoing type (
Serialized): a newtype or single-field struct over a byte buffer gains the bytes accessor and the wire spellings that route it onto the serialized wire (MessageWirefor a typed publish,ReplyShapefor the reply position).