Expand description
Apache Pulsar client driver for Rust.
Public façade for the magnetar workspace. Re-exports the sans-io core
(magnetar_proto) plus the selected runtime engine, and provides an
ergonomic PulsarClient entry point that wires the protocol layer to
the tokio engine by default.
use magnetar::{OutgoingMessage, PulsarClient};
let client = PulsarClient::builder()
.service_url("pulsar://localhost:6650")
.build()
.await?;
let producer = client.producer("persistent://public/default/orders").create().await?;
producer
.send(OutgoingMessage::with_payload(b"hello".as_slice()).into())
.await?;
let consumer = client
.consumer("persistent://public/default/orders")
.subscription("worker")
.subscribe()
.await?;
let msg = consumer.receive().await?;
consumer.ack(msg.message_id).await?;§Feature flags
tokio(default): pull in the tokio engine.moonpool: pull in the moonpool engine.admin: re-export [magnetar_admin] under [admin] for the REST admin client.auth-oauth2,auth-sasl,auth-athenz: pluggable auth providers.encryption: PIP-4 end-to-end encryption.opentelemetry(default off): inject/extract W3Ctraceparent/tracestateinto message properties (ADR-0053).
Re-exports§
pub use magnetar_proto as proto;pub use magnetar_runtime_tokio as runtime_tokio;
Structs§
- Backoff
- Truncated-exponential backoff with deterministic jitter.
- Client
Builder - Builder for
PulsarClient. - Connection
Config - Connection configuration.
- Consumer
Builder - Builder for a consumer.
- Consumer
Event Listener Handle - Owns the background poller task driving a
ConsumerEventListener. Structurally identical toMessageListenerHandle— dropping the handle aborts the poller;Self::closeawaits a clean stop. - Consumer
Handle - A consumer id, allocated by the
Connectionwhen a subscription opens. - Incoming
Message - Convenience alias for an incoming message handed back to the caller.
- Java
String Hash Hasher - Pick the partition with
java_string_hash(JavaString.hashCode()semantics), thenhash % partitions. Falls back to round-robin when no key is set. - Memory
Limit - Java parity: configured global publish memory budget. Stored verbatim on
crate::ClientBuilderand exposed to consumers viaPulsarClient::memory_limit. - Message
Builder - Producer-bound counterpart to
OutgoingMessage. Mirrors Java’sTypedMessageBuilder— the producer is captured at construction so the terminalsend()has no extra argument. - Message
Id - A logical message identifier (ledger / entry / batch / partition).
- Message
Listener Handle - Owns the background poller task driving a push-mode consumer. Mirrors the
lifetime semantics of
crate::TableView’s drain task: dropping the handle aborts the poller;Self::closeawaits a clean stop. - Multi
Topics Consumer - Multi-topics consumer. Each contained consumer subscribes to one topic;
receive()returns the next message across the whole set. - Multi
Topics Consumer Builder - Builder for
MultiTopicsConsumer. Mirrorsorg.apache.pulsar.client.api.ConsumerBuilderat the multi-topic layer. - Multi
Topics Message - A message yielded by
MultiTopicsConsumer::receive, carrying the topic it came from. - Murmur3
Hash Hasher - Pick the partition by hashing the message’s UTF-8-encoded partition key with
murmur3_32_hash(Apache PulsarMurmur3_32Hash, seed0), thenhash % partitions. Falls back to round-robin viaOutgoingMessage::keybeingNoneor empty. - NoEncryption
- Zero-sized stub for any future engine that genuinely cannot wire real
encryption. Both shipped engines (
TokioEngineand [MoonpoolEngine]) now resolve theirMessageEncryptorApi::Encryptor/MessageDecryptorApi::Decryptorto their own runtime’sArc<dyn …MessageEncryptor>/…MessageDecryptor, soNoEncryptionis no longer used by either. It is retained as the documented opt-out type an engine can hand to the façade to signal “encryption not supported on this engine” — the builders’ generic.create()/.subscribe()paths ignore the encryptor field regardless. - Operation
Retry Config - Configuration for lookup, partition-metadata, producer-open, and subscribe retries.
- Outgoing
Message - Convenience alias for outgoing application messages.
- Partitioned
Consumer Builder - Builder for a partition-aware consumer.
- Partitioned
Message Builder - Partitioned-producer-bound counterpart to
crate::MessageBuilder. Same chained setters; the terminal.send().awaitresolves the partition and dispatches. - Partitioned
Producer - Partition-aware producer.
- Partitioned
Producer Builder - Builder for
PartitionedProducer. Mirrors Java’sProducerBuilderat the partitioned layer. - Pattern
Consumer - Regex-pattern consumer. Holds one consumer per matching topic and reconciles the set
against PIP-145 deltas on
update(). - Pattern
Consumer Builder - Builder for
PatternConsumer. Mirrors Java’sPulsarClient#newConsumer().topicsPattern(...). - Pattern
Message - A message yielded by
PatternConsumer::receive, carrying the topic it came from. - Producer
Builder - Builder for a producer.
- Producer
Handle - A producer id, allocated by the
Connectionwhen a producer opens. - Pulsar
Client - High-level Pulsar client, generic over the runtime
Engine. - Reader
- Reader handle — a non-durable consumer that reads from a topic without persisting an acknowledgement cursor. Use a reader for: log replay, message inspection, batch ETL, or anywhere you want at-most-once delivery semantics that the broker doesn’t track.
- Reader
Builder - Builder for a
Reader. - Reconcile
Report - Outcome of a single
PatternConsumer::updatereconciliation cycle. - Request
Id - A protocol-level request id, monotonically increasing per connection.
- Sequence
Id - A monotonic per-producer publish sequence id.
- Supervisor
Config - Configuration for the auto-reconnect supervisor.
- Table
View - Compacted-topic key/value view.
- Table
View Builder - Builder for a
TableView. Mirrorsorg.apache.pulsar.client.api.TableViewBuilder. - Tokio
Engine - Zero-sized marker for the tokio production engine. Default
Eoncrate::PulsarClient<E>. - Topic
List Change - PIP-145
TopicListChangeddelta surfaced throughBrokerMetadataApi::poll_topic_list_change. Façade-side analogue of the per-runtimeTopicListChangestructs — each runtime impl converts its own delta into this engine-agnostic shape so generic surfaces (PatternConsumer<C>::update) can reconcile without touching runtime-specific types. - Transaction
- A live Pulsar transaction token. Holds the broker-assigned
magnetar_proto::TxnId. - Typed
Consumer - A schema-aware consumer. Wraps a consumer and decodes every received payload with the configured schema before returning to the caller.
- Typed
Consumer Builder - Builder for a
TypedConsumer. - Typed
Message - A decoded message yielded by
TypedConsumer::receive. - Typed
Message Builder - Schema-aware counterpart to
crate::MessageBuilder. Captures a&TypedProducerand lets callers chain Java-style:producer.new_message().key(..).value(&typed).send(). The schema runs on.send(&value)so we don’t pay the encode cost on values that get dropped mid-build (a logic error caught by the borrow checker, but cheap to be defensive about). - Typed
Producer - A schema-aware producer. Wraps a producer and applies the configured schema to every outbound value.
- Typed
Producer Builder - Builder for a
TypedProducer. The schema is required; the topic comes from the parentPulsarClient::typed_producerentry point. - Typed
Table View - Schema-aware
TableView. Wraps a rawTableViewplus anArc<S>and exposes typed accessors that decode the payload on demand. Mirrors Java’spulsar.tableView(Schema)shape. - Typed
Table View Builder - Builder for a
TypedTableView. Mirrors Java’s schema-awarepulsar.tableViewBuilder(Schema)shape.
Enums§
- Connection
Event - A semantic event surfaced by the state machine.
- Consumer
Event - Event surfaced by a push-delivery
ConsumerEventListener(issue #348). Mirrors JavaConsumerEventListener#becameActive(Consumer, int)/becameInactive(Consumer, int)— the Failover subscription active-consumer transitions. magnetar drops thepartitionIdargument (single-topic consumers only; a partitioned consumer’s per-partition event listener is attached per child, so the topic/partition is already implicit in which consumer’s listener fired). - Memory
Limit Policy - Java parity:
org.apache.pulsar.client.api.MemoryLimitPolicy. - Message
Routing Mode - How a
PartitionedProducerpicks the partition for an outgoing message. - OpOutcome
- Result of consuming a pending op via
Connection::take_outcome. - Protocol
Error - Errors that the
Connectionstate machine can surface. - Pulsar
Error - Top-level errors surfaced by the façade.
- Seek
Target - Per-topic seek target supplied by the closure passed to
crate::MultiTopicsConsumer::seek_per_partition(and the equivalent oncrate::PartitionedConsumer). Mirrors Java’sConsumer#seek(Function<String, Object>), where the function returns either aMessageIdor aLongpublish-time millis-since-epoch. - TxnState
- Result of committing or aborting a
Transaction. Re-exported frommagnetar-proto. Lifecycle of a transaction tracked byTxnClient.
Traits§
- Auth
Provider - Synchronous, sans-io authentication provider.
- Broker
Metadata Api - Engine-side broker metadata lookups used by
crate::PartitionedConsumerBuilderandcrate::PatternConsumerBuilder(alongside other partition-aware surfaces). Each runtime implements this on its concreteClienttype. - Consumer
Api - Pulsar consumer wire surface — implemented by each runtime on its
Consumertype. Foundational alongsideProducerApiper ADR-0026 §D1. - Consumer
Interceptor - Java
ConsumerInterceptorSPI. Plug receive-side hooks behindConsumer::receiveto inspect / mutate incoming messages and observe ack outcomes. Mirrorsorg.apache.pulsar.client.api.interceptor.ConsumerInterceptor: - Create
Producer Api - Engine-side producer-creation surface used by
ProducerBuilder<E>andPartitionedProducer<E>. Same shape asSubscribeApifor the producer side. - Engine
- Marker trait labelling a runtime engine. Implementations select the
concrete storage type (
Self::ClientState) that backs the engine’s branch ofcrate::PulsarClient<E>. - Message
Decryptor Api - Engine-side message-decryptor selection. Mirror of
MessageEncryptorApifor the consume path. Implemented on the engine marker. - Message
Encryptor Api - Engine-side message-encryptor selection. Each engine declares its own
concrete encryptor type; the façade’s
ProducerBuilderstoresOption<E::Encryptor>(engine-typed) instead of anArc<dyn magnetar_runtime_tokio::MessageEncryptor>(tokio-locked). - Message
Router - Plug a user-provided routing function in front of
MessageRoutingMode. Mirrors Java’sMessageRouterSPI — when set on the builder, the function decides the partition for every outgoing message; the configuredMessageRoutingModeis ignored. Use this for affinity routing rules (geo, tenant, schema-keyed) that don’t fit the partition-key-hash mould. - Producer
Api - Pulsar producer wire surface — implemented by each runtime on its
Producertype. Foundational for the seven dependent façade lifts (Reader,TypedSchemas,MultiTopicsConsumer,PartitionedProducer,PartitionedConsumer,PatternConsumer,TableView) per ADR-0026 §D1. - Producer
Ext - Extension trait that gives
magnetar_runtime_tokio::Producerthe Java-symmetricproducer.new_message().key(..).value(..).send().awaitentry point. - Producer
Interceptor - Java
ProducerInterceptorSPI. Plug pipeline hooks in front ofProducer::sendto inspect, mutate, or react to outgoing messages. Mirrors the Javaorg.apache.pulsar.client.api.interceptor.ProducerInterceptorinterface —eligiblegates whether the interceptor runs for a given message,before_sendruns first (mutating theOutgoingMessage), andon_send_acknowledgementfires after the broker acks the publish (or the send errors out). - Subscribe
Api - Engine-side subscribe surface used by
ConsumerBuilder<E>and the other consumer-spawning façade surfaces (MultiTopicsConsumer,PatternConsumer,Reader). Each runtime implements this on its concreteClienttype with the runtime-specificConsumertype surfaced via the associatedConsumertype. - Transaction
Api - Pulsar transactions (PIP-31) — implemented by each runtime on its
Clienttype. Phase 1 of the D1 lift train. - Wrapper
Receiver - A wrapper consumer’s
receive()surface, abstracted for the wrapper poller.
Functions§
- ack_
cumulative_ with_ interceptors - Cumulative ack variant of
ack_with_interceptors. Notifies viaon_acknowledge_cumulativeinstead ofon_acknowledge. - ack_
with_ interceptors - Ack via
consumerand notify every interceptor of the outcome. Mirrors Java’s post-ack callback chain. Returns whatever the runtime ack returned, mapped into aPulsarError. - java_
string_ hash - Bit-for-bit port of
String.hashCode() & Integer.MAX_VALUE. Iterates over UTF-16 code units (matching Java’schar) so non-BMP code points hash identically to the JDK. ASCII strings short-circuit through the byte path. - murmur3_
32_ hash - Bit-for-bit port of Apache Pulsar’s
Murmur3_32Hash.makeHash(byte[])(Murmur3_32Hash.java). Used byMurmur3HashHasherso cross-language consumers (Java, C++, Go) see identical routing for the same key. - receive_
with_ interceptors - Receive the next message via
consumer, running everyConsumerInterceptorininterceptorsagainst the payload before it is returned. Mirrors Java’s interceptor chain on the receive path — every interceptor’sbefore_consumeruns in order on a single progressively-mutated message. - send_
with_ interceptors - Send
msgthroughproducer, running every eligibleProducerInterceptorininterceptorsin order. Mirrors Java’s interceptor-chain semantics:eligibleis evaluated against the original message,before_sendruns in order on a single message the chain progressively mutates, andon_send_acknowledgementfires on every eligible interceptor regardless of whether the broker accepted the publish. - spawn_
consumer_ event_ listener - Attach a
ConsumerEventListenerto an already-subscribedconsumer, returning the owningConsumerEventListenerHandle. The poller drivesconsumer.next_active_change()in a loop and invokeslisteneronce per transition —ConsumerEvent::BecameActiveforOk(true),ConsumerEvent::BecameInactiveforOk(false)— stopping cleanly the first time the future resolvesErr(closed / terminally-disconnected consumer). - spawn_
message_ listener - Attach a push-delivery listener to an already-subscribed
consumer, returning the owningMessageListenerHandle. The poller drivesconsumer.receive()and invokeslisteneronce per message, sequentially and in order, with no auto-ack — the callback acks explicitly. - spawn_
wrapper_ message_ listener - Spawn a push-delivery poller over a wrapper consumer, returning the owning
MessageListenerHandle. The poller drivesreceiver.wrapper_receive()and invokeslistener(topic, &msg)once per message, sequentially and in order, with no auto-ack — the callback acks explicitly via the wrapper’s topic-routed ack (ack(topic, id)).
Type Aliases§
- Consumer
Event Listener - Callback fired for every Failover active/standby transition observed by a
push-mode consumer event listener. Mirrors
MessageListener’s shape — a synchronous callback, invoked sequentially from the poller task. Mirrors JavaConsumerEventListener#becameActive/#becameInactive, collapsed into one callback takingConsumerEvent(no consumer/partition argument — hold a clone of your consumer in the closure if you need to act on it, the same conventionMessageListeneruses). - Message
Listener - Callback fired for every message delivered to a push-mode consumer.
- Open
Producer Fut - Helper alias:
CreateProducerApi::open_producerfuture return type. - Partitioned
Consumer - Partition-aware consumer. Effectively a
crate::MultiTopicsConsumerwhose topic list was auto-discovered from a partitioned topic. - Receive
Batch Fut - Helper alias:
ConsumerApi::receive_batch/receive_batch_with_bytes_capfuture return type. - Receive
OptFut - Helper alias:
ConsumerApi::receive_with_timeoutfuture return type. - Subscribe
Fut - Helper alias:
SubscribeApi::subscribefuture return type. - Table
View Listener - Callback fired for every mutation applied to the table view.
- Typed
Message Listener - Schema-aware push-delivery callback (Java
ConsumerBuilder<T>#messageListener). Fired once per delivered message with the decodedTypedMessage. Like the rawcrate::MessageListener, it runs inside the poller task — sequentially, in order — and must ack explicitly (the poller never auto-acks). Register it viaTypedConsumerBuilder::message_listenerand subscribe viaTypedConsumerBuilder::subscribe_with_listener. - Watch
Topic List Fut - Helper alias:
BrokerMetadataApi::watch_topic_listfuture return type. - Wrapper
Message Listener - Callback fired for every message delivered to a push-mode wrapper
consumer (
crate::MultiTopicsConsumer,crate::PartitionedConsumer,crate::PatternConsumer).