Skip to main content

Crate id_effect_messaging

Crate id_effect_messaging 

Source
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§

ConsumerGroup
A validated consumer group name, with the rules of a Topic name. 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 ack or nack, and run the returned effect; until then it counts against the subscription’s prefetch.
Inbox
Deduplicates consumers in PostgreSQL (the table id_effect_inbox, from migrator). Cheap to clone; it holds only the WallClock of the processed_at times.
MemoryBroker
A MessageBroker in memory. Clones share the topics.
MemoryInbox
Inbox in 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.
MemoryOutbox
OutboxStore in memory, for tests and single-process development: the same claiming, leasing and fencing as PgOutbox, without a database. There is no transaction to stage with, so stage writes 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.
MessageId
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 WallClock the row times are read from.
OutboxId
The id of an outbox row (the id column).
Pending
An outbox row a relay claimed: publish message to topic, then settle the row.
PgOutbox
OutboxStore in the PostgreSQL table id_effect_outbox, over any SqlClient (id_effect_sql::pg::PgSqlClient in production). Clones share the client.
Relay
Publishes the outbox: claims committed rows from an OutboxStore, publishes each through a MessageBroker with its staged MessageId, and marks it sent.
RelayConfig
A Relay’s settings.
RelayReport
What a Relay pass did.
SubscribeOptions
How a subscription consumes: flow control, retries and the dead-letter topic.
Topic
A validated topic name.

Enums§

BrokerError
A broker operation’s failure.
DeadLetterReason
Why a message was moved to a dead-letter topic (its DEAD_LETTER_REASON header).
Nack
What to do with a delivery the consumer did not process.
Once
What Inbox::once did.
OutboxError
An outbox store’s failure.
StartFrom
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.
TopicError
Why a name is not a valid Topic.

Constants§

MIGRATIONS_TABLE
The tracking table of migrator: separate from the application’s (and from id_effect_jobs’), so the crate’s version numbers never collide with other migrations.

Traits§

Acker
How a broker settles one delivery; a Delivery holds one and spends it on ack or nack. A broker implements it per delivery (Redis Streams: XACK on ack, re-pending or XADD to the dead-letter stream on nack).
MessageBroker
A message broker: publish to a topic, and subscribe a consumer group to it.
MessageBrokerExt
Schema-typed publishing and the consumer loop, on any MessageBroker.
OutboxStore
Where a Relay finds the staged messages. Every time is passed in from the relay’s WallClock; relay is the relay’s id, the owner of a lease.

Functions§

ack_on_success
A consume handler that runs handler over each delivery and settles it: ack when the handler succeeds, Nack::Requeue when it fails (so a message that keeps failing is dead-lettered after max_deliveries). The handler’s error is dropped; a handler that dies or is interrupted leaves the delivery to be redelivered.
consume
Runs handler over every delivery, at most concurrency (at least 1) at once, until the stream ends; the handler settles each delivery (see ack_on_success for 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; see RelayConfig::retry).
migrator
The crate’s schema (the outbox and inbox tables) as an id_effect_sql Migrator tracked in its own table MIGRATIONS_TABLE, so the version numbers never collide with the application’s migrations. Run it at startup (migrator().run_on(client) or migrator().layer()); it takes the migration advisory lock, so replicas starting together apply it once. The alternative is to copy migrations/0001_id_effect_messaging.{up,down}.sql into the application’s own migrations.
retry_delay
The delay before the attempt after attempt number attempt (from 1) failed with error, or None when schedule is done.