Expand description
Messaging for id_effect services: a broker-agnostic MessageBroker, an in-memory broker, and
the transactional outbox, inbox and relay on id_effect_sql.
Topic is the validated name messages are published to: 1 to Topic::MAX_LEN ASCII
letters, digits, ., _ or -, a name every supported broker accepts.
use id_effect_messaging::{Topic, TopicError};
let topic = Topic::new("ledger.entry-posted").unwrap();
assert_eq!(topic.to_string(), "ledger.entry-posted");
assert_eq!(Topic::new("a b"), Err(TopicError::InvalidChar { ch: ' ', index: 1 }));§Brokers
A MessageBroker publishes Messages to a topic and hands them to consumer groups:
every group sees every message of the topic, and the consumers of one group share them. A
subscription is a Stream of Deliverys; each is settled once, with
ack or nack. A nacked (or dropped) delivery is
redelivered until SubscribeOptions::max_deliveries, then moved to the dead-letter topic;
at most SubscribeOptions::prefetch deliveries of a subscription are unsettled at a time.
MemoryBroker implements all of it in memory, for tests and single-process development.
use id_effect_messaging::{
ConsumerGroup, MemoryBroker, Message, MessageBroker, Nack, SubscribeOptions, Topic,
};
let broker = MemoryBroker::new();
let orders = Topic::new("orders").unwrap();
let billing = ConsumerGroup::new("billing").unwrap();
let opts = SubscribeOptions::default().max_deliveries(2);
let eff = broker
.publish(&orders, Message::new("order 1"))
.flat_map({
let (broker, orders, billing) = (broker.clone(), orders.clone(), billing.clone());
move |()| broker.subscribe(&orders, &billing, opts)
})
.flat_map(|deliveries| deliveries.take(2).run_for_each(|d| d.nack(Nack::Requeue)));
assert!(eff.block_on().into_result().is_ok());
// Delivered twice, nacked twice: dead-lettered.
let dlq = broker.messages(&Topic::new("orders.dlq").unwrap());
assert_eq!(dlq[0].payload(), b"order 1");§Outbox, relay and inbox
Outbox::stage writes a message to the table id_effect_outbox with the caller’s
SqlTransaction, so it is published if and only if the caller’s work commits. A Relay
claims the committed rows from an OutboxStore (PgOutbox: FOR UPDATE SKIP LOCKED
with a lease, so several relays share the outbox), publishes each through any
MessageBroker with its staged MessageId, marks it sent, retries a failed publish on a
core Schedule (RelayConfig::retry) and prunes sent rows. Delivery is at least once (a
relay that crashes after publishing publishes again), so consumers deduplicate with
Inbox::once: it records (consumer group, message id) in id_effect_inbox with the
handler’s transaction and runs the handler only the first time; Inbox::handler acks after
the commit. migrator ships both tables, tracked in their own table MIGRATIONS_TABLE.
MemoryOutbox and MemoryInbox are the same in memory, for tests.
use std::sync::Arc;
use id_effect_messaging::{
ConsumerGroup, MemoryBroker, MemoryInbox, MemoryOutbox, Message, MessageId, Once, Relay,
Topic,
};
let (outbox, broker) = (MemoryOutbox::new(), MemoryBroker::new());
let orders = Topic::new("orders").unwrap();
let staged = outbox.stage(&orders, Message::new("o-1").with_id("o-1"));
assert!(staged.block_on().into_result().is_ok());
let relay = Relay::new(Arc::new(outbox.clone()), Arc::new(broker.clone()));
let report = relay.run_until_idle().block_on().into_result().unwrap();
assert_eq!((report.published, broker.messages(&orders).len()), (1, 1));
let inbox = MemoryInbox::new();
let (billing, id) = (ConsumerGroup::new("billing").unwrap(), MessageId::new("o-1"));
let first = inbox.once(&billing, &id, || id_effect::succeed::<_, (), _>("billed"));
let again = inbox.once(&billing, &id, || id_effect::succeed::<_, (), _>("billed twice"));
assert_eq!(first.block_on().into_result(), Ok(Once::Ran("billed")));
assert_eq!(again.block_on().into_result(), Ok(Once::Duplicate));Tier platform (ADR 0010 Amendment 6): the Ledger reference app under
examples/reference/ depends on it.
Modules§
- headers
- The header names brokers set on the messages they carry.
Structs§
- Consumer
Group - A validated consumer group name, with the rules of a
Topicname. Every group of a topic receives every message published to it; the subscriptions of one group share them. - Delivery
- One message delivered to a subscription. Settle it once, with
ackornack, and run the returned effect; until then it counts against the subscription’sprefetch. - Inbox
- Deduplicates consumers in PostgreSQL (the table
id_effect_inbox, frommigrator). Cheap to clone; it holds only theWallClockof theprocessed_attimes. - Memory
Broker - A
MessageBrokerin memory. Clones share the topics. - Memory
Inbox Inboxin memory, for tests and single-process consumers: the same once-only processing without a database. A message is recorded when its handler succeeds; concurrent calls for the same message run one at a time, so the second sees the first’s outcome. Records are kept until the inbox is dropped. Clones share them.- Memory
Outbox OutboxStorein memory, for tests and single-process development: the same claiming, leasing and fencing asPgOutbox, without a database. There is no transaction to stage with, sostagewrites at once. Clones share the rows.- Message
- A message: an id, an optional key (the partition or ordering key on brokers that have one), text headers and an opaque payload.
- Message
Id - A message’s identity, chosen by the producer and kept by every broker and by dead-lettering, so a consumer can deduplicate redeliveries on it (the inbox). It is not the broker’s own position (a Redis Streams entry id, a Kafka offset).
- Outbox
- Stages messages in the outbox table with the caller’s transaction. Cheap to clone; it holds
only the
WallClockthe row times are read from. - Outbox
Id - The id of an outbox row (the
idcolumn). - Pending
- An outbox row a relay claimed: publish
messagetotopic, then settle the row. - PgOutbox
OutboxStorein the PostgreSQL tableid_effect_outbox, over anySqlClient(id_effect_sql::pg::PgSqlClientin production). Clones share the client.- Relay
- Publishes the outbox: claims committed rows from an
OutboxStore, publishes each through aMessageBrokerwith its stagedMessageId, and marks it sent. - Relay
Config - A
Relay’s settings. - Relay
Report - What a
Relaypass did. - Subscribe
Options - How a subscription consumes: flow control, retries and the dead-letter topic.
- Topic
- A validated topic name.
Enums§
- Broker
Error - A broker operation’s failure.
- Dead
Letter Reason - Why a message was moved to a dead-letter topic (its
DEAD_LETTER_REASONheader). - Nack
- What to do with a delivery the consumer did not process.
- Once
- What
Inbox::oncedid. - Outbox
Error - An outbox store’s failure.
- Start
From - Where a consumer group that does not exist yet starts reading its topic. A group that exists carries on from where it is, whatever a later subscription asks.
- Topic
Error - Why a name is not a valid
Topic.
Constants§
- MIGRATIONS_
TABLE - The tracking table of
migrator: separate from the application’s (and fromid_effect_jobs’), so the crate’s version numbers never collide with other migrations.
Traits§
- Acker
- How a broker settles one delivery; a
Deliveryholds one and spends it onackornack. A broker implements it per delivery (Redis Streams:XACKon ack, re-pending orXADDto the dead-letter stream on nack). - Message
Broker - A message broker: publish to a topic, and subscribe a consumer group to it.
- Message
Broker Ext - Schema-typed publishing and the consumer loop, on any
MessageBroker. - Outbox
Store - Where a
Relayfinds the staged messages. Every time is passed in from the relay’sWallClock;relayis the relay’s id, the owner of a lease.
Functions§
- ack_
on_ success - A
consumehandler that runshandlerover each delivery and settles it:ackwhen the handler succeeds,Nack::Requeuewhen it fails (so a message that keeps failing is dead-lettered aftermax_deliveries). The handler’s error is dropped; a handler that dies or is interrupted leaves the delivery to be redelivered. - consume
- Runs
handlerover every delivery, at mostconcurrency(at least 1) at once, until the stream ends; the handler settles each delivery (seeack_on_successfor the common policy). The first failure of the stream or of a handler ends the loop with it, and the deliveries still unsettled then are redelivered. - default_
relay_ retry - The default publish retry of a
RelayConfig: exponential from 500 ms, at most 5 min apart, jittered, forever (a message is never given up on; seeRelayConfig::retry). - migrator
- The crate’s schema (the outbox and inbox tables) as an
id_effect_sqlMigratortracked in its own tableMIGRATIONS_TABLE, so the version numbers never collide with the application’s migrations. Run it at startup (migrator().run_on(client)ormigrator().layer()); it takes the migration advisory lock, so replicas starting together apply it once. The alternative is to copymigrations/0001_id_effect_messaging.{up,down}.sqlinto the application’s own migrations. - retry_
delay - The delay before the attempt after attempt number
attempt(from 1) failed witherror, orNonewhenscheduleis done.