Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions crates/apache-pulsar/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,16 @@ 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"
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.
Expand All @@ -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"
Expand Down
83 changes: 83 additions & 0 deletions crates/apache-pulsar/examples/authentication.rs
Original file line number Diff line number Diff line change
@@ -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<dyn Error>> {
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(())
}
54 changes: 54 additions & 0 deletions crates/apache-pulsar/examples/blocking.rs
Original file line number Diff line number Diff line change
@@ -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<dyn Error>> {
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(())
}
62 changes: 62 additions & 0 deletions crates/apache-pulsar/examples/checkpoint_consumer.rs
Original file line number Diff line number Diff line change
@@ -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<dyn Error>> {
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(())
}
105 changes: 105 additions & 0 deletions crates/apache-pulsar/examples/local.rs
Original file line number Diff line number Diff line change
@@ -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<dyn Error + Send + Sync>> {
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<dyn Error + Send + Sync>> {
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<dyn Error + Send + Sync>> {
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(())
}
Loading
Loading