NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RUST CLIENT / MESSAGE BROKER CLIENT

Message broker client

The broker module of rasterizeddb_client talks to RasterizedDB's built-in message broker over its native protocol. Use it to create topics, queues and exchanges, publish records through a batching producer, and consume them with push subscriptions, from the same crate you use for SQL.

Add the dependency

The broker module is in rasterizeddb_client 1.1.0 and later, where the broker feature is on by default.

toml
[dependencies]
rasterizeddb_client = "1.1"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }

To build only the broker client, without the ORM derive macros and client-side sharding, turn the default features off:

toml
[dependencies]
rasterizeddb_client = { version = "1.1", default-features = false, features = ["broker"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }

Everything on this page is under rasterizeddb_client::broker. The module has its own Options, Result and BrokerError types, separate from the SQL client's. The examples below import names one by one so that broker::Result does not hide std::result::Result.

Enable the broker on the server

The native broker port is closed until you give the server --broker-port. These are the server flags the client depends on:

FlagDefaultWhat it does
--broker-port <PORT>closedTCP port for the native protocol. 7171 is the usual choice.
--broker-socket <PATH>noneServes the native protocol on a unix socket, beside the port or instead of it.
--broker-addr <ADDR>127.0.0.1The address the broker ports listen on. Set it to reach the broker from other machines.
--broker-auth <password|trust>passwordpassword checks the login against the database's roles. trust asks for no login and is refused on anything but loopback.
--broker-tls <on|off>offTLS on --broker-port, using the PostgreSQL port's certificate (--pg-cert/--pg-key, or a self-signed pair made at start).
--broker-ddl <any|superuser>anyWho may create, alter and drop topics, queues, exchanges and bindings.

The native port serves the server's default database (--pg-default-db). For the other broker flags, the Kafka, AMQP and MQTT ports, the BROKER SQL statements and the topic privileges (GRANT PRODUCE, CONSUME ON TOPIC …), see Message broker.

Connect

Broker::connect opens one connection, says hello, and logs in when the options carry a user.

rust
use rasterizeddb_client::broker::{Broker, Options};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    broker.ping().await?;
    println!("connected");
    Ok(())
}

The address is host:port, or unix:/path/to/socket for a server started with --broker-socket. Unix sockets work on Unix only.

One Broker carries any number of requests at once: replies come back in whatever order the server finishes them. Broker is cheap to clone, and every clone shares the same connection, so clone it into tasks rather than connecting again.

Logging in

ConstructorUse it when
Options::password(user, password)The server runs with --broker-auth password (the default). The user is a database role.
Options::trust()The server runs with --broker-auth trust. No login is sent.

If you connect without a user to a server that wants a login, connect fails with Code::AuthRequired. A wrong user name or password fails with Code::AuthFailed.

TLS

Start the server with --broker-tls on, then add a trust rule with Options::with_tls. The trust types are the ones the SQL client uses (see Connecting): rasterizeddb_client::Trust, and the helpers rasterizeddb_client::pin and rasterizeddb_client::load_ca.

Pin the server certificate by its SHA-256 fingerprint:

rust
use rasterizeddb_client::broker::{Broker, Options};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // openssl x509 -noout -fingerprint -sha256 -in server.pem
    let trust = rasterizeddb_client::pin(&["AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89"])?;
    let options = Options::password("app", "secret").with_tls(trust);
    let broker = Broker::connect("mq.example.com:7171", options).await?;
    broker.ping().await?;
    Ok(())
}

Or trust a private certificate authority:

rust
use rasterizeddb_client::broker::{Broker, Options};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let trust = rasterizeddb_client::load_ca("/etc/rasterizeddb/ca.pem")?;
    let options = Options::password("app", "secret").with_tls(trust);
    let broker = Broker::connect("mq.example.com:7171", options).await?;
    broker.ping().await?;
    Ok(())
}

