diff --git a/Cargo.lock b/Cargo.lock index a189096..34628af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -155,6 +155,7 @@ dependencies = [ "buffa-types", "bytes", "compio", + "futures", "futures-channel", "futures-executor", "futures-util", @@ -169,6 +170,7 @@ dependencies = [ "serde_json", "testcontainers", "thiserror", + "tokio", "tracing", ] diff --git a/README.md b/README.md index bcbaadd..c2829bc 100644 --- a/README.md +++ b/README.md @@ -53,12 +53,39 @@ client.close().await?; | Path | What it is | |---|---| | `crates/apache-pulsar` | The client: producers, Queue, Stream and Checkpoint consumers, layout watches, connections, the pool, lookup, authentication, TLS, the memory limit, and the thread-safe, local and blocking APIs. | +| `crates/apache-pulsar/examples` | Runnable examples: a producer, the Queue, Stream and Checkpoint consumers, the local and blocking APIs, schemas, TLS and token authentication, and pipelined sends. | | `crates/apache-pulsar-protocol` | The sans-IO protocol core: generated protobuf code, framing, the connection, producer and consumer state machines, entry decoding, layouts and routing, message ids. Internal; not a stable API. | | `crates/apache-pulsar-testkit` | The simulated broker and cluster, and the deterministic tests of the protocol state machines. Not published. | | `checks/` | Milestone 0 checks: compio behavior, and the handshake against a real broker. | | `tools/java-vectors` | Generates test vectors from the Java client. | | `xtask` | Repository tasks: protobuf code generation. | +## Examples + +`crates/apache-pulsar/examples` has one example for each part of the API. They run against a broker on this machine, +or the one `PULSAR_URL` names. Start a standalone broker that advertises `localhost`, and once it is up, which takes +a few seconds, run one: + +```bash +docker run -d --rm --name pulsar -p 6650:6650 -p 8080:8080 apachepulsar/pulsar:5.0.1 bash -c "echo advertisedAddress=localhost >> conf/standalone.conf && exec bin/pulsar standalone" +``` + +```bash +cargo run --example producer +``` + +| Example | What it shows | +|---|---| +| `producer` | Keyed messages with properties, a flush and a close, on the default API from a Tokio runtime. | +| `queue_consumer` | A Shared subscription on every segment: each message acknowledged, one negatively and delivered again. | +| `stream_consumer` | Segments the controller assigns, each key in order, and cumulative acknowledgments. | +| `checkpoint_consumer` | No subscription: a checkpoint kept in a file, and a second run that reads on from it. | +| `local` | The local API: a client per thread, each on its own compio event loop. | +| `blocking` | The blocking API, without an async runtime. | +| `schemas` | JSON, Avro and key/value schemas for a struct, and generic records. | +| `authentication` | TLS with a trusted CA, and a token, a token file or a client certificate. | +| `pipelining` | Many sends in flight, in order, with `buffered`, `FuturesOrdered` and `join_all`. | + ## Building and testing ```bash diff --git a/crates/apache-pulsar/Cargo.toml b/crates/apache-pulsar/Cargo.toml index cf11941..641c98d 100644 --- a/crates/apache-pulsar/Cargo.toml +++ b/crates/apache-pulsar/Cargo.toml @@ -59,6 +59,8 @@ apache-avro = { version = "0.23", features = ["derive"] } apache-pulsar-testkit = { path = "../apache-pulsar-testkit" } base64 = "0.22" buffa-types = { version = "=0.9.2", features = ["reflect"] } +# The examples' combinators, and the runtime the default API's examples run on: its futures run on any executor. +futures = "0.3" jsonwebtoken = { version = "12", default-features = false, features = ["rust_crypto"] } libtest-mimic = "0.8" prost-types = "0.14" @@ -66,6 +68,7 @@ rcgen = "0.14" ring = "0.17" serde = { version = "1", features = ["derive"] } testcontainers = { version = "0.28", features = ["blocking", "watchdog"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } # The compression codecs, each behind a feature, all on by default (docs/3-protocol.md ยง6). ZSTD binds the C # `libzstd`, so building it needs a C compiler. @@ -83,6 +86,11 @@ avro = ["dep:apache-avro", "dep:serde"] protobuf = ["dep:buffa-descriptor", "dep:base64"] prost = ["protobuf", "dep:prost"] +# The JSON and Avro schemas, and the struct deriving apache-avro's `AvroSchema`. +[[example]] +name = "schemas" +required-features = ["json", "avro"] + # Against a broker and a proxy in Docker. Not run by `cargo test`: `cargo test -p apache-pulsar --test integration`. [[test]] name = "integration" diff --git a/crates/apache-pulsar/examples/authentication.rs b/crates/apache-pulsar/examples/authentication.rs new file mode 100644 index 0000000..6c86a75 --- /dev/null +++ b/crates/apache-pulsar/examples/authentication.rs @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! TLS and authentication: a `pulsar+ssl://` service URL, the CA certificate to trust, and a token, or a client +//! certificate for mutual TLS. It sends a message and reads it back. +//! +//! PULSAR_URL=pulsar+ssl://broker.example.com:6651 PULSAR_TLS_TRUST_CERTS=ca.cert.pem \ +//! PULSAR_TOKEN_FILE=client.token cargo run --example authentication +//! +//! `PULSAR_TOKEN` gives the token itself, and `PULSAR_TLS_CERT` and `PULSAR_TLS_KEY`, PEM files, a client certificate +//! instead of a token. Without `PULSAR_TLS_TRUST_CERTS`, the platform's roots are trusted. The first argument sets +//! another topic. + +use std::error::Error; +use std::time::Duration; + +use apache_pulsar::{ErrorKind, PulsarClient, Schema, SubscriptionInitialPosition, TlsAuthentication, Token}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let url = std::env::var("PULSAR_URL").unwrap_or_else(|_| "pulsar+ssl://localhost:6651".into()); + let topic = std::env::args().nth(1).unwrap_or_else(|| "topic://public/default/secured".into()); + + let mut builder = PulsarClient::builder().service_url(url); + if let Ok(ca) = std::env::var("PULSAR_TLS_TRUST_CERTS") { + // The CA that signed the broker's certificate, which must name the broker's host. + builder = builder.tls_trust_certs_file(ca); + } + if let (Ok(cert), Ok(key)) = (std::env::var("PULSAR_TLS_CERT"), std::env::var("PULSAR_TLS_KEY")) { + // Mutual TLS: the client's certificate is the credential, and its common name the role. + builder = builder.authentication(TlsAuthentication::from_pem_files(cert, key)?); + } else if let Ok(file) = std::env::var("PULSAR_TOKEN_FILE") { + // Read for each new connection, and when the broker asks for fresh credentials: a token renewed in the file is + // taken without a restart. The provider runs on the client's event loop, not on Tokio, so it reads the file + // with the standard library. + builder = builder.authentication(Token::from_fn(move || { + let read = std::fs::read_to_string(&file); + let file = file.clone(); + async move { + read.map(|token| token.trim().to_string()).map_err(|error| { + apache_pulsar::Error::new(ErrorKind::Authentication, format!("can't read {file}: {error}")) + }) + } + })); + } else if let Ok(token) = std::env::var("PULSAR_TOKEN") { + builder = builder.authentication(Token::new(token)); + } + let client = builder.build().await?; + + let consumer = client + .new_queue_consumer(Schema::string()) + .topic(&topic) + .subscription_name("secured") + .subscription_initial_position(SubscriptionInitialPosition::Latest) + .subscribe() + .await?; + let producer = client.new_producer(Schema::string()).topic(&topic).create().await?; + let id = producer.send("over TLS".into()).await?; + println!("stored a message as {id}"); + if let Some(message) = consumer.receive_timeout(Duration::from_secs(10)).await? { + println!("read it back: {}", message.value()?); + consumer.acknowledge(message.id()).await?; + } + + producer.close().await?; + consumer.close().await?; + client.close().await?; + Ok(()) +} diff --git a/crates/apache-pulsar/examples/blocking.rs b/crates/apache-pulsar/examples/blocking.rs new file mode 100644 index 0000000..00034bb --- /dev/null +++ b/crates/apache-pulsar/examples/blocking.rs @@ -0,0 +1,54 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The blocking API, for code without an async runtime: each call blocks its thread until the operation completes. +//! Don't call it from an async task, which would block the task's executor too. +//! +//! `cargo run --example blocking`. `PULSAR_URL` sets another service URL, and the first argument another topic. + +use std::error::Error; +use std::time::Duration; + +use apache_pulsar::{Schema, blocking}; + +fn main() -> Result<(), Box> { + let url = std::env::var("PULSAR_URL").unwrap_or_else(|_| "pulsar://localhost:6650".into()); + let topic = std::env::args().nth(1).unwrap_or_else(|| "topic://public/default/blocking".into()); + + let client = blocking::PulsarClient::builder().service_url(url).build()?; + // Subscribed first: a new subscription starts at the latest message by default. + let consumer = + client.new_queue_consumer(Schema::string()).topic(&topic).subscription_name("blocking").subscribe()?; + let producer = client.new_producer(Schema::string()).topic(&topic).create()?; + + for i in 0..10 { + // A blocking send sends its batch at once, as Java's does, so a loop of them doesn't wait out the batching + // delay for each. + let id = producer.new_message().key(format!("key-{}", i % 3)).value(format!("message {i}")).send()?; + println!("stored message {i} as {id}"); + } + + while let Some(message) = consumer.receive_timeout(Duration::from_secs(5))? { + println!("{:?}: {}", message.key(), message.value()?); + consumer.acknowledge(message.id())?; + } + + producer.close()?; + consumer.close()?; + client.close()?; + Ok(()) +} diff --git a/crates/apache-pulsar/examples/checkpoint_consumer.rs b/crates/apache-pulsar/examples/checkpoint_consumer.rs new file mode 100644 index 0000000..dcdf293 --- /dev/null +++ b/crates/apache-pulsar/examples/checkpoint_consumer.rs @@ -0,0 +1,62 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! A Checkpoint consumer: no subscription on the brokers. The application keeps where it is as a `Checkpoint`, here +//! in a file, and a consumer created at it reads on from there: run it twice, and the second run reads only what +//! came after the first. +//! +//! `cargo run --example checkpoint_consumer`, with `cargo run --example producer` before. It stops once no message +//! comes for 5 s. `PULSAR_URL` sets another service URL, the first argument another topic, and the second the file. + +use std::error::Error; +use std::time::Duration; + +use apache_pulsar::{Checkpoint, PulsarClient, Schema}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let url = std::env::var("PULSAR_URL").unwrap_or_else(|_| "pulsar://localhost:6650".into()); + let mut args = std::env::args().skip(1); + let topic = args.next().unwrap_or_else(|| "topic://public/default/orders".into()); + let file = args.next().map_or_else(|| std::env::temp_dir().join("apache-pulsar-orders.checkpoint"), Into::into); + + // Where the last run stopped, or the topic's start. Java's client reads and writes the same bytes. + let start = match std::fs::read(&file) { + Ok(bytes) => Checkpoint::from_bytes(&bytes)?, + Err(_) => Checkpoint::earliest(), + }; + println!("starting at {start:?}"); + + let client = PulsarClient::builder().service_url(url).build().await?; + let consumer = + client.new_checkpoint_consumer(Schema::string()).topic(&topic).start_position(start).create().await?; + + // A key's messages come in the order they were published, across the topic's splits and merges. + while let Some(message) = consumer.receive_timeout(Duration::from_secs(5)).await? { + println!("{:?}: {}", message.key(), message.value()?); + } + + // For each segment, the last message a receive returned: a consumer created at it reads on after them. It asks + // nothing of the brokers. + let checkpoint = consumer.checkpoint().await?; + std::fs::write(&file, checkpoint.to_bytes())?; + println!("saved {checkpoint:?} to {}", file.display()); + + consumer.close().await?; + client.close().await?; + Ok(()) +} diff --git a/crates/apache-pulsar/examples/local.rs b/crates/apache-pulsar/examples/local.rs new file mode 100644 index 0000000..ce7ceb4 --- /dev/null +++ b/crates/apache-pulsar/examples/local.rs @@ -0,0 +1,105 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The local API, for applications that run their own compio event loops, one per core: each thread has a client of +//! its own, whose producers and consumers run on that thread's loop, so no operation hops to another thread. Here two +//! threads produce, and a third reads what they stored. +//! +//! `cargo run --example local`. `PULSAR_URL` sets another service URL, and the first argument another topic. + +use std::error::Error; +use std::time::Duration; + +use apache_pulsar::{Schema, SubscriptionInitialPosition, local}; + +const THREADS: usize = 2; +const MESSAGES: usize = 10; + +fn main() -> Result<(), Box> { + let url = std::env::var("PULSAR_URL").unwrap_or_else(|_| "pulsar://localhost:6650".into()); + let topic = std::env::args().nth(1).unwrap_or_else(|| "topic://public/default/per-core".into()); + + // Subscribed before the producers start, so that it gets all they send. + let reader = { + let (url, topic) = (url.clone(), topic.clone()); + let (subscribed, is_subscribed) = std::sync::mpsc::channel(); + let reader = + std::thread::spawn(move || compio::runtime::Runtime::new()?.block_on(read(url, topic, subscribed))); + // A failed subscribe ends the thread, and drops the sender. + if is_subscribed.recv().is_err() { + return reader.join().expect("the reader panicked"); + } + reader + }; + + let producers: Vec<_> = (0..THREADS) + .map(|core| { + let (url, topic) = (url.clone(), topic.clone()); + std::thread::spawn(move || compio::runtime::Runtime::new()?.block_on(produce(core, url, topic))) + }) + .collect(); + for producer in producers { + producer.join().expect("a producer panicked")?; + } + reader.join().expect("the reader panicked") +} + +/// Runs on its thread's loop: a client of the loop's own, and a producer on it. +async fn produce(core: usize, url: String, topic: String) -> Result<(), Box> { + let client = local::PulsarClient::builder().service_url(url).build().await?; + let producer = client.new_producer(Schema::string()).topic(topic).create().await?; + for i in 0..MESSAGES { + producer + .new_message() + .key(format!("core-{core}")) + .value(format!("message {i} from core {core}")) + .send() + .await?; + } + producer.close().await?; + client.close().await?; + Ok(()) +} + +/// Reads what the producers send, as a stream, until it has them all, or none comes for 10 s. +async fn read( + url: String, + topic: String, + subscribed: std::sync::mpsc::Sender<()>, +) -> Result<(), Box> { + use futures::StreamExt; + + let client = local::PulsarClient::builder().service_url(url).build().await?; + let consumer = client + .new_queue_consumer(Schema::string()) + .topic(topic) + .subscription_name("per-core-reader") + .subscription_initial_position(SubscriptionInitialPosition::Latest) + .subscribe() + .await?; + subscribed.send(())?; + let mut messages = std::pin::pin!(consumer.stream().take(THREADS * MESSAGES)); + loop { + let next = compio::time::timeout(Duration::from_secs(10), messages.next()).await; + let Ok(Some(message)) = next else { break }; + println!("{:?}: {}", message.key(), message.value()?); + consumer.acknowledge(message.id()).await?; + } + consumer.close().await?; + client.close().await?; + Ok(()) +} diff --git a/crates/apache-pulsar/examples/pipelining.rs b/crates/apache-pulsar/examples/pipelining.rs new file mode 100644 index 0000000..a6a571f --- /dev/null +++ b/crates/apache-pulsar/examples/pipelining.rs @@ -0,0 +1,75 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Pipelining sends: many messages in flight from one task, stored in the order they were sent. A send queues its +//! message when its future is first polled, so a combinator that polls the futures in order keeps their order: +//! `buffered`, `FuturesOrdered` and `join_all`. +//! +//! Two ways lose it. Spawning each send as a task of its own: the tasks start in any order. And a send future dropped +//! after its first poll, as when a timeout around it expires, doesn't recall its message, which may still be stored: +//! only its result is lost. The producer's send timeout bounds how long a message waits. +//! +//! `cargo run --example pipelining`. `PULSAR_URL` sets another service URL, and the first argument another topic. + +use std::error::Error; +use std::pin::pin; +use std::time::Instant; + +use apache_pulsar::{PulsarClient, Schema}; +use futures::future::join_all; +use futures::stream::{self, FuturesOrdered, StreamExt}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let url = std::env::var("PULSAR_URL").unwrap_or_else(|_| "pulsar://localhost:6650".into()); + let topic = std::env::args().nth(1).unwrap_or_else(|| "topic://public/default/pipelined".into()); + let client = PulsarClient::builder().service_url(url).build().await?; + let producer = client.new_producer(Schema::string()).topic(&topic).create().await?; + + // A continuous source: up to 1000 sends in flight, their results in send order, while `buffered` keeps taking + // messages from the source. + let started = Instant::now(); + let orders = (0..10_000).map(|i| (format!("user-{}", i % 100), format!("order {i}"))); + let sends = stream::iter(orders).map(|(user, order)| producer.new_message().key(user).value(order).send()); + let mut results = pin!(sends.buffered(1000)); + let mut stored = 0; + while let Some(result) = results.next().await { + result?; + stored += 1; + } + println!("buffered: {stored} messages stored in {:?}", started.elapsed()); + + // A known batch: `FuturesOrdered` polls its futures in the order they were pushed, and yields their results in + // that order. Nothing is sent until it is first polled. + let started = Instant::now(); + let mut batch: FuturesOrdered<_> = (0..1000).map(|i| producer.send(format!("batch {i}"))).collect(); + let mut last = None; + while let Some(result) = batch.next().await { + last = Some(result?); + } + println!("FuturesOrdered: 1000 messages in {:?}, the last stored as {}", started.elapsed(), last.unwrap()); + + // `join_all`: the same order, with every result at the end. + let started = Instant::now(); + let results = join_all((0..1000).map(|i| producer.send(format!("joined {i}")))).await; + let ids = results.into_iter().collect::, _>>()?; + println!("join_all: {} messages in {:?}", ids.len(), started.elapsed()); + + producer.close().await?; + client.close().await?; + Ok(()) +} diff --git a/crates/apache-pulsar/examples/producer.rs b/crates/apache-pulsar/examples/producer.rs new file mode 100644 index 0000000..73dd47e --- /dev/null +++ b/crates/apache-pulsar/examples/producer.rs @@ -0,0 +1,66 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! A producer on the default, thread-safe API, from a Tokio runtime: keyed messages with properties, a flush and a +//! close. +//! +//! Against a broker on this machine: `cargo run --example producer`. `PULSAR_URL` sets another service URL, and the +//! first argument another topic. + +use std::error::Error; +use std::time::Duration; + +use apache_pulsar::{PulsarClient, Schema}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let url = std::env::var("PULSAR_URL").unwrap_or_else(|_| "pulsar://localhost:6650".into()); + let topic = std::env::args().nth(1).unwrap_or_else(|| "topic://public/default/orders".into()); + + // One client per application: it is cheap to clone, and its futures run on any executor. + let client = PulsarClient::builder().service_url(url).build().await?; + let producer = client + .new_producer(Schema::string()) + .topic(&topic) + .producer_name("orders-writer") + .send_timeout(Duration::from_secs(30)) + .create() + .await?; + + // The messages of a key are stored in the order they are sent, across the topic's splits and merges. + for (i, user) in ["user-1", "user-2", "user-1"].into_iter().enumerate() { + let id = producer + .new_message() + .key(user) + .value(format!("order {i} of {user}")) + .property("source", "web") + .send() + .await?; + println!("stored order {i} of {user} as {id}"); + } + + // A message with only a value. Each send above waits for its message to be stored, and so for the batching + // delay too: pipelining.rs has many messages in flight at once. + let id = producer.send("no key".into()).await?; + println!("stored a message without a key as {id}"); + + // Every message sent before is stored once the flush completes; closing doesn't fail them. + producer.flush().await?; + producer.close().await?; + client.close().await?; + Ok(()) +} diff --git a/crates/apache-pulsar/examples/queue_consumer.rs b/crates/apache-pulsar/examples/queue_consumer.rs new file mode 100644 index 0000000..5f8397e --- /dev/null +++ b/crates/apache-pulsar/examples/queue_consumer.rs @@ -0,0 +1,63 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! A Queue consumer: a Shared subscription on every segment of the topic. The consumers of a subscription share its +//! messages, each one acknowledged on its own; a negative acknowledgment asks for a message again. +//! +//! `cargo run --example queue_consumer`, with `cargo run --example producer` before or meanwhile: it reads the +//! subscription from its start, and stops once no message comes for 10 s. `PULSAR_URL` sets another service URL, and +//! the first argument another topic. + +use std::error::Error; +use std::time::Duration; + +use apache_pulsar::{PulsarClient, Schema, SubscriptionInitialPosition}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let url = std::env::var("PULSAR_URL").unwrap_or_else(|_| "pulsar://localhost:6650".into()); + let topic = std::env::args().nth(1).unwrap_or_else(|| "topic://public/default/orders".into()); + + let client = PulsarClient::builder().service_url(url).build().await?; + let consumer = client + .new_queue_consumer(Schema::string()) + .topic(&topic) + .subscription_name("order-workers") + .subscription_initial_position(SubscriptionInitialPosition::Earliest) + .negative_ack_redelivery_delay(Duration::from_secs(1)) + .subscribe() + .await?; + + while let Some(message) = consumer.receive_timeout(Duration::from_secs(10)).await? { + let order = message.value()?; + // Work that fails now and may succeed later: the broker delivers the message again after the delay, with its + // redelivery count one higher. + if message.redelivery_count() == 0 && order.ends_with("user-2") { + println!("{order}: try again later"); + consumer.negative_acknowledge(message.id())?; + continue; + } + println!("{order} (key {:?}, redelivery count {})", message.key(), message.redelivery_count()); + // The acknowledgment goes out with the others of its group, within 100 ms by default. + consumer.acknowledge(message.id()).await?; + } + + // Sends the acknowledgments still waiting, and leaves the subscription's messages to its other consumers. + consumer.close().await?; + client.close().await?; + Ok(()) +} diff --git a/crates/apache-pulsar/examples/schemas.rs b/crates/apache-pulsar/examples/schemas.rs new file mode 100644 index 0000000..b43865f --- /dev/null +++ b/crates/apache-pulsar/examples/schemas.rs @@ -0,0 +1,103 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Schemas: a struct's values as JSON and as Avro, a key/value pair, and generic records, which a consumer reads with +//! the schema each message was written with. JSON and Avro take the crate's `json` and `avro` features, on by default; +//! the struct derives `serde`'s traits and apache-avro's `AvroSchema`. Java's client reads and writes the same messages. +//! +//! `cargo run --example schemas`. Each schema has a topic of its own, the first argument and a suffix: a topic keeps one +//! history of schemas, and refuses a schema of another type. `PULSAR_URL` sets another service URL. + +use std::error::Error; +use std::time::Duration; + +use apache_avro::AvroSchema; +use apache_pulsar::{KeyValue, PulsarClient, Schema, SubscriptionInitialPosition}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, AvroSchema)] +struct Order { + id: i64, + user: String, + total: f64, + /// A nullable field, as Java's reflection makes one of a class. + note: Option, +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + let url = std::env::var("PULSAR_URL").unwrap_or_else(|_| "pulsar://localhost:6650".into()); + let base = std::env::args().nth(1).unwrap_or_else(|| "topic://public/default/schemas".into()); + let client = PulsarClient::builder().service_url(url).build().await?; + let order = Order { id: 1, user: "user-42".into(), total: 99.5, note: None }; + + // JSON, through serde_json, with the record described to the broker in Avro, as Java's `Schema.json` does. + let json = round_trip(&client, Schema::::json(), &format!("{base}-json"), order.clone()).await?; + println!("JSON: {json:?}"); + + // Avro: each message is read with the schema version that wrote it, resolved to `Order`. + let avro = round_trip(&client, Schema::::avro(), &format!("{base}-avro"), order.clone()).await?; + println!("Avro: {avro:?}"); + + // A key and a value in the payload, each with its own schema: Java's inline key/value encoding. + let schema = Schema::key_value(Schema::string(), Schema::::avro()); + let pair = KeyValue { key: order.user.clone(), value: order }; + let pair = round_trip(&client, schema, &format!("{base}-key-value"), pair).await?; + println!("key/value: {} => {:?}", pair.key, pair.value); + + // Generic records: a consumer that doesn't know `Order` reads the Avro topic, fetching each version's schema. + let generic = client + .new_queue_consumer(Schema::auto_consume()) + .topic(format!("{base}-avro")) + .subscription_name("schemas-generic") + .subscription_initial_position(SubscriptionInitialPosition::Earliest) + .subscribe() + .await?; + while let Some(message) = generic.receive_timeout(Duration::from_secs(5)).await? { + let record = message.value()?; + let (schema, fields, user) = (record.schema_type(), record.fields(), record.field("user")); + println!("generic record, written with {schema:?}: fields {fields:?}, user {user:?}"); + generic.acknowledge(message.id()).await?; + } + generic.close().await?; + client.close().await?; + Ok(()) +} + +/// Sends `value` to `topic` with `schema`, and reads it back with the same schema. The consumer subscribes first, and +/// registers the schema on a new topic. +async fn round_trip( + client: &PulsarClient, + schema: Schema, + topic: &str, + value: T, +) -> Result> { + let consumer = client + .new_queue_consumer(schema.clone()) + .topic(topic) + .subscription_name("schemas") + .subscription_initial_position(SubscriptionInitialPosition::Earliest) + .subscribe() + .await?; + let producer = client.new_producer(schema).topic(topic).create().await?; + producer.send(value).await?; + let message = consumer.receive().await?; + consumer.acknowledge(message.id()).await?; + producer.close().await?; + consumer.close().await?; + Ok(message.value()?) +} diff --git a/crates/apache-pulsar/examples/stream_consumer.rs b/crates/apache-pulsar/examples/stream_consumer.rs new file mode 100644 index 0000000..a1923c3 --- /dev/null +++ b/crates/apache-pulsar/examples/stream_consumer.rs @@ -0,0 +1,70 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! A Stream consumer: the topic's controller spreads the topic's segments over the consumers of a subscription, so +//! that each key's messages go to one consumer, in order. One cumulative acknowledgment covers everything the +//! consumer received before, on every segment. +//! +//! `cargo run --example stream_consumer -- `; run it twice with two names, and the two share the +//! topic. It reads the subscription from its start, and stops once no message comes for 10 s. `PULSAR_URL` sets +//! another service URL. + +use std::error::Error; +use std::time::Duration; + +use apache_pulsar::{PulsarClient, Schema, SubscriptionInitialPosition}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let url = std::env::var("PULSAR_URL").unwrap_or_else(|_| "pulsar://localhost:6650".into()); + let mut args = std::env::args().skip(1); + let topic = args.next().unwrap_or_else(|| "topic://public/default/orders".into()); + let name = args.next().unwrap_or_else(|| "billing-1".into()); + + let client = PulsarClient::builder().service_url(url).build().await?; + let consumer = client + .new_stream_consumer(Schema::string()) + .topic(&topic) + .subscription_name("billing") + // The controller knows the consumer by its name: one that comes back under it soon gets its segments back. + .consumer_name(name) + .subscription_initial_position(SubscriptionInitialPosition::Earliest) + .subscribe() + .await?; + println!("subscribed as {}", consumer.consumer_name()); + + let mut last = None; + let mut unacknowledged = 0; + while let Some(message) = consumer.receive_timeout(Duration::from_secs(10)).await? { + println!("{:?}: {}", message.key(), message.value()?); + unacknowledged += 1; + // One acknowledgment for every 100 messages: each covers every message received before it. + if unacknowledged == 100 { + consumer.acknowledge_cumulative(message.id()).await?; + unacknowledged = 0; + } + last = Some(message); + } + if let Some(message) = last { + consumer.acknowledge_cumulative(message.id()).await?; + } + + // Leaves the controller's group, which hands this consumer's segments to the others at once. + consumer.close().await?; + client.close().await?; + Ok(()) +}