diff --git a/crates/apache-pulsar-protocol/tests/layout.rs b/crates/apache-pulsar-protocol/tests/layout.rs index ba54c91..3ad1e59 100644 --- a/crates/apache-pulsar-protocol/tests/layout.rs +++ b/crates/apache-pulsar-protocol/tests/layout.rs @@ -78,6 +78,27 @@ fn legacy_layout_routes_like_v4_partitions() { } } +/// A legacy segment active beside a managed one: keys still route by hash range. Only a layout whose active +/// segments are all legacy routes them like v4 partitions. Java's +/// `SegmentRouterTest.testMixedLegacyAndRegularStillUsesHashRouting`. +#[test] +fn a_legacy_segment_beside_a_managed_one_routes_by_hash_range() { + let legacy = SegmentInfoProto { + legacy_topic_name: Some("persistent://acme/orders/events-partition-0".into()), + ..info(0, 0, 0x7fff, true) + }; + let layout = layout(vec![legacy, info(1, 0x8000, 0xffff, true)]); + // A key in each half whose v4 partition is the other segment. + let crossed = |high: bool| { + (0..) + .map(|i: u32| KeyHash::of(&i.to_be_bytes())) + .find(|h| (h.segment_hash() >= 0x8000) == high && h.partition(2) == u32::from(!high)) + .unwrap() + }; + assert_eq!(layout.route_key(crossed(false)), Ok(0)); + assert_eq!(layout.route_key(crossed(true)), Ok(1)); +} + /// A layout replaces one of a lower epoch. At the same epoch, only a migrated topic's first layout replaces the /// synthetic one, as the 5.0.1 broker gives both epoch 0. #[test] @@ -127,3 +148,17 @@ fn keeps_bucket_splits() { segment.entry_bucket_splits = vec![0x100, 0x1_0000]; assert_eq!(layout(vec![segment]).segment(0).unwrap().bucket_splits, [0x100, 0xffff]); } + +/// The DAG names the controller's `pulsar://` and `pulsar+ssl://` URLs: the layout gives the one for the client's +/// connections. Java's `ClientSegmentLayoutTest.testControllerBrokerUrlPropagated`. +#[test] +fn gives_the_controller_url_for_plain_or_tls_connections() { + let dag = ScalableTopicDAG { + controller_broker_url: Some("pulsar://controller:6650".into()), + controller_broker_url_tls: Some("pulsar+ssl://controller-tls:6651".into()), + ..Default::default() + }; + let layout = Layout::from_dag(&dag, "topic://acme/orders/events").unwrap(); + assert_eq!(layout.controller(false), Some("pulsar://controller:6650")); + assert_eq!(layout.controller(true), Some("pulsar+ssl://controller-tls:6651")); +} diff --git a/crates/apache-pulsar-protocol/tests/message_id_vectors.rs b/crates/apache-pulsar-protocol/tests/message_id_vectors.rs index 6b3c72c..db82b5d 100644 --- a/crates/apache-pulsar-protocol/tests/message_id_vectors.rs +++ b/crates/apache-pulsar-protocol/tests/message_id_vectors.rs @@ -172,6 +172,7 @@ fn rejects_malformed_bytes() { #[test] fn ids_hash_and_order_as_they_compare() { use std::collections::{BTreeSet, HashSet}; + use std::hash::{BuildHasher, RandomState}; let entry = |batch_index, batch_size| EntryId { ledger_id: 1, entry_id: 2, partition: -1, batch_index, batch_size }; // The batch size is carried, not compared: the same entry in a set once. let entries: HashSet = [entry(0, 1), entry(0, 5), entry(1, 5)].into_iter().collect(); @@ -184,6 +185,15 @@ fn ids_hash_and_order_as_they_compare() { .into_iter() .collect(); assert_eq!(ids.len(), 2); + // The position vector is carried, not compared: ids differing only there are equal, and hash alike. Java's + // `MessageIdV5Test.testEqualsIgnoresPositionVector`. + let mut one = MessageId::new(7, entry(-1, 0)); + one.positions.insert(0, entry(-1, 0)); + let mut other = one.clone(); + other.positions.insert(1, EntryId { ledger_id: 5, entry_id: 6, ..entry(-1, 0) }); + assert_eq!(one, other); + let state = RandomState::new(); + assert_eq!(state.hash_one(&one), state.hash_one(&other)); } #[test] diff --git a/crates/apache-pulsar-testkit/tests/producer.rs b/crates/apache-pulsar-testkit/tests/producer.rs index 2c116bb..58cc02a 100644 --- a/crates/apache-pulsar-testkit/tests/producer.rs +++ b/crates/apache-pulsar-testkit/tests/producer.rs @@ -71,6 +71,20 @@ fn values_in(harness: &Harness, segment: u64) -> Vec { harness.world.stored_in(TOPIC, segment).iter().map(|s| String::from_utf8(s.value.to_vec()).unwrap()).collect() } +/// How many entries were written to the producers of `segment`, whether the world stored them, holds them or +/// ignored them. +fn sends_to(harness: &Harness, segment: u64) -> usize { + let name = format!("p-seg-{segment}"); + let producers: Vec = harness + .world + .received(Type::PRODUCER) + .iter() + .filter(|c| c.producer.producer_name.as_deref() == Some(name.as_str())) + .map(|c| c.producer.producer_id) + .collect(); + harness.world.received(Type::SEND).iter().filter(|c| producers.contains(&c.send.producer_id)).count() +} + #[test] fn sends_a_stamped_batch_of_one_per_message() { let mut h = Harness::new(world(1), TOPIC, options()); @@ -189,6 +203,38 @@ fn only_the_keys_of_a_retiring_segment_are_held() { assert_eq!(h.segment_of(a1), h.segment_of(a2)); } +/// Java: `aLayoutAppliedWhileReleasingStopsTheRestOfTheBatch`. a1 and a2 are in flight on segment 0 when it is +/// terminated, and a3 is held behind them. Segment 0 splits: the three are written to its child, which splits too +/// while they are in flight there. They reach the grandchild, in order. +#[test] +fn messages_moved_to_a_child_that_splits_reach_the_grandchild_in_order() { + let mut h = Harness::new(world(1), TOPIC, options()); + // A key of segment 0, of its lower child, and of that child's lower child. + let a = key_in(0, 0x3fff, 0); + h.send(Some(&a), "a0"); + h.world.hold_sends = true; + let a1 = h.send(Some(&a), "a1"); + let a2 = h.send(Some(&a), "a2"); + h.world.terminate(TOPIC, 0); + // The producer registers again, is refused, and parks a1 and a2. + h.run_until(Duration::from_secs(5), |h| h.registrations[&0] == 2); + let a3 = h.send(Some(&a), "a3"); + assert_eq!(h.producer.sends_parked_or_held(), 3, "a1 and a2 parked, a3 held"); + let (child, _) = h.world.split(TOPIC, 0); + h.pump(); + assert_eq!(sends_to(&h, child), 3, "a1, a2 and a3 are in flight on the child"); + let (grandchild, _) = h.world.split(TOPIC, child); + h.pump(); + // What was written to the closed producers of segment 0 and of the child is ignored. + h.world.hold_sends = false; + h.world.release_sends(); + h.run_until(Duration::from_secs(5), |h| h.producer.outstanding() == 0); + assert_eq!(values_in(&h, 0), ["a0"]); + assert!(values_in(&h, child).is_empty()); + assert_eq!(values_in(&h, grandchild), ["a1", "a2", "a3"]); + assert_eq!([a1, a2, a3].map(|s| h.segment_of(s)), [grandchild; 3]); +} + /// Java: `V5ProducerLayoutChangeOrderingTest`, on the simulated broker: many keys, a split mid-stream, every key in /// call order. #[test] diff --git a/crates/apache-pulsar-testkit/tests/producer_edges.rs b/crates/apache-pulsar-testkit/tests/producer_edges.rs index 0c6d956..dcc8828 100644 --- a/crates/apache-pulsar-testkit/tests/producer_edges.rs +++ b/crates/apache-pulsar-testkit/tests/producer_edges.rs @@ -304,6 +304,19 @@ fn refused_credentials_are_retried_once_registered() { ); } +/// Java: `V5AuthErrorTest.testProduceNotAuthorized`, its exclusive producer. An exclusive producer registers on every +/// segment at create: a segment refusing it for authorization fails the create with the refusal, and the producer +/// closes. A shared producer's messages fail instead (`registration_failures`). +#[test] +fn an_exclusive_create_refused_for_authorization_fails() { + let mut t = Test::new(ProducerAccessMode::Exclusive, one_segment()); + let generation = Test::connects(&t.actions())[0].1; + let denied = RegisterError::Server { error: ServerError::AuthorizationError, message: "no".into() }; + t.producer.on_register_failed(0, generation, denied, t.now); + let refused = SendError::Server { error: ServerError::AuthorizationError, message: "no".into() }; + assert_eq!(t.actions(), [Action::Created(Err(refused)), Action::Closed]); +} + #[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/producer_tests.rs b/crates/apache-pulsar/src/producer_tests.rs index 7d23408..21e2008 100644 --- a/crates/apache-pulsar/src/producer_tests.rs +++ b/crates/apache-pulsar/src/producer_tests.rs @@ -21,11 +21,12 @@ //! the producer task, its layout watch, registrations, pushes, timers, the memory limit, the two client models, //! and the send-order promise of the rustdoc. -use std::cell::RefCell; -use std::collections::{BTreeMap, HashMap}; +use std::cell::{Cell, RefCell}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::future::poll_fn; use std::pin::Pin; use std::rc::Rc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::task::{Poll, Waker}; use std::time::Duration; @@ -45,7 +46,11 @@ use futures_util::io::{AsyncRead, AsyncWrite}; use futures_util::stream::{FuturesOrdered, StreamExt}; use crate::error::ErrorKind; -use crate::{BatchingPolicy, CompressionPolicy, CompressionType, ProducerAccessMode, PulsarClient, Schema, local}; +use crate::memory::PER_MESSAGE_OVERHEAD; +use crate::{ + BatchingPolicy, CompressionPolicy, CompressionType, ProducerAccessMode, PulsarClient, Schema, + SubscriptionInitialPosition, local, +}; pub(crate) const TOPIC: &str = "topic://acme/orders/events"; @@ -54,6 +59,8 @@ pub(crate) struct WorldServer { address: HostPort, pub(crate) world: Rc>, wakers: Rc>>, + /// While set, what the world sends waits: [`WorldServer::hold_output`]. + held: Rc>, _task: JoinHandle<()>, } @@ -65,17 +72,18 @@ impl WorldServer { world.lookup = LookupAnswer::Connect { broker: address.clone(), proxy: false }; let world = Rc::new(RefCell::new(world)); let wakers: Rc>> = Rc::default(); + let held: Rc> = Rc::default(); let task = { - let (world, wakers) = (world.clone(), wakers.clone()); + let (world, wakers, held) = (world.clone(), wakers.clone(), held.clone()); compio::runtime::spawn(async move { let mut connections = Vec::new(); loop { let Ok((tcp, _)) = listener.accept().await else { return }; - connections.push(compio::runtime::spawn(serve(tcp, world.clone(), wakers.clone()))); + connections.push(compio::runtime::spawn(serve(tcp, world.clone(), wakers.clone(), held.clone()))); } }) }; - Self { address, world, wakers, _task: task } + Self { address, world, wakers, held, _task: task } } pub(crate) fn url(&self) -> String { @@ -94,10 +102,23 @@ impl WorldServer { pub(crate) fn received(&self, kind: Type) -> usize { self.world.borrow().received(kind).len() } + + /// Holds what the world sends, on every connection, or lets it go: a broker slow to answer. The world still + /// takes what the clients write meanwhile. + pub(crate) fn hold_output(&self, hold: bool) { + self.held.set(hold); + self.with(|_| ()); + } } -/// Serves one connection: what the client writes goes to the world, what the world has for it goes out. -async fn serve(tcp: TcpStream, world: Rc>, wakers: Rc>>) { +/// Serves one connection: what the client writes goes to the world, what the world has for it goes out, unless +/// `held`. +async fn serve( + tcp: TcpStream, + world: Rc>, + wakers: Rc>>, + held: Rc>, +) { let conn = world.borrow_mut().connect(); let mut stream = Box::pin(AsyncStream::new(tcp)); let mut read_buf = vec![0; 64 * 1024]; @@ -128,7 +149,7 @@ async fn serve(tcp: TcpStream, world: Rc>, wakers: Rc, received: &AtomicUsize) -> Vec { + let deadline = std::time::Instant::now() + Duration::from_secs(10); + let mut mine = Vec::new(); + while received.load(Ordering::Acquire) < PRODUCERS * MESSAGES { + assert!(std::time::Instant::now() < deadline, "timed out waiting for the messages"); + if let Some(message) = consumer.receive_timeout(Duration::from_millis(10)).await.unwrap() { + consumer.acknowledge(message.id()).await.unwrap(); + mine.push(message.value().unwrap()); + received.fetch_add(1, Ordering::AcqRel); + } + } + mine + } + + let rt = compio::runtime::Runtime::new().unwrap(); + let (server, url) = rt.block_on(async { + let server = WorldServer::start(world(4)).await; + let url = server.url(); + (server, url) + }); + // The server runs on this thread's runtime, polled while the test waits on it. + let worker = std::thread::spawn(move || { + futures_executor::block_on(async { + let client = PulsarClient::builder().service_url(url).event_loops(2).build().await.unwrap(); + // All subscribed before anything is sent. + let mut consumers = Vec::new(); + for _ in 0..3 { + let builder = client.new_queue_consumer(Schema::string()).topic(TOPIC).subscription_name(SUB); + let builder = builder.subscription_initial_position(SubscriptionInitialPosition::Earliest); + consumers.push(builder.subscribe().await.unwrap()); + } + let received = AtomicUsize::new(0); + let got: Vec> = std::thread::scope(|threads| { + for p in 0..PRODUCERS { + let client = &client; + threads.spawn(move || futures_executor::block_on(produce(client, p))); + } + let receivers: Vec<_> = consumers + .iter() + .map(|consumer| { + let received = &received; + threads.spawn(move || futures_executor::block_on(consume(consumer, received))) + }) + .collect(); + receivers.into_iter().map(|receiver| receiver.join().unwrap()).collect() + }); + // A close sends the acks still waiting. + for consumer in &consumers { + consumer.close().await.unwrap(); + } + client.close().await.unwrap(); + got + }) + }); + rt.block_on(async { + while !worker.is_finished() { + compio::time::sleep(Duration::from_millis(5)).await; + } + }); + let got = worker.join().unwrap(); + let counts: Vec = got.iter().map(Vec::len).collect(); + assert!(counts.iter().all(|&count| count > 0), "a consumer got nothing: {counts:?}"); + let mut received: Vec = got.into_iter().flatten().collect(); + received.sort(); + let mut sent: Vec = (0..PRODUCERS).flat_map(|p| (0..MESSAGES).map(move |i| format!("p{p}-m{i}"))).collect(); + sent.sort(); + assert_eq!(received, sent); + let world = server.world.borrow(); + for segment in 0..4 { + assert!(!world.stored_in(TOPIC, segment).is_empty(), "segment {segment} got nothing"); + assert_eq!(world.backlog(TOPIC, segment, SUB), 0, "segment {segment} has messages not acknowledged"); + } +} + #[test] fn the_blocking_api_sends_from_a_plain_thread() { let rt = compio::runtime::Runtime::new().unwrap(); @@ -802,6 +966,90 @@ fn sends_wait_for_room_at_the_memory_limit() { }); } +/// Java: `cancelledSendsGiveTheirReservationBackOnceDropped`. Unlike Java's, a send dropped after its first poll isn't +/// recalled: its message is stored, and keeps its room under the memory limit until its receipt comes, then gives it +/// back. +#[test] +fn dropped_sends_keep_their_room_until_they_complete() { + run(async { + let server = WorldServer::start(world(1)).await; + let client = local_client(&server).await; + let producer = client + .new_producer(Schema::bytes()) + .topic(TOPIC) + .batching_policy(BatchingPolicy::disabled()) + .create() + .await + .unwrap(); + producer.send(vec![0; 100]).await.unwrap(); + server.with(|w| w.hold_receipts = true); + for _ in 0..10 { + // Queued at its first poll, then dropped. + assert!(producer.send(vec![0; 100]).now_or_never().is_none(), "the receipts are held"); + } + let room = 10 * (100 + PER_MESSAGE_OVERHEAD); + assert_eq!(client.memory().used(), room); + wait_until("the dropped sends are stored", || server.world.borrow().messages(TOPIC).len() == 11).await; + assert_eq!(client.memory().used(), room, "their room goes back with their receipts"); + server.with(|w| { + w.hold_receipts = false; + w.release_receipts(); + }); + wait_until("the memory is released", || client.memory().used() == 0).await; + producer.send(vec![0; 100]).await.unwrap(); + assert_eq!(client.memory().used(), 0); + client.close().await.unwrap(); + }); +} + +/// Java: `retriesAcrossASegmentSplitKeepTheAccountingBalanced`. The segment splits while sends are in flight on it, +/// and more wait for room at the memory limit: those in flight are written again to its children, every send goes +/// through, and the memory comes back. +#[test] +fn sends_waiting_for_room_go_through_a_split_and_give_it_back() { + run(async { + let server = WorldServer::start(world(1)).await; + let client = + local::PulsarClient::builder().service_url(server.url()).memory_limit(8 * 1024).build().await.unwrap(); + let producer = client + .new_producer(Schema::bytes()) + .topic(TOPIC) + .batching_policy(BatchingPolicy::disabled()) + .create() + .await + .unwrap(); + for _ in 0..20 { + producer.send(vec![7; 1000]).await.unwrap(); + } + // The broker holds what is written next. About 2 KiB each: a handful find room, and are in flight on the + // parent; the rest wait. + server.with(|w| w.hold_sends = true); + let mut sends = futures_util::stream::iter(0..200).map(|_| producer.send(vec![7; 1000])).buffered(64); + assert!(sends.next().now_or_never().is_none(), "the sends are held"); + assert!(client.memory().used() > 8 * 1024, "the limit is reached"); + let in_flight = (client.memory().used() / (1000 + PER_MESSAGE_OVERHEAD)) as usize; + wait_until("the sends with room are written", || server.received(Type::SEND) == 20 + in_flight).await; + server.with(|w| { + w.split(TOPIC, 0); + w.hold_sends = false; + w.release_sends(); + }); + let mut segments = BTreeSet::new(); + let drained = compio::time::timeout(Duration::from_secs(10), async { + while let Some(sent) = sends.next().await { + segments.insert(MessageIdSegment::of(&sent.unwrap())); + } + }); + drained.await.expect("the sends did not go through"); + // The sends from the hold on are all on the children; the parent has what came before. + assert_eq!(segments, BTreeSet::from([1, 2])); + assert_eq!(server.world.borrow().stored_in(TOPIC, 0).len(), 20); + assert_eq!(server.world.borrow().messages(TOPIC).len(), 220); + wait_until("the memory is released", || client.memory().used() == 0).await; + client.close().await.unwrap(); + }); +} + /// Every field of a message, and of the producer, reaches the wire as Java writes it. #[test] fn every_message_field_reaches_the_wire() { @@ -909,6 +1157,33 @@ fn a_message_above_the_brokers_limit_fails() { }); } +/// Java: `V5AuthErrorTest.testLookupNotAuthorized`, the producer's part, and the exclusive producer of its +/// `testProduceNotAuthorized`. A lookup the broker refuses fails the create, with the broker's category: the topic's, +/// which the layout watch starts with, and a segment's, which an exclusive producer registers on at create. +#[test] +fn a_refused_lookup_fails_create() { + run(async { + let server = WorldServer::start(world(1)).await; + let refused = || LookupAnswer::Fail { + error: apache_pulsar_protocol::proto::ServerError::AuthorizationError, + message: "not you".into(), + }; + let allowed = server.with(|w| std::mem::replace(&mut w.lookup, refused())); + let client = local_client(&server).await; + let error = client.new_producer(Schema::bytes()).topic(TOPIC).create().await.unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Authorization, "{error}"); + assert_eq!(server.received(Type::SCALABLE_TOPIC_LOOKUP), 0, "the watch opened no session"); + // With the topic's watch open, only the segment is looked up. + server.with(|w| w.lookup = allowed); + let _shared = client.new_producer(Schema::bytes()).topic(TOPIC).create().await.unwrap(); + server.with(|w| w.lookup = refused()); + let exclusive = client.new_producer(Schema::bytes()).topic(TOPIC).access_mode(ProducerAccessMode::Exclusive); + let error = exclusive.create().await.unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Authorization, "{error}"); + client.close().await.unwrap(); + }); +} + /// A lookup the broker refuses fails the sends routed to the segment, with the broker's category. #[test] fn a_refused_segment_lookup_fails_the_send() {