The client sends the host part of the address as the server name; with load_ca, the server's certificate must be valid for that name. Pin a certificate the server keeps (--pg-cert/--pg-key): the self-signed pair a server makes for itself without them is a new one at every start. rasterizeddb_client::Trust::AcceptAny encrypts without checking who the server is; use it only on a link you already trust.

A unix socket takes no TLS: with_tls is ignored for a unix: address.

Options reference

Options (in rasterizeddb_client::broker):

FieldTypeDefaultWhat it does
userOption<String>NoneThe role to log in as. None sends no login.
passwordOption<String>NoneThe role's password.
client_nameString"rasterizeddb_client"The name the client gives in its hello.
timeoutDuration30 secondsHow long each request waits for its reply before it fails.
tlsOption<Trust>NoneTLS to the broker port, believing the server as the Trust says. None is plain TCP.

Options::default() and Options::trust() give the defaults above. Options::password(user, password) sets user and password and leaves the rest at their defaults. with_tls(trust) sets tls.

Topics

A topic is a named set of partitions. Each partition is an append-only log, and every record in it has a 64-bit offset. Records are kept until retention removes them, whether or not anyone has read them.

rust
use rasterizeddb_client::broker::{Broker, Durability, Options, TopicConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;

    let config = TopicConfig { partitions: 8, durability: Durability::Sync, ..Default::default() };
    let orders = broker.create_topic("orders", &config, true).await?;
    println!("topic {} has id {} and {} partitions", orders.name, orders.id, orders.partitions);

    for t in broker.list_topics().await? {
        println!("{}: {} messages, {} bytes, queue = {}", t.name, t.messages, t.bytes, t.queue);
    }
    Ok(())
}
MethodReturnsWhat it does
create_topic(name, &config, if_not_exists)TopicRefCreates a topic. With if_not_exists = true, an existing topic of that name is returned when its partitions and durability match, and the call fails with Code::Mismatch when they do not. With false, an existing topic fails with Code::TopicExists.
topic(name)TopicRefLooks a topic up by name. The answer is remembered for the life of the connection. Fails with Code::NoTopic when there is none.
alter_topic(name, &config)TopicConfigChanges retention_ms, retention_bytes, segment_bytes and max_batch_bytes, and returns the topic's settings after the change. The other fields of config are ignored.
delete_topic(name, if_exists)boolDeletes a topic and its subscriptions. true when a topic was deleted.
list_topics()Vec<TopicInfo>Every topic the role may see.

A topic or queue name is 1 to 255 bytes with no control characters. A topic has 1 to 4096 partitions.

