diff --git a/crates/apache-pulsar-protocol/src/producer.rs b/crates/apache-pulsar-protocol/src/producer.rs index 19fd024..f2498ab 100644 --- a/crates/apache-pulsar-protocol/src/producer.rs +++ b/crates/apache-pulsar-protocol/src/producer.rs @@ -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 { @@ -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 { @@ -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 { @@ -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)) } diff --git a/crates/apache-pulsar-testkit/tests/producer.rs b/crates/apache-pulsar-testkit/tests/producer.rs index c7f8887..2c116bb 100644 --- a/crates/apache-pulsar-testkit/tests/producer.rs +++ b/crates/apache-pulsar-testkit/tests/producer.rs @@ -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] diff --git a/crates/apache-pulsar-testkit/tests/producer_edges.rs b/crates/apache-pulsar-testkit/tests/producer_edges.rs index c3745b4..0c6d956 100644 --- a/crates/apache-pulsar-testkit/tests/producer_edges.rs +++ b/crates/apache-pulsar-testkit/tests/producer_edges.rs @@ -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()); diff --git a/crates/apache-pulsar/src/auth.rs b/crates/apache-pulsar/src/auth.rs index 12b8737..17bbee4 100644 --- a/crates/apache-pulsar/src/auth.rs +++ b/crates/apache-pulsar/src/auth.rs @@ -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. @@ -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(fetch: F) -> Self where F: Fn() -> Fut + Send + Sync + 'static, @@ -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, key: impl AsRef) -> Result { let read = |path: &std::path::Path| { std::fs::read(path).map_err(|e| { diff --git a/crates/apache-pulsar/src/checkpoint.rs b/crates/apache-pulsar/src/checkpoint.rs index 25bfae1..cf7f804 100644 --- a/crates/apache-pulsar/src/checkpoint.rs +++ b/crates/apache-pulsar/src/checkpoint.rs @@ -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 { wire::Checkpoint::from_bytes(bytes) .map(Checkpoint) diff --git a/crates/apache-pulsar/src/client.rs b/crates/apache-pulsar/src/client.rs index 7ebc5c3..bee2343 100644 --- a/crates/apache-pulsar/src/client.rs +++ b/crates/apache-pulsar/src/client.rs @@ -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(()); @@ -222,7 +222,16 @@ impl LoopStarter { } impl ClientBuilder { - /// 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 { self.build_with(LoopStarter::SYSTEM).await } @@ -231,9 +240,10 @@ impl ClientBuilder { pub(crate) async fn build_with(self, starter: LoopStarter) -> Result { 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(); diff --git a/crates/apache-pulsar/src/config.rs b/crates/apache-pulsar/src/config.rs index 83b1232..0196b46 100644 --- a/crates/apache-pulsar/src/config.rs +++ b/crates/apache-pulsar/src/config.rs @@ -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 {} @@ -198,9 +207,9 @@ impl ClientBuilder { 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)), }) } diff --git a/crates/apache-pulsar/src/conn.rs b/crates/apache-pulsar/src/conn.rs index 613822f..e577f3b 100644 --- a/crates/apache-pulsar/src/conn.rs +++ b/crates/apache-pulsar/src/conn.rs @@ -175,6 +175,12 @@ fn not_connected(_: 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 { let started = Instant::now(); @@ -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), diff --git a/crates/apache-pulsar/src/consumer/checkpoint.rs b/crates/apache-pulsar/src/consumer/checkpoint.rs index cc6d4f8..31d3f02 100644 --- a/crates/apache-pulsar/src/consumer/checkpoint.rs +++ b/crates/apache-pulsar/src/consumer/checkpoint.rs @@ -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}; @@ -166,6 +166,21 @@ impl CheckpointConsumerBuilder { /// 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> { let ApiClient::ThreadSafe(client) = &self.client else { unreachable!() }; let client = client.clone(); @@ -185,6 +200,10 @@ impl CheckpointConsumerBuilder { /// 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> { let builder = CheckpointConsumerBuilder:: { client: self.client, @@ -203,6 +222,10 @@ impl CheckpointConsumerBuilder { /// 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> { let ApiClient::Local(client) = &self.client else { unreachable!() }; let client = client.clone(); @@ -282,7 +305,8 @@ impl CheckpointConsumer { 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. @@ -291,19 +315,21 @@ impl CheckpointConsumer { 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>> { - 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>> { 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()) } @@ -315,8 +341,8 @@ impl CheckpointConsumer { } /// 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 { let (reply, checkpoint) = oneshot::channel(); self.shared.link.requests.unbounded_send(Request::Checkpoint { reply }).map_err(consumer_closed)?; @@ -324,7 +350,7 @@ impl CheckpointConsumer { } /// 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 } diff --git a/crates/apache-pulsar/src/consumer/mod.rs b/crates/apache-pulsar/src/consumer/mod.rs index 2021bb7..2b1c2c1 100644 --- a/crates/apache-pulsar/src/consumer/mod.rs +++ b/crates/apache-pulsar/src/consumer/mod.rs @@ -41,7 +41,7 @@ use futures_channel::{mpsc, oneshot}; use futures_util::Stream; use crate::client::{LoopSlot, PulsarClient}; -use crate::config::{Blocking, Local, ThreadSafe}; +use crate::config::{Blocking, Local, ThreadSafe, bounded}; use crate::error::{Error, ErrorKind, Result}; use crate::local; use crate::message_id::MessageId; @@ -212,9 +212,9 @@ fn consumer_options( consumer_name: settings.consumer_name.clone(), initial_position, receiver_queue_size: settings.receiver_queue_size, - ack_group_time: settings.ack_group_time, + ack_group_time: bounded(settings.ack_group_time), max_ack_group_size: settings.max_ack_group_size, - negative_ack_delay: settings.negative_ack_delay, + negative_ack_delay: bounded(settings.negative_ack_delay), priority_level: settings.priority_level, subscription_properties: settings.subscription_properties.clone(), properties: settings.properties.clone(), @@ -235,6 +235,21 @@ impl QueueConsumerBuilder { } /// Subscribes, on the client's least loaded event loop, to every segment of the topic. + /// + /// # Errors + /// + /// - [`InvalidConfiguration`](ErrorKind::InvalidConfiguration): the topic or the subscription name is missing or + /// malformed, the receiver queue or the acknowledgment group size is 0, or the schema is a key/value schema with + /// a part of [`Schema::auto_consume`], which reads key/value messages whole. + /// - [`NotFound`](ErrorKind::NotFound): the topic doesn't exist, and the broker doesn't create it. + /// - [`Authentication`](ErrorKind::Authentication), [`Authorization`](ErrorKind::Authorization) and + /// [`UnsupportedBroker`](ErrorKind::UnsupportedBroker), from the brokers. + /// - [`IncompatibleSchema`](ErrorKind::IncompatibleSchema): the schema isn't compatible with the topic's. + /// - [`ConsumerBusy`](ErrorKind::ConsumerBusy): the subscription doesn't take the consumer, as when a consumer of + /// another kind holds it. + /// - [`Timeout`](ErrorKind::Timeout): no layout, or a segment not subscribed, within the operation timeout; + /// [`Connect`](ErrorKind::Connect): the broker that serves the topic can't be reached. + /// - [`AlreadyClosed`](ErrorKind::AlreadyClosed): the client is closed. pub async fn subscribe(self) -> Result> { let ApiClient::ThreadSafe(client) = &self.client else { unreachable!() }; let (topic, options) = self.options(client.operation_timeout())?; @@ -252,6 +267,10 @@ impl QueueConsumerBuilder { } /// Subscribes, on the client's least loaded event loop, and blocks until every segment is subscribed. + /// + /// # Errors + /// + /// As the thread-safe API's `subscribe`, above. pub fn subscribe(self) -> Result> { let builder = QueueConsumerBuilder:: { client: self.client, @@ -269,6 +288,10 @@ impl QueueConsumerBuilder { } /// Subscribes, on the local client's loop, to every segment of the topic. + /// + /// # Errors + /// + /// As the thread-safe API's `subscribe`, above. pub async fn subscribe(self) -> Result> { let ApiClient::Local(client) = &self.client else { unreachable!() }; let (topic, options) = self.options(client.operation_timeout())?; @@ -389,6 +412,11 @@ impl Drop for Pending { } } +/// When a receive that waits up to `timeout` gives up. +fn deadline(timeout: Duration) -> Instant { + Instant::now() + bounded(timeout) +} + /// The error of an operation on a closed consumer: its task is gone, or went before answering. fn consumer_closed(_: E) -> Error { Error::new(ErrorKind::AlreadyClosed, "the consumer is closed") @@ -430,7 +458,7 @@ impl QueueConsumer { self.shared.consumer_name.as_deref() } - /// The next message. Fails only once the consumer is closed. + /// The next message. Fails only with [`AlreadyClosed`](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. @@ -439,19 +467,21 @@ impl QueueConsumer { 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`](ErrorKind::AlreadyClosed), once the consumer is closed. pub async fn receive_timeout(&self, timeout: Duration) -> Result>> { - 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`](ErrorKind::InvalidConfiguration) if `max` is 0, and with + /// [`AlreadyClosed`](ErrorKind::AlreadyClosed) once the consumer is closed. pub async fn receive_batch(&self, max: usize, timeout: Duration) -> Result>> { 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()) } @@ -463,8 +493,8 @@ impl QueueConsumer { } /// Acknowledges a message. The ack goes out with the others of its group; the broker doesn't confirm it. Fails - /// only once the consumer is closed. A message of a segment the consumer no longer has is acknowledged already - /// or gone: its ack does nothing, as in Java. + /// only with [`AlreadyClosed`](ErrorKind::AlreadyClosed), once the consumer is closed. A message of a segment the + /// consumer no longer has is acknowledged already or gone: its ack does nothing, as in Java. pub async fn acknowledge(&self, id: &MessageId) -> Result<()> { let (reply, done) = oneshot::channel(); self.shared.link.requests.unbounded_send(Request::Ack { id: id.0.clone(), reply }).map_err(consumer_closed)?; @@ -472,14 +502,14 @@ impl QueueConsumer { } /// Asks for a message again after the negative ack delay: the broker delivers its whole entry again. Fails only - /// once the consumer is closed. + /// with [`AlreadyClosed`](ErrorKind::AlreadyClosed), once the consumer is closed. pub fn negative_acknowledge(&self, id: &MessageId) -> Result<()> { self.shared.link.requests.unbounded_send(Request::Nack { id: id.0.clone() }).map_err(consumer_closed) } /// Closes the consumer: sends the acks waiting, then closes every segment's consumer. The receives waiting fail /// with [`ErrorKind::AlreadyClosed`], and the messages not received yet go to the subscription's other - /// consumers. Can be called again. + /// consumers. Can be called again. Doesn't fail. pub async fn close(&self) -> Result<()> { self.shared.link.close().await } @@ -525,6 +555,11 @@ impl std::fmt::Debug for Message { impl Message { /// The value, decoded with the consumer's schema each time. [`Schema::auto_consume`] decodes it with the schema /// it was written with, which the consumer fetched before delivering it: a fetch that failed fails here. + /// + /// # Errors + /// + /// [`Other`](ErrorKind::Other) if the payload doesn't decode with the schema, or the schema it was written with + /// isn't one this build reads; and the failure of the schema's fetch, such as a [`Timeout`](ErrorKind::Timeout). pub fn value(&self) -> Result { let writer = self.writer.as_ref().map_err(Clone::clone)?; self.schema.decode_with(&self.message.payload, writer.as_deref()) diff --git a/crates/apache-pulsar/src/consumer/stream.rs b/crates/apache-pulsar/src/consumer/stream.rs index d422a44..71cc14c 100644 --- a/crates/apache-pulsar/src/consumer/stream.rs +++ b/crates/apache-pulsar/src/consumer/stream.rs @@ -30,7 +30,7 @@ use futures_util::Stream; use super::stream_task::{Request, Task}; use super::writers::{self, Delivered, Writers}; -use super::{Message, Settings, SubscriptionInitialPosition, consumer_closed, consumer_options, invalid}; +use super::{Message, Settings, SubscriptionInitialPosition, consumer_closed, consumer_options, deadline, invalid}; use crate::client::{LoopSlot, PulsarClient}; use crate::config::{Blocking, Local, ThreadSafe}; use crate::error::Result; @@ -141,6 +141,24 @@ impl StreamConsumerBuilder { /// Subscribes, on the client's least loaded event loop: registers with the topic's controller, and subscribes to /// every segment it assigns. + /// + /// # Errors + /// + /// - [`InvalidConfiguration`](crate::ErrorKind::InvalidConfiguration): the topic or the subscription name 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. + /// - [`ConsumerBusy`](crate::ErrorKind::ConsumerBusy): the subscription doesn't take the consumer, as when a + /// consumer of another kind holds it. + /// - [`Timeout`](crate::ErrorKind::Timeout): no layout, no answer from the controller, or an assigned segment 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 the consumer, 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 subscribe(self) -> Result> { let ApiClient::ThreadSafe(client) = &self.client else { unreachable!() }; let (topic, name, options) = self.options(client.operation_timeout())?; @@ -159,6 +177,10 @@ impl StreamConsumerBuilder { } /// Subscribes, on the client's least loaded event loop, and blocks until every assigned segment is subscribed. + /// + /// # Errors + /// + /// As the thread-safe API's `subscribe`, above. pub fn subscribe(self) -> Result> { let builder = StreamConsumerBuilder:: { client: self.client, @@ -177,6 +199,10 @@ impl StreamConsumerBuilder { /// Subscribes, on the local client's loop: registers with the topic's controller, and subscribes to every segment /// it assigns. + /// + /// # Errors + /// + /// As the thread-safe API's `subscribe`, above. pub async fn subscribe(self) -> Result> { let ApiClient::Local(client) = &self.client else { unreachable!() }; let (topic, name, options) = self.options(client.operation_timeout())?; @@ -308,7 +334,8 @@ impl StreamConsumer { &self.shared.consumer_name } - /// 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. @@ -317,19 +344,21 @@ impl StreamConsumer { 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>> { - let messages = self.shared.receive(1, Some(Instant::now() + timeout)).await?; + let messages = self.shared.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>> { if max == 0 { return Err(invalid("a batch receive takes at least one message")); } - let messages = self.shared.receive(max, Some(Instant::now() + timeout)).await?; + let messages = self.shared.receive(max, Some(deadline(timeout))).await?; Ok(messages.into_iter().map(|message| self.message(message)).collect()) } @@ -341,18 +370,18 @@ impl StreamConsumer { } /// Acknowledges the message and every message received before it, from every part of the topic (*client-api* - /// §4.1). The ack goes out with the others of its group; the broker doesn't confirm it. Fails only once the - /// consumer is closed. + /// §4.1). The ack goes out with the others of its group; the broker doesn't confirm it. Fails only with + /// [`AlreadyClosed`](crate::ErrorKind::AlreadyClosed), once the consumer is closed. pub async fn acknowledge_cumulative(&self, id: &MessageId) -> Result<()> { let (reply, done) = oneshot::channel(); self.shared.link.requests.unbounded_send(Request::Ack { id: id.0.clone(), reply }).map_err(consumer_closed)?; done.await.map_err(consumer_closed)? } - /// Closes the consumer: sends the acks waiting, closes every segment's consumer, and leaves the controller's - /// group, which rebalances at once. The receives waiting fail with + /// Closes the consumer: sends the acks waiting, closes every segment's consumer, and leaves the controller's group, + /// which rebalances at once. The receives waiting fail with /// [`ErrorKind::AlreadyClosed`](crate::ErrorKind::AlreadyClosed), and the messages not acknowledged go to the - /// subscription's other consumers. Can be called again. + /// subscription's other consumers. Can be called again. Doesn't fail. pub async fn close(&self) -> Result<()> { let (reply, done) = oneshot::channel(); if self.shared.link.requests.unbounded_send(Request::Close { reply: Some(reply) }).is_err() { diff --git a/crates/apache-pulsar/src/consumer/stream_task.rs b/crates/apache-pulsar/src/consumer/stream_task.rs index 818b6e5..cd27cf3 100644 --- a/crates/apache-pulsar/src/consumer/stream_task.rs +++ b/crates/apache-pulsar/src/consumer/stream_task.rs @@ -40,7 +40,7 @@ use apache_pulsar_protocol::assignment::AssignmentSession; use apache_pulsar_protocol::connection::IdKind; use apache_pulsar_protocol::entry::ReceivedMessage; use apache_pulsar_protocol::frame::Frame; -use apache_pulsar_protocol::lookup::{BrokerAddress, parse_broker_url}; +use apache_pulsar_protocol::lookup::{BrokerAddress, LookupError, parse_broker_url}; use apache_pulsar_protocol::message_id::MessageId; use apache_pulsar_protocol::producer::RegisterError; use apache_pulsar_protocol::proto::base_command::Type; @@ -54,7 +54,7 @@ use futures_util::{Stream, StreamExt}; use super::task::{Link, Linked, close_command, subscribe, subscribe_error}; use super::writers::{Delivered, Writers}; use crate::conn::{ConnHandle, Push}; -use crate::error::{Error, Result}; +use crate::error::Result; use crate::local; /// What a Stream consumer's handle asks of its task. @@ -542,7 +542,8 @@ async fn controller(client: &local::PulsarClient, topic: &str) -> Result Ok(BrokerAddress::direct(parse_broker_url(url).map_err(Error::from)?)), + // A URL from the broker, not the application's: one that doesn't parse is a malformed answer. + Some(url) => Ok(BrokerAddress::direct(parse_broker_url(url).map_err(LookupError::from)?)), None => Ok(BrokerAddress::direct(service.hosts[0].clone())), } } diff --git a/crates/apache-pulsar/src/consumer_tests.rs b/crates/apache-pulsar/src/consumer_tests.rs index 61d6555..52b5f95 100644 --- a/crates/apache-pulsar/src/consumer_tests.rs +++ b/crates/apache-pulsar/src/consumer_tests.rs @@ -587,6 +587,58 @@ fn thread_safe_consumers_receive_on_any_thread() { assert_eq!(got, ["m0", "m1", "m2", "m3"]); } +/// A duration too long for a deadline, as `Duration::MAX`, counts as a year: nothing panics or hangs. A message +/// delivered after it waits as long as its metadata holds, not none. +#[test] +fn durations_too_long_for_a_deadline_count_as_a_year() { + run(async { + let server = WorldServer::start(world(1)).await; + let client = local::PulsarClient::builder() + .service_url(server.url()) + .connect_timeout(Duration::MAX) + .operation_timeout(Duration::MAX) + .keepalive_interval(Duration::MAX) + .build() + .await + .unwrap(); + let batching = crate::BatchingPolicy { max_publish_delay: Duration::MAX, ..Default::default() }; + let producer = client + .new_producer(Schema::string()) + .topic(TOPIC) + .send_timeout(Duration::MAX) + .batching_policy(batching) + .create() + .await + .unwrap(); + // The batch waits until the flush. + let (sent, flushed) = futures_util::join!(producer.send("now".into()), producer.flush()); + sent.unwrap(); + flushed.unwrap(); + producer.new_message().value("later".into()).deliver_after(Duration::MAX).send().await.unwrap(); + let delivered_at = server.world.borrow().stored(TOPIC).last().unwrap().metadata.deliver_at_time; + assert_eq!(delivered_at, Some(i64::MAX)); + + let consumer = client + .new_queue_consumer(Schema::string()) + .topic(TOPIC) + .subscription_name(SUB) + .subscription_initial_position(SubscriptionInitialPosition::Earliest) + .acknowledgment_group_time(Duration::MAX) + .negative_ack_redelivery_delay(Duration::MAX) + .subscribe() + .await + .unwrap(); + let first = consumer.receive_timeout(Duration::MAX).await.unwrap().unwrap(); + let more = consumer.receive_batch(1, Duration::MAX).await.unwrap(); + consumer.negative_acknowledge(first.id()).unwrap(); + consumer.acknowledge(more[0].id()).await.unwrap(); + // The ack waits for its group until the close sends it. + consumer.close().await.unwrap(); + assert_eq!(backlog(&server, 0), 1); + client.close().await.unwrap(); + }); +} + /// Thread-safe consumers, their messages and their futures can move across threads. #[allow(dead_code)] fn thread_safe_types_are_send(consumer: &crate::QueueConsumer, id: &crate::MessageId) { diff --git a/crates/apache-pulsar/src/error.rs b/crates/apache-pulsar/src/error.rs index e82b1ac..246969f 100644 --- a/crates/apache-pulsar/src/error.rs +++ b/crates/apache-pulsar/src/error.rs @@ -25,36 +25,97 @@ use apache_pulsar_protocol::lookup::{LookupError, UrlError}; use apache_pulsar_protocol::proto::ServerError; use buffa::EnumValue; -/// The category of an [`Error`]: what the application can act on. +/// The category of an [`Error`]: what the application can branch on (*error-model* §2). +/// +/// The client retries what it can resolve itself: a lost connection, a broker that isn't ready, a segment that a +/// split or a merge replaced. Those reach the application only once the retries run out, mostly as +/// [`Timeout`](Self::Timeout). The other kinds come back at once, and the client doesn't retry them: +/// +/// - [`NotFound`](Self::NotFound), [`Authentication`](Self::Authentication), [`Authorization`](Self::Authorization), +/// [`IncompatibleSchema`](Self::IncompatibleSchema), [`InvalidConfiguration`](Self::InvalidConfiguration) and +/// [`InvalidServiceUrl`](Self::InvalidServiceUrl) fail the same way again until the configuration, the +/// credentials or the topic changes; +/// - [`ProducerBusy`](Self::ProducerBusy), [`ProducerFenced`](Self::ProducerFenced) and +/// [`ConsumerBusy`](Self::ConsumerBusy) come from the topic's access mode or the subscription's type; +/// - after [`Timeout`](Self::Timeout), [`MemoryBufferFull`](Self::MemoryBufferFull) and +/// [`MessageTooLarge`](Self::MessageTooLarge), the application decides whether to try again. +/// +/// A failed send fails that message only, and a failed receive or acknowledgment loses nothing: the producer or the +/// consumer stays usable, unless the error is [`AlreadyClosed`](Self::AlreadyClosed). +/// +/// More kinds may come in later releases, so a `match` on a kind needs a wildcard arm. #[non_exhaustive] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ErrorKind { + /// The topic doesn't exist and the broker doesn't create it, or the broker doesn't know the subscription or + /// the consumer named. NotFound, + /// The broker refused the credentials, or the [`Authentication`](crate::Authentication) provider failed to + /// supply them. Authentication, + /// The credentials are valid, but they don't allow the operation on the topic. Authorization, + /// The operation didn't complete in time: a lookup, a create or a subscribe within the client's operation + /// timeout, a message within the producer's send timeout, a connection within the connect timeout. A failure the + /// client kept retrying, such as a broker it can't connect to, ends as a timeout too, with the last failure in its + /// message. Timeout, + /// The client, the producer or the consumer is closed: by `close`, or as the client closed. Messages a producer + /// still held when it closed fail with it too. AlreadyClosed, + /// The topic doesn't take this producer: an exclusive producer holds it, another producer has the same name, or + /// the topic has as many producers as it allows. ProducerBusy, + /// An exclusive producer can't have the topic, which other producers hold, or a newer exclusive producer took it: + /// the producer is fenced out. Create a new producer to try again. ProducerFenced, + /// The subscription doesn't take this consumer: its type allows one consumer and another is attached, or the + /// consumer's key ranges overlap another consumer's. ConsumerBusy, + /// The schema isn't compatible with the topic's. It fails a consumer's subscribe or create, an exclusive + /// producer's create, and a Shared producer's sends to a segment, where it registers with its first message. IncompatibleSchema, + /// The topic is terminated and takes no more messages. The producer moves the messages of a segment that a split + /// or a merge sealed to its successors by itself: a message fails with this kind only after ten tries. TopicTerminated, + /// The client can't connect to a broker. Retried by the client, as a timeout once the retries run out: a create or + /// a subscribe fails with this kind when the broker that serves the topic can't be reached for its first layout, + /// as in Java. Connect, + /// The connection to a broker closed, or the broker isn't ready to serve the topic. Retried by the client. NotConnected, + /// A producer's queue of pending messages is full. Not raised: the client's memory limit is the only bound on + /// what producers hold, as in Java V5. ProducerQueueFull, + /// The client's memory limit is reached, and the producer doesn't wait for room + /// ([`ProducerBuilder::block_if_queue_full`](crate::ProducerBuilder::block_if_queue_full)). Room comes back as + /// the brokers store the messages in flight. MemoryBufferFull, /// A message larger than the broker accepts. It fails alone: the producer stays usable. MessageTooLarge, + /// A transaction conflicts with another, or can't go on. Not raised yet: transactions come in a later release. TransactionConflict, + /// Encrypting or decrypting a message failed. Not raised yet: end-to-end encryption comes in a later release. Crypto, + /// A builder's settings, or an argument, are invalid: a topic or a subscription name that is missing or + /// malformed, a codec this build leaves out, a schema used where it doesn't apply, TLS files that can't be read, + /// bytes that aren't a message id or a checkpoint. InvalidConfiguration, + /// The service URL is malformed: it takes `pulsar://` or `pulsar+ssl://`, and one or more `host:port`. InvalidServiceUrl, + /// The broker doesn't support scalable topics, which take Pulsar 5.0 or later (C15). UnsupportedBroker, - /// A failure outside the other categories, such as an unexpected broker error. + /// A failure outside the other categories: a value that doesn't encode with the schema or a payload that doesn't + /// decode with it, an answer from a broker that the client can't read, a broker error with no category of its + /// own, an event loop that can't start. Other, } -/// An error from the client. +/// An error from the client: its [`ErrorKind`], a message, and the failure that caused it, if any, as its +/// [`source`](std::error::Error::source). +/// +/// It prints as its kind and its message, as in `Timeout: no layout for topic://acme/orders/events within the +/// timeout`. Cheap to clone. #[derive(Clone)] pub struct Error { kind: ErrorKind, @@ -66,6 +127,7 @@ pub struct Error { pub type Result = std::result::Result; impl Error { + /// An error of `kind`, such as one an [`Authentication`](crate::Authentication) provider returns. pub fn new(kind: ErrorKind, message: impl Into) -> Self { Self { kind, message: message.into(), source: None } } @@ -78,10 +140,16 @@ impl Error { Self { kind, message: message.into(), source: Some(Arc::new(source)) } } + /// The category of the error. pub fn kind(&self) -> ErrorKind { self.kind } + /// The message, without the kind. + pub(crate) fn message(&self) -> &str { + &self.message + } + /// Whether trying again may succeed: connection and timeout failures, not configuration or permission ones. pub(crate) fn is_retryable(&self) -> bool { matches!(self.kind, ErrorKind::Connect | ErrorKind::NotConnected | ErrorKind::Timeout) @@ -91,13 +159,19 @@ impl Error { Self::new(ErrorKind::AlreadyClosed, "the client is closed") } - /// The broker's error code, when the broker refused the operation. + /// The broker's error code, when the broker refused the operation, or refused the connection with an error the + /// client doesn't retry, such as credentials it rejects. A refusal the client retries, as a lookup does, counts as + /// a failure to connect. pub(crate) fn server_error(&self) -> Option<(ServerError, String)> { let source = self.source.as_deref()?; let (error, message) = if let Some(RequestError::Server { error, message }) = source.downcast_ref() { (*error, message) } else if let Some(LookupError::Server { error, message }) = source.downcast_ref() { (*error, message) + } else if let Some(ConnectionError::Refused { error, message }) = source.downcast_ref() + && !self.is_retryable() + { + (*error, message) } else { return None; }; @@ -126,7 +200,7 @@ impl std::error::Error for Error { } } -/// The category of a broker error code. +/// The category of a broker error code, as Java V5 maps its v4 exception (`V5ExceptionMappings`) where it has one. pub(crate) fn server_error_kind(error: EnumValue) -> ErrorKind { use ServerError::*; match error { @@ -135,11 +209,16 @@ pub(crate) fn server_error_kind(error: EnumValue) -> ErrorKind { EnumValue::Known(AuthorizationError) => ErrorKind::Authorization, EnumValue::Known(ProducerBusy) => ErrorKind::ProducerBusy, EnumValue::Known(ProducerFenced) => ErrorKind::ProducerFenced, - EnumValue::Known(ConsumerBusy) => ErrorKind::ConsumerBusy, + // Key_Shared ranges that overlap another consumer's: a subscription constraint, as for Java. + EnumValue::Known(ConsumerBusy | ConsumerAssignError) => ErrorKind::ConsumerBusy, EnumValue::Known(IncompatibleSchema) => ErrorKind::IncompatibleSchema, EnumValue::Known(TopicTerminatedError) => ErrorKind::TopicTerminated, EnumValue::Known(TransactionConflict) => ErrorKind::TransactionConflict, + // A transaction no longer open, or that its coordinator no longer knows: it can't go on, as for Java V5. + EnumValue::Known(InvalidTxnStatus | TransactionNotFound) => ErrorKind::TransactionConflict, EnumValue::Known(ServiceNotReady | TooManyRequests) => ErrorKind::NotConnected, + // A name the broker refuses is the application's to change. Java V5 has no category for it. + EnumValue::Known(InvalidTopicName) => ErrorKind::InvalidConfiguration, _ => ErrorKind::Other, } } diff --git a/crates/apache-pulsar/src/local.rs b/crates/apache-pulsar/src/local.rs index 025c217..9713ed7 100644 --- a/crates/apache-pulsar/src/local.rs +++ b/crates/apache-pulsar/src/local.rs @@ -130,8 +130,8 @@ impl PulsarClient { crate::CheckpointConsumerBuilder::new_local(self.clone(), schema) } - /// Closes the producers and consumers, then every connection. Later operations fail with [`ErrorKind::AlreadyClosed`]. Can - /// be called again. + /// Closes the producers and consumers, then every connection. Later operations fail with + /// [`ErrorKind::AlreadyClosed`]. Can be called again. Doesn't fail. pub async fn close(&self) -> Result<()> { if self.inner.closed.replace(true) { return Ok(()); @@ -262,7 +262,14 @@ impl PulsarClient { } impl ClientBuilder { - /// Creates the client. Must be called inside a compio runtime, which the client's tasks then run on. + /// Creates the client. Must be called inside a compio runtime, which the client's tasks then run on. 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, or TLS authentication is set without a `pulsar+ssl://` URL. pub async fn build(self) -> Result { Ok(PulsarClient::from_config(self.into_config()?)) } diff --git a/crates/apache-pulsar/src/message_id.rs b/crates/apache-pulsar/src/message_id.rs index 4c16936..b845d65 100644 --- a/crates/apache-pulsar/src/message_id.rs +++ b/crates/apache-pulsar/src/message_id.rs @@ -48,7 +48,8 @@ impl MessageId { self.0.to_bytes() } - /// Restores an id from [`MessageId::to_bytes`], or from bytes the Java client wrote. + /// Restores an id from [`MessageId::to_bytes`], or from bytes the Java client wrote. Fails with + /// [`InvalidConfiguration`](ErrorKind::InvalidConfiguration) for bytes that aren't an id. pub fn from_bytes(bytes: &[u8]) -> Result { wire::MessageId::from_bytes(bytes) .map(MessageId) diff --git a/crates/apache-pulsar/src/producer/mod.rs b/crates/apache-pulsar/src/producer/mod.rs index 0b63a04..f204f1e 100644 --- a/crates/apache-pulsar/src/producer/mod.rs +++ b/crates/apache-pulsar/src/producer/mod.rs @@ -31,7 +31,7 @@ use apache_pulsar_protocol::proto; use futures_channel::{mpsc, oneshot}; use crate::client::{LoopSlot, PulsarClient}; -use crate::config::{Blocking, Local, ThreadSafe}; +use crate::config::{Blocking, Local, ThreadSafe, bounded}; use crate::error::{Error, ErrorKind, Result}; use crate::local; use crate::memory::{MemoryLimit, PER_MESSAGE_OVERHEAD}; @@ -111,7 +111,7 @@ impl BatchingPolicy { self.enabled.then_some(Batching { max_messages: self.max_messages, max_bytes: self.max_size, - max_delay: self.max_publish_delay, + max_delay: bounded(self.max_publish_delay), }) } } @@ -246,7 +246,7 @@ impl ProducerBuilder { /// How long a message may wait to be stored once it is on its way to a broker; [`Duration::ZERO`] for no /// limit. 30 s by default. A message that times out fails alone: the producer stays usable. pub fn send_timeout(mut self, timeout: Duration) -> Self { - self.settings.send_timeout = (!timeout.is_zero()).then_some(timeout); + self.settings.send_timeout = (!timeout.is_zero()).then_some(bounded(timeout)); self } @@ -309,7 +309,23 @@ impl ProducerBuilder { Self { client: ApiClient::ThreadSafe(client), schema, settings: Settings::default(), _api: PhantomData } } - /// Creates the producer, on the client's least loaded event loop. + /// Creates the producer, on the client's least loaded event loop, once the topic's layout is known. A Shared + /// producer registers on each segment with the first message routed there; an exclusive one registers on every + /// segment now. + /// + /// # Errors + /// + /// - [`InvalidConfiguration`](ErrorKind::InvalidConfiguration): the topic is missing or malformed, the schema is + /// one only consumers decode with ([`Schema::auto_consume`]), or this build leaves the codec out. + /// - [`NotFound`](ErrorKind::NotFound): the topic doesn't exist, and the broker doesn't create it. + /// - [`Authentication`](ErrorKind::Authentication), [`Authorization`](ErrorKind::Authorization) and + /// [`UnsupportedBroker`](ErrorKind::UnsupportedBroker), from the broker that serves the topic. + /// - [`ProducerBusy`](ErrorKind::ProducerBusy), [`ProducerFenced`](ErrorKind::ProducerFenced) and + /// [`IncompatibleSchema`](ErrorKind::IncompatibleSchema), under an exclusive access mode. A Shared producer + /// meets them in its sends. + /// - [`Timeout`](ErrorKind::Timeout): no layout, or for an exclusive producer no segment's broker, within the + /// operation timeout; [`Connect`](ErrorKind::Connect): the broker that serves the topic can't be reached. + /// - [`AlreadyClosed`](ErrorKind::AlreadyClosed): the client is closed. pub async fn create(self) -> Result> { let ApiClient::ThreadSafe(client) = &self.client else { unreachable!() }; let topic = normalize_topic(self.settings.topic.as_deref())?; @@ -327,6 +343,10 @@ impl ProducerBuilder { } /// Creates the producer, on the client's least loaded event loop, and blocks until it is ready. + /// + /// # Errors + /// + /// As the thread-safe API's `create`, above. pub fn create(self) -> Result> { let builder = ProducerBuilder:: { client: self.client, @@ -344,6 +364,10 @@ impl ProducerBuilder { } /// Creates the producer, on the local client's loop. + /// + /// # Errors + /// + /// As the thread-safe API's `create`, above. pub async fn create(self) -> Result> { let ApiClient::Local(client) = &self.client else { unreachable!() }; let topic = normalize_topic(self.settings.topic.as_deref())?; @@ -476,13 +500,18 @@ impl Producer { MessageBuilder { producer: self, value: None, message: OutgoingMessage::default() } } - /// Sends a message with only a value. See [`MessageBuilder::send`]. + /// Sends a message with only a value. See [`MessageBuilder::send`], which fails the same ways. pub async fn send(&self, value: T) -> Result { self.new_message().value(value).send().await } /// Waits for every message sent before the call to be stored, and fails if one of them failed. The open batches /// go out at once, without waiting out the batching delay. + /// + /// # Errors + /// + /// The first failure among those messages, as their sends have it ([`MessageBuilder::send`]), or + /// [`AlreadyClosed`](ErrorKind::AlreadyClosed) once the producer is closed. pub async fn flush(&self) -> Result<()> { let (reply, done) = oneshot::channel(); self.shared.link.requests.unbounded_send(Request::Flush { reply }).map_err(producer_closed)?; @@ -492,7 +521,7 @@ impl Producer { /// Closes the producer: waits for the messages the brokers already have, fails those still waiting, in an open /// batch or for a layout, a connection or a segment's producer, with [`ErrorKind::AlreadyClosed`], and closes every /// segment's producer. Later sends fail. Can be called again. Call [`Producer::flush`] first to publish - /// everything. + /// everything. Doesn't fail. pub async fn close(&self) -> Result<()> { let (reply, done) = oneshot::channel(); if self.shared.link.requests.unbounded_send(Request::Close { reply: Some(reply) }).is_err() { @@ -554,7 +583,8 @@ impl MessageBuilder<'_, T, Api> { /// Delivers the message to consumers no sooner than `delay` from now. pub fn deliver_after(mut self, delay: Duration) -> Self { - self.message.deliver_at = Some(now_millis() as i64 + delay.as_millis() as i64); + // As late as the field holds, for a longer delay. + self.message.deliver_at = Some(i64::try_from(u128::from(now_millis()) + delay.as_millis()).unwrap_or(i64::MAX)); self } @@ -572,15 +602,36 @@ impl MessageBuilder<'_, T, Api> { /// Sends the message, and completes with its id once it is stored. /// - /// The message is queued when the future is first polled, so sends are published in the order their futures - /// are first polled, which is call order for code that awaits each one or drives them with `buffered`, - /// `FuturesOrdered` or `join_all`. Spawning each send as a task of its own gives no order. Dropping the future - /// after its first poll doesn't recall the message: it may still be published. The producer's send timeout - /// bounds how long a message waits. + /// The message is queued when the future is first polled, so sends are published in the order their futures are + /// first polled, which is call order for code that awaits each one or drives them with `buffered`, `FuturesOrdered` + /// or `join_all`. Spawning each send as a task of its own gives no order. Dropping the future after its first poll + /// doesn't recall the message: it may still be published. The producer's send timeout bounds how long a message + /// waits. + /// + /// With batching, on by default, the message waits up to the batching delay (1 ms by default) for others to join + /// its batch. A loop that awaits each send pays that delay for every message: pipeline the sends, as above, or call + /// [`Producer::flush`], or turn batching off ([`ProducerBuilder::batching_policy`]). + /// + /// # Errors + /// + /// A failed send fails that message only: the producer stays usable, unless it is closed. /// - /// With batching, on by default, the message waits up to the batching delay (1 ms by default) for others to - /// join its batch. A loop that awaits each send pays that delay for every message: pipeline the sends, as above, - /// or call [`Producer::flush`], or turn batching off ([`ProducerBuilder::batching_policy`]). + /// - [`InvalidConfiguration`](ErrorKind::InvalidConfiguration): the message has no value. + /// - [`Other`](ErrorKind::Other): the schema can't encode the value. + /// - [`MemoryBufferFull`](ErrorKind::MemoryBufferFull): the client's memory limit is reached, and the producer + /// doesn't wait for room ([`ProducerBuilder::block_if_queue_full`]). + /// - [`MessageTooLarge`](ErrorKind::MessageTooLarge): the message is larger than the broker takes. + /// - [`Timeout`](ErrorKind::Timeout): the message wasn't stored within the send timeout, or no broker took the + /// producer of its segment within the operation timeout. + /// - [`IncompatibleSchema`](ErrorKind::IncompatibleSchema), [`ProducerBusy`](ErrorKind::ProducerBusy), + /// [`Authentication`](ErrorKind::Authentication) or [`Authorization`](ErrorKind::Authorization): the broker of + /// the message's segment refused the producer, which a Shared producer registers with its first message there. + /// The next message routed there tries again. + /// - [`ProducerFenced`](ErrorKind::ProducerFenced): a newer exclusive producer took the topic. + /// - [`TopicTerminated`](ErrorKind::TopicTerminated): the message moved from a sealed segment to its successors ten + /// times without being stored. + /// - [`AlreadyClosed`](ErrorKind::AlreadyClosed): the producer is closed, or closed before a broker had the + /// message. pub async fn send(self) -> Result { self.producer.dispatch(self.value, self.message, false).await } diff --git a/crates/apache-pulsar/src/producer/task.rs b/crates/apache-pulsar/src/producer/task.rs index 6a77214..738d623 100644 --- a/crates/apache-pulsar/src/producer/task.rs +++ b/crates/apache-pulsar/src/producer/task.rs @@ -36,7 +36,9 @@ use apache_pulsar_protocol::connection::IdKind; use apache_pulsar_protocol::frame::Frame; use apache_pulsar_protocol::producer::{Action, OutgoingMessage, Producer, RegisterError, SendError, SendId}; use apache_pulsar_protocol::proto::base_command::Type; -use apache_pulsar_protocol::proto::{BaseCommand, CommandCloseProducer, CommandProducerSuccess, MessageMetadata}; +use apache_pulsar_protocol::proto::{ + BaseCommand, CommandCloseProducer, CommandProducerSuccess, MessageMetadata, ServerError, +}; use buffa::{EnumValue, MessageView}; use bytes::Bytes; use futures_channel::{mpsc, oneshot}; @@ -466,11 +468,16 @@ async fn register( Ok((link, pushes, success)) } -/// Why a producer couldn't register: the broker's refusal, or no broker to ask. +/// Why a producer or a consumer couldn't register: the broker's refusal, or no broker to ask. Credentials the broker +/// refused, or the provider couldn't supply, count as the broker's `AuthenticationError`, which isn't retried, as a +/// lookup doesn't retry them. impl From for RegisterError { fn from(error: Error) -> Self { match error.server_error() { Some((error, message)) => RegisterError::Server { error, message }, + None if error.kind() == ErrorKind::Authentication => { + RegisterError::Server { error: ServerError::AuthenticationError, message: error.message().to_string() } + } None => RegisterError::Unavailable(error.to_string()), } } diff --git a/crates/apache-pulsar/src/tests/clients.rs b/crates/apache-pulsar/src/tests/clients.rs index 3f59f22..c08f216 100644 --- a/crates/apache-pulsar/src/tests/clients.rs +++ b/crates/apache-pulsar/src/tests/clients.rs @@ -169,6 +169,16 @@ fn a_loop_thread_that_cannot_be_spawned_fails_the_build() { assert!(error.to_string().contains("can't start an event loop thread"), "{error}"); } +/// More loops than threads can start: the build fails as they run out, without reserving room for them all first. +#[test] +fn a_loop_count_too_large_to_start_fails_the_build() { + use crate::client::LoopStarter; + let starter = LoopStarter { spawn: |_, _| Err(std::io::Error::other("no more threads")), ..LoopStarter::SYSTEM }; + let builder = PulsarClient::builder().service_url("pulsar://127.0.0.1:1").event_loops(usize::MAX); + let error = futures_executor::block_on(builder.build_with(starter)).unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Other, "{error}"); +} + #[test] fn a_loop_without_a_runtime_fails_the_build() { use crate::client::LoopStarter; diff --git a/crates/apache-pulsar/src/tests/driver.rs b/crates/apache-pulsar/src/tests/driver.rs index 3dc350b..40691f7 100644 --- a/crates/apache-pulsar/src/tests/driver.rs +++ b/crates/apache-pulsar/src/tests/driver.rs @@ -129,6 +129,28 @@ fn the_connect_timeout_covers_the_authentication_provider() { }); } +/// A provider that can't supply credentials fails the connection with an authentication failure, whatever its own +/// error's kind, which comes as the source: not retried, as the provider's kind here would be. +#[test] +fn a_failing_authentication_provider_is_an_authentication_failure() { + run(async { + let server = SimServer::start(None, self_serving).await; + let provider = || async { Err(crate::Error::new(ErrorKind::Connect, "the token service is down")) }; + let client = local::PulsarClient::builder() + .service_url(server.service_url("pulsar")) + .authentication(Token::from_fn(provider)) + .build() + .await + .unwrap(); + let error = client.lookup(TOPIC).await.unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Authentication, "{error}"); + let source = std::error::Error::source(&error).map(ToString::to_string); + assert_eq!(source.as_deref(), Some("Connect: the token service is down")); + assert!(server.received(Type::CONNECT).is_empty()); + client.close().await.unwrap(); + }); +} + #[test] fn a_request_the_broker_does_not_support_fails_at_once() { run(async { diff --git a/crates/apache-pulsar/src/tests/errors.rs b/crates/apache-pulsar/src/tests/errors.rs index a98347a..10b789d 100644 --- a/crates/apache-pulsar/src/tests/errors.rs +++ b/crates/apache-pulsar/src/tests/errors.rs @@ -39,11 +39,16 @@ fn broker_error_codes_map_to_kinds() { (ProducerBusy, ErrorKind::ProducerBusy), (ProducerFenced, ErrorKind::ProducerFenced), (ConsumerBusy, ErrorKind::ConsumerBusy), + // Key_Shared ranges that overlap another consumer's, as Java V5 maps it. + (ConsumerAssignError, ErrorKind::ConsumerBusy), (IncompatibleSchema, ErrorKind::IncompatibleSchema), (TopicTerminatedError, ErrorKind::TopicTerminated), (TransactionConflict, ErrorKind::TransactionConflict), + (InvalidTxnStatus, ErrorKind::TransactionConflict), + (TransactionNotFound, ErrorKind::TransactionConflict), (ServiceNotReady, ErrorKind::NotConnected), (TooManyRequests, ErrorKind::NotConnected), + (InvalidTopicName, ErrorKind::InvalidConfiguration), (PersistenceError, ErrorKind::Other), ]; for (code, kind) in cases { @@ -115,3 +120,56 @@ fn the_brokers_refusal_is_found_in_an_error() { let registration = RegisterError::from(Error::closed()); assert!(matches!(®istration, RegisterError::Unavailable(m) if m.contains("closed")), "{registration:?}"); } + +/// A broker that refuses the handshake with credentials it rejects has refused the registration the connection was +/// for, which isn't retried; a refusal the client retries, as a lookup does, stays a failure to connect. Credentials +/// the provider couldn't supply count as rejected. +#[test] +fn a_refused_handshake_is_the_brokers_refusal_unless_it_is_retried() { + use apache_pulsar_protocol::producer::RegisterError; + + let refused = |code| Error::from(ConnectionError::Refused { error: EnumValue::Known(code), message: "no".into() }); + assert_eq!( + refused(ServerError::AuthenticationError).server_error(), + Some((ServerError::AuthenticationError, "no".into())) + ); + assert_eq!( + refused(ServerError::AuthorizationError).server_error(), + Some((ServerError::AuthorizationError, "no".into())) + ); + assert_eq!(refused(ServerError::ServiceNotReady).server_error(), None); + assert_eq!(refused(ServerError::UnknownError).server_error(), None); + assert!(matches!(RegisterError::from(refused(ServerError::UnknownError)), RegisterError::Unavailable(_))); + + let rejected = RegisterError::from(Error::from(ConnectionError::Authentication("expired".into()))); + let expected = RegisterError::Server { + error: ServerError::AuthenticationError, + message: "authentication failed: expired".into(), + }; + assert_eq!(rejected, expected); +} + +/// A Shared producer registers on a segment with its first message there. A segment's broker that refuses the +/// credentials fails that send with the refusal, at once, not with a timeout once the retries run out. +#[test] +fn a_segment_broker_refusing_the_credentials_fails_the_send() { + use crate::Schema; + use crate::producer_tests::{TOPIC, WorldServer, local_client, world}; + use apache_pulsar_testkit::{LookupAnswer, SimBroker}; + + super::run(async { + let server = WorldServer::start(world(1)).await; + let client = local_client(&server).await; + let producer = client.new_producer(Schema::string()).topic(TOPIC).create().await.unwrap(); + let refusing = super::SimServer::start(None, |_| { + let mut broker = SimBroker::new(); + broker.refuse = Some(ServerError::AuthenticationError); + super::Behavior { broker, close_after: None, push_after_connect: vec![] } + }) + .await; + server.with(|world| world.lookup = LookupAnswer::Connect { broker: refusing.address.clone(), proxy: false }); + let error = producer.send("refused".into()).await.unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Authentication, "{error}"); + client.close().await.unwrap(); + }); +} diff --git a/docs/7-api.md b/docs/7-api.md index cbe0fb8..56230f4 100644 --- a/docs/7-api.md +++ b/docs/7-api.md @@ -184,7 +184,7 @@ pub enum ErrorKind { NotFound, Authentication, Authorization, Timeout, AlreadyClosed, ProducerBusy, ProducerFenced, ConsumerBusy, IncompatibleSchema, TopicTerminated, Connect, NotConnected, ProducerQueueFull, MemoryBufferFull, MessageTooLarge, TransactionConflict, - Crypto, InvalidConfiguration, InvalidServiceUrl, UnsupportedBroker, + Crypto, InvalidConfiguration, InvalidServiceUrl, UnsupportedBroker, Other, } ``` @@ -196,9 +196,26 @@ pub enum ErrorKind { - `MessageTooLarge` is the failure of a message larger than the broker's `max_message_size`. It fails alone, and the producer stays usable. The spec has no category for it, and Java V5 raises a plain `PulsarClientException` ([spec gap 12](../DESIGN.md#spec-gaps-to-raise-upstream)). +- `Other` is a failure outside the categories, which the spec leaves room for, since it asks for `NotFound` to be + distinct from a generic failure: a value the schema can't encode or a payload it can't decode, an answer from a + broker the client can't read, a broker error code with no category of its own, an event loop that can't start. +- Broker error codes map to kinds as Java V5 maps the exceptions they become (`V5ExceptionMappings`): + `ConsumerAssignError`, Key_Shared ranges that overlap another consumer's, is `ConsumerBusy`, and a transaction's + `InvalidTxnStatus` and `TransactionNotFound` are `TransactionConflict`. `InvalidTopicName`, which Java leaves + without a category, is `InvalidConfiguration`. +- What the spec retries (*error-model* §3), the client retries: a lost connection, a broker that isn't ready, a + segment that is gone. A failure it keeps retrying ends as a `Timeout`, with the last failure in its message; a + message that moved from a sealed segment to its successors ten times fails with `TopicTerminated`. What the spec + surfaces comes back at once: credentials the broker refuses fail a lookup, a create, a subscribe, and a producer's + first registration on a segment, without a retry. A producer already registered on a segment retries them as it + retries the lost connection, so that its messages wait, within their send timeout, for a provider with fresh ones; + a running consumer subscribes the segment again after a backoff. An authentication provider that fails is an + `Authentication` failure, whatever its own error's kind, as in Java V5. - The spec's `Interrupted` has no Rust counterpart, since Rust threads are not interrupted. - An async operation never fails before its future exists: every failure comes out of the future - (*error-model* §1). Nothing in the public API panics on bad input; that is an `InvalidConfiguration` error. + (*error-model* §1). Nothing in the public API panics on bad input; that is an `InvalidConfiguration` error. A + duration longer than a year, as `Duration::MAX`, counts as a year, which every timer takes. +- Each operation's rustdoc lists the kinds it fails with. ## 7. Message identifiers and checkpoints