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
16 changes: 14 additions & 2 deletions crates/apache-pulsar-protocol/src/producer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ impl Producer {
let last = success.last_sequence_id.unwrap_or(-1);
s.last_published = last;
s.last_pushed = s.last_pushed.max(last);
s.next_sequence = (last + 1).max(0) as u64;
s.next_sequence = next_after(last);
}
// The messages that got into a batch got their deadlines then.
if let Some(timeout) = send_timeout {
Expand Down Expand Up @@ -570,6 +570,12 @@ impl Producer {
now,
);
}
// Credentials refused as a registered segment's producer registers again: retried, as the lost connection
// was, so that its messages wait, within their send timeout, for a provider with fresh ones. A first
// registration fails with them, as a lookup does.
RegisterError::Server { error: ServerError::AuthenticationError, .. } if s.registered_once => {
return self.retry_later(segment, now);
}
RegisterError::Server { error, message } if !retriable(error) => SendError::Server { error, message },
RegisterError::Server { error, message } => {
if s.registered_once || now < s.first_deadline {
Expand Down Expand Up @@ -867,7 +873,7 @@ impl Producer {
}
let info = self.layout.segment(id).expect("routed to a segment of the layout");
let (initial_last, initial_next) = match self.options.initial_sequence_id {
Some(initial) => (initial, (initial + 1).max(0) as u64),
Some(initial) => (initial, next_after(initial)),
None => (-1, 0),
};
let segment = Segment {
Expand Down Expand Up @@ -1285,6 +1291,12 @@ pub(crate) fn retriable(error: ServerError) -> bool {
)
}

/// The sequence id after `last`, the last one used: 0 after none (-1). A `u64`, as on the wire, so the id after
/// `i64::MAX` doesn't overflow.
fn next_after(last: i64) -> u64 {
u64::try_from(last).map_or(0, |last| last + 1)
}

fn retirement_delay(check: u32) -> Duration {
Duration::from_millis((100 * u64::from(check)).min(500))
}
Expand Down
7 changes: 7 additions & 0 deletions crates/apache-pulsar-testkit/tests/producer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,13 @@ fn sequence_ids_start_after_the_initial_or_the_brokers_last() {
let mut second = Harness::new(first.world, TOPIC, options());
second.send(None, "next");
assert_eq!(second.world.stored_in(TOPIC, 0).last().unwrap().sequence_id, 3);

// The id after the largest initial one: an id is a `u64` on the wire.
let mut opts = options();
opts.initial_sequence_id = Some(i64::MAX);
let mut h = Harness::new(world(1), TOPIC, opts);
h.send(None, "a");
assert_eq!(h.world.stored_in(TOPIC, 0)[0].sequence_id, 1 << 63);
}

#[test]
Expand Down
35 changes: 35 additions & 0 deletions crates/apache-pulsar-testkit/tests/producer_edges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,41 @@ fn registration_failures() {
assert_eq!(t.producer.oldest_outstanding(), Some(waits));
}

/// Credentials refused as a registered segment's producer registers again, after a lost connection: retried, as the
/// connection was, and its messages wait for a provider with fresh ones. A first registration fails with them.
#[test]
fn refused_credentials_are_retried_once_registered() {
let mut t = Test::new(ProducerAccessMode::Shared, one_segment());
t.send(keyless());
let generation = Test::connects(&t.actions())[0].1;
t.register(0, generation, 7);
t.receipt(0, generation, 0, Some(1));
t.producer.on_disconnected(0, generation, t.now);
t.actions();
let waiting = t.send(keyless());
t.advance(Duration::from_secs(1));
let generation = Test::connects(&t.actions())[0].1;
let refused = RegisterError::Server { error: ServerError::AuthenticationError, message: "expired".into() };
t.producer.on_register_failed(0, generation, refused.clone(), t.now);
assert!(Test::done(&t.actions()).is_empty(), "the message waits");
t.advance(Duration::from_secs(1));
let generation = Test::connects(&t.actions())[0].1;
t.register(0, generation, 8);
assert_eq!(Test::sent(&t.actions()), [(0, 1)]);
t.receipt(0, generation, 1, Some(2));
assert!(matches!(&Test::done(&t.actions())[..], [(send, Ok(_))] if *send == waiting));

// A first registration fails with them.
let mut t = Test::new(ProducerAccessMode::Shared, one_segment());
let refused_send = t.send(keyless());
let generation = Test::connects(&t.actions())[0].1;
t.producer.on_register_failed(0, generation, refused, t.now);
let done = Test::done(&t.actions());
assert!(
matches!(&done[..], [(send, Err(SendError::Server { error: ServerError::AuthenticationError, .. }))] if *send == refused_send)
);
}

#[test]
fn a_message_is_parked_at_most_ten_times() {
let mut t = Test::new(ProducerAccessMode::Shared, one_segment());
Expand Down
10 changes: 8 additions & 2 deletions crates/apache-pulsar/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ pub trait Authentication: Send + Sync + 'static {
fn method_name(&self) -> &str;

/// The data to send in `CONNECT`, and in answer to a refresh challenge. Called again for each.
///
/// A failure fails the connection with [`ErrorKind::Authentication`], whatever the error's own kind, which comes
/// as its source. The client doesn't retry it.
fn auth_data(&self) -> AuthFuture;

/// Answers a challenge of a multi-round exchange. Single-round methods answer with fresh data.
Expand Down Expand Up @@ -81,7 +84,8 @@ impl Token {
Self { source: TokenSource::Static(token.into().into()) }
}

/// A token fetched by `fetch` whenever a connection is made or the broker asks for a refresh.
/// A token fetched by `fetch` whenever a connection is made or the broker asks for a refresh. A failed fetch fails
/// the connection with [`ErrorKind::Authentication`], as [`Authentication::auth_data`] says.
pub fn from_fn<F, Fut>(fetch: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Expand Down Expand Up @@ -127,7 +131,9 @@ pub struct TlsAuthentication {
}

impl TlsAuthentication {
/// Reads the certificate chain and private key from PEM files.
/// Reads the certificate chain and private key from PEM files. Fails with
/// [`InvalidConfiguration`](ErrorKind::InvalidConfiguration) if one can't be read; the client's `build` checks
/// what they hold.
pub fn from_pem_files(chain: impl AsRef<std::path::Path>, key: impl AsRef<std::path::Path>) -> Result<Self> {
let read = |path: &std::path::Path| {
std::fs::read(path).map_err(|e| {
Expand Down
3 changes: 2 additions & 1 deletion crates/apache-pulsar/src/checkpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ impl Checkpoint {
self.0.to_bytes()
}

/// Restores a checkpoint from [`Checkpoint::to_bytes`], or from bytes the Java client wrote.
/// Restores a checkpoint from [`Checkpoint::to_bytes`], or from bytes the Java client wrote. Fails with
/// [`InvalidConfiguration`](ErrorKind::InvalidConfiguration) for bytes that aren't a checkpoint.
pub fn from_bytes(bytes: &[u8]) -> Result<Checkpoint> {
wire::Checkpoint::from_bytes(bytes)
.map(Checkpoint)
Expand Down
22 changes: 16 additions & 6 deletions crates/apache-pulsar/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ impl PulsarClient {
ClientBuilder::default()
}

/// Closes the client: every loop closes its connections, then its thread exits. Later operations fail with
/// [`ErrorKind::AlreadyClosed`]. Can be called again.
/// Closes the client: every loop closes its producers, its consumers and its connections, then its thread exits.
/// Later operations fail with [`ErrorKind::AlreadyClosed`]. Can be called again. Doesn't fail.
pub async fn close(&self) -> Result<()> {
if self.inner.closed.swap(true, Ordering::AcqRel) {
return Ok(());
Expand Down Expand Up @@ -222,7 +222,16 @@ impl LoopStarter {
}

impl ClientBuilder<ThreadSafe> {
/// Starts the event loops and creates the client.
/// Starts the event loops and creates the client. It connects to no broker yet: the first producer or consumer
/// does.
///
/// # Errors
///
/// - [`InvalidServiceUrl`](ErrorKind::InvalidServiceUrl): the service URL doesn't parse.
/// - [`InvalidConfiguration`](ErrorKind::InvalidConfiguration): the service URL is missing, a TLS file can't be
/// read or holds no valid certificate or key, TLS authentication is set without a `pulsar+ssl://` URL, or the
/// client has no event loop.
/// - [`Other`](ErrorKind::Other): an event loop's thread or runtime can't start.
pub async fn build(self) -> Result<PulsarClient> {
self.build_with(LoopStarter::SYSTEM).await
}
Expand All @@ -231,9 +240,10 @@ impl ClientBuilder<ThreadSafe> {
pub(crate) async fn build_with(self, starter: LoopStarter) -> Result<PulsarClient> {
let loops = self.event_loops;
let config = self.into_config()?;
let mut handles = Vec::with_capacity(loops);
let mut threads = Vec::with_capacity(loops);
let mut started = Vec::with_capacity(loops);
// Grown loop by loop: a count too large to start fails as the threads run out, with nothing reserved up front.
let mut handles = Vec::new();
let mut threads = Vec::new();
let mut started = Vec::new();
let config_for_client = config.clone();
for index in 0..loops {
let (sender, receiver) = mpsc::unbounded();
Expand Down
15 changes: 12 additions & 3 deletions crates/apache-pulsar/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ use crate::auth::Authentication;
use crate::error::{Error, ErrorKind, Result};
use crate::memory::MemoryLimit;

/// The longest duration the client waits. A longer one, as `Duration::MAX`, counts as a year: as good as forever, and
/// short enough for every timer and event loop to take (macOS's refuses a wait of 68 years or more).
pub(crate) const LONGEST: Duration = Duration::from_secs(365 * 24 * 60 * 60);

/// `duration`, at most [`LONGEST`].
pub(crate) fn bounded(duration: Duration) -> Duration {
duration.min(LONGEST)
}

/// Marks a builder for the thread-safe client.
#[derive(Debug, Clone, Copy)]
pub enum ThreadSafe {}
Expand Down Expand Up @@ -198,9 +207,9 @@ impl<Api> ClientBuilder<Api> {
service,
authentication: self.authentication,
tls,
connect_timeout: self.connect_timeout,
operation_timeout: self.operation_timeout,
keepalive_interval: self.keepalive_interval,
connect_timeout: bounded(self.connect_timeout),
operation_timeout: bounded(self.operation_timeout),
keepalive_interval: bounded(self.keepalive_interval),
memory: Arc::new(MemoryLimit::new(self.memory_limit)),
})
}
Expand Down
9 changes: 8 additions & 1 deletion crates/apache-pulsar/src/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,12 @@ fn not_connected<E>(_: E) -> Error {
Error::new(ErrorKind::NotConnected, "the connection closed")
}

/// The authentication provider couldn't supply credentials: an authentication failure, whatever the provider's own
/// error says, as Java V5 reports it.
fn provider_failed(error: Error) -> Error {
Error::with_source(ErrorKind::Authentication, format!("the authentication provider failed: {error}"), error)
}

/// Connects to `address` and completes the handshake within the connect timeout.
pub(crate) async fn open(address: BrokerAddress, config: &ClientConfig) -> Result<ConnHandle> {
let started = Instant::now();
Expand All @@ -189,7 +195,8 @@ pub(crate) async fn open(address: BrokerAddress, config: &ClientConfig) -> Resul
Some(auth) => {
let data = compio::time::timeout(timeout.saturating_sub(started.elapsed()), auth.auth_data())
.await
.map_err(|_| Error::new(ErrorKind::Timeout, "the authentication provider did not answer in time"))??;
.map_err(|_| Error::new(ErrorKind::Timeout, "the authentication provider did not answer in time"))?
.map_err(provider_failed)?;
(Some(auth.method_name().to_string()), Some(data))
}
None => (None, None),
Expand Down
44 changes: 35 additions & 9 deletions crates/apache-pulsar/src/consumer/checkpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use futures_util::Stream;

use super::stream::random_name;
use super::task::Machine;
use super::{Link, Message, Request, consumer_closed, invalid};
use super::{Link, Message, Request, consumer_closed, deadline, invalid};
use crate::checkpoint::Checkpoint;
use crate::client::{LoopSlot, PulsarClient};
use crate::config::{Blocking, Local, ThreadSafe};
Expand Down Expand Up @@ -166,6 +166,21 @@ impl<T: 'static> CheckpointConsumerBuilder<T, ThreadSafe> {

/// Creates the consumer, on the client's least loaded event loop, with a reader on every segment of the topic, or,
/// in a group, on every segment the topic's controller assigns it.
///
/// # Errors
///
/// - [`InvalidConfiguration`](crate::ErrorKind::InvalidConfiguration): the topic is missing or malformed, or the
/// schema is a key/value schema with a part of [`Schema::auto_consume`], which reads key/value messages whole.
/// - [`NotFound`](crate::ErrorKind::NotFound): the topic doesn't exist, and the broker doesn't create it.
/// - [`Authentication`](crate::ErrorKind::Authentication), [`Authorization`](crate::ErrorKind::Authorization) and
/// [`UnsupportedBroker`](crate::ErrorKind::UnsupportedBroker), from the brokers.
/// - [`IncompatibleSchema`](crate::ErrorKind::IncompatibleSchema): the schema isn't compatible with the topic's.
/// - [`Timeout`](crate::ErrorKind::Timeout): no layout, no answer from the controller, or a segment's reader not
/// subscribed, within the operation timeout; [`Connect`](crate::ErrorKind::Connect): the broker that serves the
/// topic can't be reached.
/// - [`Other`](crate::ErrorKind::Other): the controller refused a member of a group, as a 5.0.1 broker does for a
/// regular `persistent://` topic until the topic migrates.
/// - [`AlreadyClosed`](crate::ErrorKind::AlreadyClosed): the client is closed.
pub async fn create(mut self) -> Result<CheckpointConsumer<T>> {
let ApiClient::ThreadSafe(client) = &self.client else { unreachable!() };
let client = client.clone();
Expand All @@ -185,6 +200,10 @@ impl<T: 'static> CheckpointConsumerBuilder<T, Blocking> {

/// Creates the consumer, on the client's least loaded event loop, and blocks until every segment's reader is
/// subscribed.
///
/// # Errors
///
/// As the thread-safe API's `create`, above.
pub fn create(self) -> Result<crate::blocking::CheckpointConsumer<T>> {
let builder = CheckpointConsumerBuilder::<T, ThreadSafe> {
client: self.client,
Expand All @@ -203,6 +222,10 @@ impl<T: 'static> CheckpointConsumerBuilder<T, Local> {

/// Creates the consumer, on the local client's loop, with a reader on every segment of the topic, or, in a group,
/// on every segment the topic's controller assigns it.
///
/// # Errors
///
/// As the thread-safe API's `create`, above.
pub async fn create(mut self) -> Result<CheckpointConsumer<T, Local>> {
let ApiClient::Local(client) = &self.client else { unreachable!() };
let client = client.clone();
Expand Down Expand Up @@ -282,7 +305,8 @@ impl<T: 'static, Api> CheckpointConsumer<T, Api> {
self.shared.consumer_name.as_deref()
}

/// The next message. Fails only once the consumer is closed.
/// The next message. Fails only with [`AlreadyClosed`](crate::ErrorKind::AlreadyClosed), once the consumer is
/// closed.
///
/// Receives are answered in the order they are first polled. A receive dropped before it completes loses no
/// message: the next receive gets it, and checkpoints taken meanwhile don't count it as received.
Expand All @@ -291,19 +315,21 @@ impl<T: 'static, Api> CheckpointConsumer<T, Api> {
Ok(self.message(messages.pop().expect("a receive without a deadline gets its message")))
}

/// The next message, or `None` if none comes within `timeout`.
/// The next message, or `None` if none comes within `timeout`. Fails only with
/// [`AlreadyClosed`](crate::ErrorKind::AlreadyClosed), once the consumer is closed.
pub async fn receive_timeout(&self, timeout: Duration) -> Result<Option<Message<T>>> {
let messages = self.shared.link.receive(1, Some(Instant::now() + timeout)).await?;
let messages = self.shared.link.receive(1, Some(deadline(timeout))).await?;
Ok(messages.into_iter().next().map(|message| self.message(message)))
}

/// Up to `max` messages: as soon as there are `max`, or once `timeout` passes with those there are, none
/// included.
/// included. Fails with [`InvalidConfiguration`](crate::ErrorKind::InvalidConfiguration) if `max` is 0, and with
/// [`AlreadyClosed`](crate::ErrorKind::AlreadyClosed) once the consumer is closed.
pub async fn receive_batch(&self, max: usize, timeout: Duration) -> Result<Vec<Message<T>>> {
if max == 0 {
return Err(invalid("a batch receive takes at least one message"));
}
let messages = self.shared.link.receive(max, Some(Instant::now() + timeout)).await?;
let messages = self.shared.link.receive(max, Some(deadline(timeout))).await?;
Ok(messages.into_iter().map(|message| self.message(message)).collect())
}

Expand All @@ -315,16 +341,16 @@ impl<T: 'static, Api> CheckpointConsumer<T, Api> {
}

/// Where the application is: for each segment, the last message a receive returned, or where the segment's
/// reading starts. A consumer created at it reads on from there. It asks nothing of the brokers. Fails only once
/// the consumer is closed.
/// reading starts. A consumer created at it reads on from there. It asks nothing of the brokers. Fails only with
/// [`AlreadyClosed`](crate::ErrorKind::AlreadyClosed), once the consumer is closed.
pub async fn checkpoint(&self) -> Result<Checkpoint> {
let (reply, checkpoint) = oneshot::channel();
self.shared.link.requests.unbounded_send(Request::Checkpoint { reply }).map_err(consumer_closed)?;
checkpoint.await.map(Checkpoint).map_err(consumer_closed)
}

/// Closes the consumer: closes every segment's reader, and leaves the group. The receives waiting fail with
/// [`ErrorKind::AlreadyClosed`](crate::ErrorKind::AlreadyClosed). Can be called again.
/// [`ErrorKind::AlreadyClosed`](crate::ErrorKind::AlreadyClosed). Can be called again. Doesn't fail.
pub async fn close(&self) -> Result<()> {
self.shared.link.close().await
}
Expand Down
Loading
Loading