TopicRef is what other calls take to name a topic. Its fields: name, id (the number the protocol uses), partitions, durability, and queue (whether it is a queue's topic).

TopicInfo fields: id, name, config (a TopicConfig), queue, messages and bytes.

TopicConfig reference

FieldTypeDefaultWhat it does
partitionsu321Number of partitions. Fixed once the topic exists.
durabilityDurabilityDurability::SyncWhen an append counts as stored (below). Fixed once the topic exists.
retention_msi647 days (604800000)Records older than this are removed. -1 keeps them forever.
retention_bytesi64-1Size limit per partition; -1 is unbounded.
segment_bytesu64256 MiBSize of one log segment file on disk.
max_batch_bytesu3216 MiBThe largest batch the topic accepts. A larger one is refused with Code::BadBatch.
memory_bytesu6464 MiBFor a Memory topic, the size of the in-memory ring per partition.

Durability

DurabilityAn append is acknowledged whenIt survives
Sync (default)it is synced to disk. One sync covers every batch appended since the last one, across all connections.power loss
Asyncit is in the operating system's page cache. The server syncs async topics every --broker-flush-ms.a process crash; a power loss can take the last flush interval
Memoryit is in the in-memory ring. Nothing is written to disk.nothing

Publishing

The batching producer

Broker::producer makes a Producer for one topic. It gathers records per partition into batches and sends each batch as one frame, which is the fast way to write many records.

rust
use rasterizeddb_client::broker::{Broker, Options, ProducerOptions, TopicConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    let orders = broker.create_topic("orders", &TopicConfig { partitions: 8, ..Default::default() }, true).await?;

    let producer = broker.producer(orders, ProducerOptions::default());

    // Keyed: every record with this key goes to the same partition, in order.
    let offset = producer
        .send(Some("customer-7".as_bytes()), br#"{"total": 42}"#, &[(b"source".as_slice(), b"web".as_slice())])
        .await?;
    println!("stored at offset {offset}");

    // Many records at once: each send is queued when called, so start them all
    // and wait afterwards.
    let pending: Vec<_> = (0..1000)
        .map(|i| producer.send(None, format!("event {i}").as_bytes(), &[]))
        .collect();
    producer.flush();
    for p in pending {
        p.await?;
    }
    Ok(())
}
MethodWhat it does
send(key, value, headers)Queues a record and returns a future that resolves to its offset once its batch is acknowledged. A record with a key goes to the key's partition; records without one are spread round robin.
send_to(partition, key, value, headers)The same, to a partition you choose (numbered from 0).
flush()Sends every partly built batch now, without waiting for linger.
topic()The TopicRef the producer writes to.

key is Option<&[u8]>, value is &[u8], and headers is &[(&[u8], &[u8])] (name, value pairs). The record is queued when you call send, not when you await the future, so records go out in call order. Dropping the future does not cancel the record. The future does not borrow its arguments, so it can be moved into another task. Producer is cheap to clone; clones share their batches.

A batch is sent when it reaches batch_bytes, or linger after its first record, whichever comes first.

ProducerOptions reference

FieldTypeDefaultWhat it does
batch_bytesusize256 KiB (262144)A partition's batch is sent once it reaches this many bytes.
lingerDuration1 ms... or this long after its first record.
ackAckAck::DurableWhen the server replies (below). Ack::None is taken as Ack::Written, since send resolves to an offset.
idempotentboolfalseMarks batches with a producer id and sequence, so a batch the server receives twice is stored once.

Acknowledgement modes

AckThe reply comes
Nonenever: fire and forget. Errors are not reported.
Writtenonce the batch is appended (in memory or the page cache).
Durable (default)once the batch is as durable as its topic is: synced to disk for a Sync topic.

Sending one batch yourself

Broker::produce sends a batch you built with BatchBuilder to one partition, and returns where it was stored.

rust
use rasterizeddb_client::broker::{Ack, BatchBuilder, Broker, Options, BY_KEY};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    let orders = broker.topic("orders").await?;

    let mut batch = BatchBuilder::new();
    batch.push(Some(b"customer-7".as_slice()), b"first", &[])?;
    batch.push(Some(b"customer-7".as_slice()), b"second", &[])?;
    let bytes = batch.finish();

    let stored = broker.produce(&orders, BY_KEY, &bytes, Ack::Durable).await?;
    println!("partition {} from offset {}", stored.partition, stored.base_offset);
    Ok(())
}

The partition is a number from 0, or BY_KEY (the partition of the first record's key), or ANY_PARTITION (round robin). The result has partition, base_offset (the first record's offset; the rest follow in order) and duplicate (an idempotent batch that was already stored; base_offset is where it went the first time). With Ack::None nothing comes back and the result is a placeholder.

BatchBuilder methods:

MethodWhat it does
BatchBuilder::new() / with_capacity(bytes)An empty batch.
push(key, value, headers)Adds a record whose time the server stamps.
push_at(key, value, headers, time_us)Adds a record with its own time, in microseconds since the Unix epoch. A batch holds either kind of record, not both, and its records' times must lie within about 71 minutes of each other.
set_limit(bytes)The largest batch push builds; the record that would pass it is refused, unless it is the first.
count(), is_empty(), len_bytes()Records and bytes so far.
finish()The finished batch as bytes. The builder starts over, empty.

Scheduled delivery

A record with the header DELIVER_AT_HEADER is held back from shared subscriptions (and queues) until the time in it. deliver_at(time_us) makes the header's value from microseconds since the Unix epoch. Ordered and broadcast subscriptions ignore the header.

rust
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use rasterizeddb_client::broker::{Broker, DELIVER_AT_HEADER, Options, ProducerOptions, deliver_at};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    let reminders = broker.topic("reminders").await?;
    let producer = broker.producer(reminders, ProducerOptions::default());

    let in_one_minute = (SystemTime::now().duration_since(UNIX_EPOCH)? + Duration::from_secs(60)).as_micros() as i64;
    let when = deliver_at(in_one_minute);
    producer.send(None, b"call the customer back", &[(DELIVER_AT_HEADER, &when[..])]).await?;
    Ok(())
}

Consuming

Subscription modes

A subscription is a named reader of one topic. SubConfig::mode picks how it hands records out:

SubModeBehaviourUse it for
Shared (default)Competing consumers. Each record goes to one member, which acks it. A record is delivered again when it is nacked, when its ack timeout passes, or when its consumer disconnects.work queues
OrderedOne committed offset per partition, with the partitions shared out among the members. Order holds within a partition.consumer groups, ordered streams
BroadcastEach subscribe call gets its own cursor, kept only in memory. Nothing is stored for it and acks do nothing.plain pub/sub

Every member that subscribes with the same name joins the same subscription. Different subscription names on one topic each see every record.

Subscribing and acking

rust
use rasterizeddb_client::broker::{Broker, Options, SubConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    let orders = broker.topic("orders").await?;

    let mut sub = broker.subscribe(&orders, "billing", SubConfig::default(), 1024).await?;
    while let Some(delivery) = sub.next().await {
        let delivery = delivery?;
        for r in delivery.records() {
            println!("partition {} offset {}: {}", delivery.partition, r.offset, String::from_utf8_lossy(r.value));
        }
        sub.ack_delivery(&delivery)?;
    }
    Ok(())
}

subscribe(&topic, name, config, credits) joins subscription name, creating it with config when it does not exist. The server pushes up to credits records ahead of what you have taken. next() grants credit back as you take deliveries, so about one window of records stays in flight.

A subscription's settings are fixed when it is first made. Joining an existing one keeps its settings; joining it with a different mode fails with Code::Mismatch. start applies only to a subscription that has no position yet.

Subscription methods:

MethodWhat it does
next().awaitThe next Delivery, or an error. None once the subscription's channel is gone. Grants credit as it goes.
ack(&ranges) / ack_delivery(&delivery)Acks records. A shared subscription forgets them; an ordered one commits past them. No reply is awaited: a refused ack comes back as an error from next().
nack(&ranges, delay)Hands records back to be delivered again after delay (shared).
renew(&ranges, extend).awaitKeeps records in flight extend longer, like renewing a lock. Duration::ZERO means the subscription's ack timeout. Returns how many records were in flight.
commit(partition, offset).awaitSets an ordered subscription's committed offset for a partition, and waits for the server to take it.
credit(n)Lets the server push n more records. Only needed with next_push.
next_push().awaitThe next raw Push (Deliver, Assign or Closed), without granting credit.
handle()The subscription's handle on this connection.
assigned (field)The partitions an ordered subscription gave this member. It changes as members come and go.
close().awaitLeaves the subscription. A shared one's unacked records go to the other members. Dropping a Subscription also leaves it, without waiting.

A Range is partition, offset and count: the offsets offset up to offset + count of that partition.

Ordered subscriptions and offsets

rust
use rasterizeddb_client::broker::{Broker, Options, Start, SubConfig, SubMode};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    let orders = broker.topic("orders").await?;

    let config = SubConfig { mode: SubMode::Ordered, start: Start::Earliest, ..Default::default() };
    let mut sub = broker.subscribe(&orders, "search-indexer", config, 4096).await?;
    println!("this member reads partitions {:?}", sub.assigned);

    while let Some(delivery) = sub.next().await {
        let delivery = delivery?;
        for r in delivery.records() {
            println!("{} {}", r.offset, String::from_utf8_lossy(r.value));
        }
        // Moves the committed offset past these records.
        sub.ack_delivery(&delivery)?;
    }
    Ok(())
}

Run the same program several times to share the partitions among the instances. A member with no partitions gets nothing, so more members than partitions leaves some idle.

An ack on an ordered subscription only moves the committed offset forward. commit(partition, offset) sets it anywhere, forward or back; offset is the next record to read. A restarted member continues from the committed offset.

Broadcast

rust
use rasterizeddb_client::broker::{Broker, Options, Start, SubConfig, SubMode};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    let prices = broker.topic("prices").await?;

    let config = SubConfig { mode: SubMode::Broadcast, start: Start::Latest, ..Default::default() };
    let mut sub = broker.subscribe(&prices, "ticker", config, 1024).await?;
    while let Some(delivery) = sub.next().await {
        for r in delivery?.records() {
            println!("{}", String::from_utf8_lossy(r.value));
        }
    }
    Ok(())
}

A broadcast cursor starts where start says; set Start::Latest to receive only new records.

Redelivery, delivery counts and dead letters

In a shared subscription, a record not acked within ack_timeout_ms is delivered again, to any member. Call renew for work that takes longer, or nack to give a record back early.

Delivery::delivery_count(partition, offset) says which delivery of a record this is: 1 for the first. When it equals the subscription's max_deliveries, this is the last attempt: if that one is not acked either, the record moves to the dead_letter topic, or is dropped when dead_letter is empty. Counts start again from 1 after a server restart.

rust
use std::time::Duration;

use rasterizeddb_client::broker::{Broker, Options, Range, SubConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    let jobs = broker.topic("jobs").await?;

    let config = SubConfig { ack_timeout_ms: 60_000, max_deliveries: 5, dead_letter: "jobs-failed".into(), ..Default::default() };
    let mut sub = broker.subscribe(&jobs, "workers", config, 16).await?;

    while let Some(delivery) = sub.next().await {
        let delivery = delivery?;
        for r in delivery.records() {
            let one = [Range { partition: delivery.partition, offset: r.offset, count: 1 }];
            if r.value.is_empty() {
                // Try again in ten seconds.
                sub.nack(&one, Duration::from_secs(10))?;
            } else {
                println!("attempt {}: {}", delivery.delivery_count(delivery.partition, r.offset), String::from_utf8_lossy(r.value));
                sub.ack(&one)?;
            }
        }
    }
    Ok(())
}

SubConfig reference

FieldTypeDefaultWhat it does
modeSubModeSubMode::SharedShared, Ordered or Broadcast (above).
startStartStart::EarliestWhere a subscription with no position starts: Earliest (the first kept record), Latest (the next new record), Offset(u64), or Time(i64) (the first record at or after this time, in microseconds since the Unix epoch).
ack_timeout_msu3230000A delivery not acked within this is delivered again (shared).
max_deliveriesu320Deliveries before a record goes to dead_letter (shared). 0 is no limit.
dead_letterStringemptyThe topic records go to after max_deliveries. Empty drops them.

Reading a delivery

Delivery fields and methods:

ItemWhat it is
partitionThe partition the records come from.
rangesThe offsets delivered to this member, as Ranges.
countsDeliveryCount { partition, offset, deliveries } for records on their second or later delivery.
records()The delivered records, in order. Only this member's records are yielded.
count()How many records were delivered.
delivery_count(partition, offset)Which delivery of that record this is (1 for the first).
raw()The stored batches as received, for code that parses them itself.
models::<M>()The records decoded as ORM models (see Models as messages).

Each record is a RecordView with these fields: offset, time_us (microseconds since the Unix epoch), key (Option<&[u8]>), value (&[u8]) and index (its position in its batch). header(name) returns the first header with that name, headers() iterates over (name, value) pairs, and header_count() counts them.

Fetching (pull)

Instead of subscribing, you can read a partition from any offset with fetch. Nothing is recorded on the server about what you have read.

rust
use std::time::Duration;

use rasterizeddb_client::broker::{Broker, EARLIEST, Options};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    let orders = broker.topic("orders").await?;

    let (mut offset, log_start, next) = broker.list_offsets(&orders, 0, EARLIEST).await?;
    println!("partition 0 keeps offsets {log_start}..{next}");

    loop {
        let fetched = broker.fetch(&orders, 0, offset, 1 << 20, Duration::from_secs(5)).await?;
        for r in fetched.records() {
            println!("{} {}", r.offset, String::from_utf8_lossy(r.value));
        }
        offset = fetched.next_fetch();
    }
}

fetch(&topic, partition, offset, max_bytes, max_wait) returns up to max_bytes of whole stored batches from offset, waiting up to max_wait when nothing is there yet. An offset before the first kept record fails with Code::OffsetOutOfRange. The Fetched result has partition, next_offset (the offset the next append gets), log_start (the first kept offset), records() (records at or after the offset you asked for), batches(), next_fetch() (the offset to ask for next) and models::<M>().

list_offsets(&topic, partition, at) returns (offset, log_start, next_offset), where offset is the one for at: LATEST (the next offset), EARLIEST (the first kept offset), or a time in microseconds since the Unix epoch.

Managing subscriptions

MethodReturnsWhat it does
list_subscriptions(&topic)Vec<SubInfo>Each subscription's name, config, members, backlog (records not yet acked or committed past) and inflight.
delete_subscription(&topic, name, if_exists)boolDeletes a stored subscription. true when one was deleted.

Queues

A queue is a topic with one partition plus a shared subscription of the same name. declare_queue makes both in one step, and consume subscribes to it.

rust
use rasterizeddb_client::broker::{Ack, BatchBuilder, Broker, Options, QueueConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    broker.declare_queue("emails", &QueueConfig { max_deliveries: 3, dead_letter: "emails-failed".into(), ..Default::default() }, true).await?;

    // Publish through the default exchange ("") to the queue by name.
    let mut batch = BatchBuilder::new();
    batch.push(None, b"welcome mail for user 42", &[])?;
    broker.publish("", "emails", &batch.finish(), Ack::Durable, true).await?;

    let mut jobs = broker.consume("emails", 32).await?;
    if let Some(delivery) = jobs.next().await {
        let delivery = delivery?;
        for r in delivery.records() {
            println!("sending: {}", String::from_utf8_lossy(r.value));
        }
        jobs.ack_delivery(&delivery)?;
    }
    Ok(())
}
MethodReturnsWhat it does
declare_queue(name, &config, if_not_exists)TopicRefDeclares a queue. Declaring one that exists with other settings fails with Code::Mismatch. With if_not_exists = false, an existing queue fails with Code::TopicExists.
consume(name, credits)SubscriptionJoins the queue's shared subscription.
delete_queue(name, if_exists)boolDeletes a queue. Fails on a name that is a plain topic.

The TopicRef a queue returns works with producer and produce like any topic.

QueueConfig reference

FieldTypeDefaultWhat it does
durabilityDurabilityDurability::SyncAs for topics.
ack_timeout_msu3230000A delivery not acked within this is delivered again.
max_deliveriesu320Deliveries before a message goes to dead_letter. 0 is no limit.
dead_letterStringemptyThe topic messages go to after max_deliveries. Empty drops them.
message_ttl_msi64-1Messages older than this are dropped at delivery. -1 is never.
max_lengthi64-1Messages kept; the oldest go first. -1 is unbounded.

Exchanges and routing

An exchange maps a routing key (and, for Headers, record headers) to one or more topics. A publish appends one copy to each matched topic, once per topic even when several bindings name it.

rust
use rasterizeddb_client::broker::{Ack, BatchBuilder, Binding, Broker, ExchangeKind, Options, TopicConfig, XMatch};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    broker.create_topic("eu-orders", &TopicConfig::default(), true).await?;
    broker.declare_exchange("orders-x", ExchangeKind::Topic, true, None).await?;
    broker
        .bind(&Binding {
            exchange: "orders-x".into(),
            topic: "eu-orders".into(),
            key: "order.eu.*".into(),
            x_match: XMatch::All,
            args: Vec::new(),
        })
        .await?;

    let mut batch = BatchBuilder::new();
    batch.push(None, b"order 1001", &[])?;
    let reached = broker.publish("orders-x", "order.eu.de", &batch.finish(), Ack::Durable, true).await?;
    println!("reached {reached} topic(s)");
    Ok(())
}
ExchangeKindA binding matches when
Directits key equals the routing key.
Fanoutalways.
Topicits key matches the routing key as .-separated words: * matches one word, # zero or more.
Headersthe record headers match its args: all of them with XMatch::All, any one with XMatch::Any. Args whose names start with x- are not compared.
Mqttits key matches as an MQTT filter: /-separated, + one level, # the rest.
MethodReturnsWhat it does
declare_exchange(name, kind, durable, alternate)()Declares an exchange. A non-durable one is not kept across a server restart. alternate names an exchange that routes what this one cannot. Declaring an existing name with another kind fails with Code::Mismatch.
delete_exchange(name, if_exists)booltrue when one was deleted.
bind(&binding)boolAdds a binding; false when it was already there.
unbind(&binding)boolRemoves a binding.
publish(exchange, key, &batch, ack, mandatory)u32Publishes one batch and returns how many topics it reached. The exchange "" sends to the queue or topic named key. With mandatory = true, reaching none fails with Code::Unroutable; otherwise the batch is dropped. With Ack::None the result is 0.

Binding fields: exchange, topic (the topic or queue it delivers to), key, x_match (default XMatch::All, used by Headers), and args (Vec<(String, Vec<u8>)>, used by Headers).

Within a matched topic, a published batch goes to the partition of its first record's key, or round robin when it has none.

Models as messages

A #[derive(Model)] struct from the ORM can be the message itself. model_topic::<M>(partitions, options) uses the topic named after the model's table, creating it with partitions when it does not exist, and returns a ModelTopic<M> that publishes rows. Readers decode them with Delivery::models::<M>() or Fetched::models::<M>(). The derive needs the crate's derive feature, which is on by default.

rust
use rasterizeddb_client::Model;
use rasterizeddb_client::broker::{Broker, Options, ProducerOptions, SubConfig};

#[derive(Model, Clone, Debug)]
struct Order {
    #[rdb(primary_key)]
    id: i64,
    total: i64,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;

    let orders = broker.model_topic::<Order>(8, ProducerOptions::default()).await?;
    orders.publish(&Order { id: 1, total: 42 }).await?;

    let mut sub = broker.subscribe(orders.topic(), "billing", SubConfig::default(), 256).await?;
    if let Some(delivery) = sub.next().await {
        let delivery = delivery?;
        for order in delivery.models::<Order>() {
            println!("{:?}", order?);
        }
        sub.ack_delivery(&delivery)?;
    }
    Ok(())
}

The record's key is the primary key, so every change to one row lands in one partition, in order; a model without a primary key is spread round robin. The value holds each column by name, so a consumer built from another version of the struct still finds each column. Each record carries the header MODEL_HEADER (rdb-model) with the table name.

ItemWhat it does
broker.model_topic::<M>(partitions, options)The topic named after M's table, created when missing.
broker.model_topic_on::<M>(topic, options)M rows on a topic you choose.
ModelTopic::publish(&m)Publishes a row; resolves to its offset once stored.
ModelTopic::flush(), ModelTopic::topic()As on Producer.
encode_model(&m) / decode_model::<M>(value)The key and value for a row, and the row back from a value, for use with BatchBuilder or fetch.

Errors

Every call returns rasterizeddb_client::broker::Result<T>, whose error is BrokerError:

FieldTypeWhat it is
codeOption<Code>The server's error code, or None for a failure on the client side: the connection closed, a reply that did not arrive within Options::timeout, an address that does not resolve, a malformed reply.
messageStringA readable description.

BrokerError implements std::error::Error and Display, so it works with ? in a function returning Box<dyn std::error::Error>. Errors from the SQL client's helpers, such as rasterizeddb_client::pin, convert into it too. For the SQL client's own errors see Errors.

rust
use rasterizeddb_client::broker::{Broker, Code, Options};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let broker = Broker::connect("127.0.0.1:7171", Options::password("app", "secret")).await?;
    match broker.topic("orders").await {
        Ok(t) => println!("orders has {} partitions", t.partitions),
        Err(e) if e.code == Some(Code::NoTopic) => println!("no orders topic yet"),
        Err(e) => return Err(e.into()),
    }
    Ok(())
}

When the connection is lost, every waiting call fails with "the broker connection is closed", and every subscription's next() returns that error.

CodeMeaning
UnknownAn error code this client does not know.
ProtocolThe server could not read a request.
AuthRequiredThe server wants a login, or a request came before one.
AuthFailedWrong user name or password.
PermissionThe role lacks the privilege, or may not change the broker's objects (--broker-ddl).
NoTopicNo topic or queue of that name or id.
TopicExistsA topic of that name exists and if_not_exists was false.
NoPartitionThe partition number is past the topic's last.
BadBatchThe batch is malformed or larger than the topic's max_batch_bytes.
TooLargeOver a size limit.
OffsetOutOfRangeA fetch from before the first kept offset.
NoSubscriptionNo subscription of that name or handle.
NoExchangeNo exchange of that name.
MismatchDeclared again with different settings.
UnroutableA mandatory publish reached no topic.
StorageThe server could not write or read its files; its log says why.
ShuttingDownThe server is stopping.
InvalidA setting or name out of range (for example 0 partitions, or an empty name).
FencedAn idempotent producer's epoch is older than the one the partition has seen.
OutOfOrderA sequence gap from an idempotent producer.
UnsupportedThe request is not supported, such as changing a topic's partitions or durability.
FullThe queue is full and refuses new messages.

Limits

  • The broker client is not in any release yet. Its API can change before it is.
  • There is no automatic reconnect. When the connection drops, pending calls and subscriptions fail; connect again and subscribe again.
  • Options::timeout applies to each request. It does not limit how long next() waits for a delivery.
  • A topic looked up by name is remembered for the life of the connection. If another client deletes and re-creates it, calls with the old TopicRef fail with Code::NoTopic; connect again to pick up the new one.
  • A topic's partitions and durability cannot be changed after it is created.
  • A Producer takes the partition count from its TopicRef when it is made. send_to with a partition past the last one writes to the last partition.
  • The producer does not retry a failed batch. With idempotent, a duplicate is recognised only within one Producer, which gets a new producer id each time it is made.
  • With Ack::None, failures are not reported.
  • Shared subscriptions deliver at least once: after a server restart, anything not acked is delivered again, and delivery counts start again from 1.
  • A broadcast subscription's position lives in memory only and ends with its connection.
  • A Headers exchange routes a published batch by its first record's headers.
  • The native port serves only the server's default database.
  • Unix socket addresses work on Unix only.
✓ page rendered in 181 µs axum + tera + htmx · no other javascript