| // Licensed to the Apache Software Foundation (ASF) under one | |
| // or more contributor license agreements. See the NOTICE file | |
| // distributed with this work for additional information | |
| // regarding copyright ownership. The ASF licenses this file | |
| // to you under the Apache License, Version 2.0 (the | |
| // "License"); you may not use this file except in compliance | |
| // with the License. You may obtain a copy of the License at | |
| // | |
| // http://www.apache.org/licenses/LICENSE-2.0 | |
| // | |
| // Unless required by applicable law or agreed to in writing, | |
| // software distributed under the License is distributed on an | |
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| // KIND, either express or implied. See the License for the | |
| // specific language governing permissions and limitations | |
| // under the License. | |
| //! The task that runs one consumer on its loop: a Queue consumer, or a Checkpoint consumer. | |
| //! | |
| //! It owns the sans-IO consumer ([`Machine`]) and its layout watch, and does what the consumer asks: it looks up and | |
| //! connects each segment, subscribes the segment's consumer there, sends its flows, acks and redelivery requests, | |
| //! asks for a segment's last message id, and closes it. It feeds back the outcome, the commands the brokers push for | |
| //! each segment's consumer, the layouts and the passing of time. It hands the application its messages as receives ask | |
| //! for them, in the order they asked, and takes its acks, its checkpoints and its close. Everything is polled from | |
| //! one future. | |
| //! | |
| //! A Checkpoint consumer in a group follows the assignments of the topic's controller instead of the layout: the task | |
| //! registers it there and leaves, as the Stream consumer's task does, and feeds it what the controller pushes. | |
| use std::cell::RefCell; | |
| use std::collections::{HashMap, VecDeque}; | |
| use std::future::{Future, poll_fn}; | |
| use std::pin::Pin; | |
| use std::rc::Rc; | |
| use std::task::{Context, Poll}; | |
| use std::time::Instant; | |
| use apache_pulsar_protocol::assignment::AssignmentSession; | |
| use apache_pulsar_protocol::checkpoint::Checkpoint; | |
| use apache_pulsar_protocol::checkpoint_consumer::{self, CheckpointConsumer}; | |
| use apache_pulsar_protocol::connection::IdKind; | |
| use apache_pulsar_protocol::entry::ReceivedMessage; | |
| use apache_pulsar_protocol::frame::{Frame, PayloadSection}; | |
| use apache_pulsar_protocol::layout::Layout; | |
| use apache_pulsar_protocol::message_id::{EntryId, MessageId}; | |
| use apache_pulsar_protocol::producer::RegisterError; | |
| use apache_pulsar_protocol::proto::base_command::Type; | |
| use apache_pulsar_protocol::proto::{BaseCommand, CommandCloseConsumer, CommandGetLastMessageId, CommandMessage}; | |
| use apache_pulsar_protocol::queue_consumer::{self, QueueConsumer}; | |
| use buffa::{EnumValue, MessageView}; | |
| use futures_channel::{mpsc, oneshot}; | |
| use futures_util::stream::{FuturesUnordered, SelectAll}; | |
| use futures_util::{Stream, StreamExt}; | |
| use super::stream_task::{Session, register}; | |
| use super::writers::{Delivered, Writers}; | |
| use crate::conn::{ConnHandle, Push}; | |
| use crate::error::{Error, ErrorKind, Result, server_error_kind}; | |
| use crate::local; | |
| use crate::watch::LayoutWatch; | |
| /// What a consumer handle asks of its task. | |
| pub(crate) enum Request { | |
| /// Up to `max` messages: answered once it has them, or at the deadline with what it has. | |
| Receive { | |
| max: usize, | |
| deadline: Option<Instant>, | |
| reply: oneshot::Sender<Delivery>, | |
| }, | |
| /// Messages a receive was answered with, and went away without taking: the next receives get them first. | |
| Return(Delivery), | |
| Ack { | |
| id: MessageId, | |
| reply: oneshot::Sender<Result<()>>, | |
| }, | |
| Nack { | |
| id: MessageId, | |
| }, | |
| /// A Checkpoint consumer's position. | |
| Checkpoint { | |
| reply: oneshot::Sender<Checkpoint>, | |
| }, | |
| /// `None` when the last handle dropped, or the client is closing: close in the background. | |
| Close { | |
| reply: Option<oneshot::Sender<Result<()>>>, | |
| }, | |
| } | |
| /// The answer to a receive: its messages, and where a Checkpoint consumer's checkpoint was for their segments before | |
| /// them, to go back to if they come back: per segment, with the attachment of its messages. | |
| pub(crate) struct Delivery { | |
| pub(crate) messages: Vec<Delivered>, | |
| undo: Vec<(i64, u64, EntryId)>, | |
| } | |
| /// The consumer a task runs. | |
| pub(crate) enum Machine { | |
| Queue(QueueConsumer), | |
| Checkpoint(CheckpointConsumer), | |
| } | |
| /// What a consumer asks of its task, whichever it is. | |
| enum Action { | |
| Register { generation: u64 }, | |
| Unregister { generation: u64 }, | |
| Connect { segment: u64, generation: u64, topic: String }, | |
| Send { segment: u64, command: Box<BaseCommand> }, | |
| CloseConsumer { segment: u64, generation: u64 }, | |
| GetLastMessageId { segment: u64, generation: u64 }, | |
| Subscribed(std::result::Result<(), RegisterError>), | |
| Closed, | |
| } | |
| impl Machine { | |
| pub(crate) fn topic(&self) -> &str { | |
| match self { | |
| Machine::Queue(queue) => queue.topic(), | |
| Machine::Checkpoint(reader) => reader.topic(), | |
| } | |
| } | |
| /// Whether it follows the topic's layouts: all but a Checkpoint consumer in a group, which follows its | |
| /// assignments. | |
| pub(crate) fn follows_layouts(&self) -> bool { | |
| match self { | |
| Machine::Queue(_) => true, | |
| Machine::Checkpoint(reader) => !reader.is_grouped(), | |
| } | |
| } | |
| fn is_closed(&self) -> bool { | |
| match self { | |
| Machine::Queue(queue) => queue.is_closed(), | |
| Machine::Checkpoint(reader) => reader.is_closed(), | |
| } | |
| } | |
| fn close(&mut self) { | |
| match self { | |
| Machine::Queue(queue) => queue.close(), | |
| Machine::Checkpoint(reader) => reader.close(), | |
| } | |
| } | |
| fn subscribe_command(&self, segment: u64) -> Option<BaseCommand> { | |
| match self { | |
| Machine::Queue(queue) => queue.subscribe_command(segment, 0), | |
| Machine::Checkpoint(reader) => reader.subscribe_command(segment, 0), | |
| } | |
| } | |
| fn on_layout(&mut self, layout: Rc<Layout>, now: Instant) { | |
| match self { | |
| Machine::Queue(queue) => queue.on_layout(layout, now), | |
| Machine::Checkpoint(reader) => reader.on_layout(layout, now), | |
| } | |
| } | |
| fn on_subscribed(&mut self, segment: u64, generation: u64, consumer_id: u64) { | |
| match self { | |
| Machine::Queue(queue) => queue.on_subscribed(segment, generation, consumer_id), | |
| Machine::Checkpoint(reader) => reader.on_subscribed(segment, generation, consumer_id), | |
| } | |
| } | |
| fn on_subscribe_failed(&mut self, segment: u64, generation: u64, error: RegisterError, now: Instant) { | |
| match self { | |
| Machine::Queue(queue) => queue.on_subscribe_failed(segment, generation, error, now), | |
| Machine::Checkpoint(reader) => reader.on_subscribe_failed(segment, generation, error, now), | |
| } | |
| } | |
| fn on_message(&mut self, segment: u64, generation: u64, message: &CommandMessage, section: &PayloadSection) { | |
| match self { | |
| Machine::Queue(queue) => queue.on_message(segment, generation, message, section), | |
| Machine::Checkpoint(reader) => reader.on_message(segment, generation, message, section), | |
| } | |
| } | |
| fn on_reached_end_of_topic(&mut self, segment: u64, generation: u64) { | |
| match self { | |
| Machine::Queue(queue) => queue.on_reached_end_of_topic(segment, generation), | |
| Machine::Checkpoint(reader) => reader.on_reached_end_of_topic(segment, generation), | |
| } | |
| } | |
| fn on_disconnected(&mut self, segment: u64, generation: u64, now: Instant) { | |
| match self { | |
| Machine::Queue(queue) => queue.on_disconnected(segment, generation, now), | |
| Machine::Checkpoint(reader) => reader.on_disconnected(segment, generation, now), | |
| } | |
| } | |
| fn on_closed(&mut self, segment: u64, generation: u64, now: Instant) { | |
| match self { | |
| Machine::Queue(queue) => queue.on_closed(segment, generation), | |
| Machine::Checkpoint(reader) => reader.on_closed(segment, generation, now), | |
| } | |
| } | |
| fn next_message(&mut self) -> Option<ReceivedMessage> { | |
| match self { | |
| Machine::Queue(queue) => queue.next_message(), | |
| Machine::Checkpoint(reader) => reader.next_message(), | |
| } | |
| } | |
| /// A message reached the application. Returns where a Checkpoint consumer's checkpoint was for its segment. | |
| fn deliver(&mut self, message: &ReceivedMessage) -> Option<EntryId> { | |
| match self { | |
| Machine::Queue(_) => None, | |
| Machine::Checkpoint(reader) => reader.deliver(message), | |
| } | |
| } | |
| fn poll_timeout(&self) -> Option<Instant> { | |
| match self { | |
| Machine::Queue(queue) => queue.poll_timeout(), | |
| Machine::Checkpoint(reader) => reader.poll_timeout(), | |
| } | |
| } | |
| fn handle_timeout(&mut self, now: Instant) { | |
| match self { | |
| Machine::Queue(queue) => queue.handle_timeout(now), | |
| Machine::Checkpoint(reader) => reader.handle_timeout(now), | |
| } | |
| } | |
| fn poll_action(&mut self) -> Option<Action> { | |
| match self { | |
| Machine::Queue(queue) => queue.poll_action().map(|action| match action { | |
| queue_consumer::Action::Connect { segment, generation, topic } => { | |
| Action::Connect { segment, generation, topic } | |
| } | |
| queue_consumer::Action::Send { segment, command } => Action::Send { segment, command }, | |
| queue_consumer::Action::CloseConsumer { segment, generation } => { | |
| Action::CloseConsumer { segment, generation } | |
| } | |
| queue_consumer::Action::Subscribed(result) => Action::Subscribed(result), | |
| queue_consumer::Action::Closed => Action::Closed, | |
| }), | |
| Machine::Checkpoint(reader) => reader.poll_action().map(|action| match action { | |
| checkpoint_consumer::Action::Register { generation } => Action::Register { generation }, | |
| checkpoint_consumer::Action::Unregister { generation } => Action::Unregister { generation }, | |
| checkpoint_consumer::Action::Connect { segment, generation, topic } => { | |
| Action::Connect { segment, generation, topic } | |
| } | |
| checkpoint_consumer::Action::Send { segment, command } => Action::Send { segment, command }, | |
| checkpoint_consumer::Action::CloseConsumer { segment, generation } => { | |
| Action::CloseConsumer { segment, generation } | |
| } | |
| checkpoint_consumer::Action::GetLastMessageId { segment, generation } => { | |
| Action::GetLastMessageId { segment, generation } | |
| } | |
| checkpoint_consumer::Action::Subscribed(result) => Action::Subscribed(result), | |
| checkpoint_consumer::Action::Closed => Action::Closed, | |
| }), | |
| } | |
| } | |
| } | |
| type Sleep = Pin<Box<dyn Future<Output = ()>>>; | |
| type Subscription = Pin<Box<dyn Future<Output = Subscribed>>>; | |
| type Registration = Pin<Box<dyn Future<Output = (u64, std::result::Result<Session, RegisterError>)>>>; | |
| type Ending = Pin<Box<dyn Future<Output = u64>>>; | |
| type Closing = Pin<Box<dyn Future<Output = (u64, u64)>>>; | |
| /// A last message id asked for a segment's subscription of a generation: the id, or `None` if the broker didn't give | |
| /// it. | |
| type Asking = Pin<Box<dyn Future<Output = (u64, u64, Option<EntryId>)>>>; | |
| type Pushes = Pin<Box<dyn Stream<Item = (u64, u64, Push)>>>; | |
| /// Where a subscribe in flight registered its consumer id, once it did. | |
| type Registering = Rc<RefCell<Option<(ConnHandle, u64)>>>; | |
| /// A subscribed consumer: its link, and the commands pushed for it. | |
| pub(super) type Linked = (Link, mpsc::UnboundedReceiver<Push>); | |
| /// The outcome of subscribing a segment's consumer. | |
| struct Subscribed { | |
| segment: u64, | |
| generation: u64, | |
| outcome: std::result::Result<Linked, RegisterError>, | |
| } | |
| /// A segment's consumer as registered on a connection. Dropping it unregisters the consumer id there. | |
| pub(super) struct Link { | |
| pub(super) generation: u64, | |
| pub(super) connection: ConnHandle, | |
| pub(super) consumer_id: u64, | |
| } | |
| impl Drop for Link { | |
| fn drop(&mut self) { | |
| self.connection.unregister(IdKind::Consumer, self.consumer_id); | |
| } | |
| } | |
| /// A receive waiting for its messages. | |
| struct Waiter { | |
| max: usize, | |
| deadline: Option<Instant>, | |
| got: Vec<Delivered>, | |
| reply: oneshot::Sender<Delivery>, | |
| } | |
| pub(crate) struct Task { | |
| machine: Machine, | |
| client: local::PulsarClient, | |
| /// The topic as the application named it, to find a group's controller. | |
| topic: String, | |
| /// The layouts, for a consumer that follows them ([`Machine::follows_layouts`]). | |
| watch: Option<LayoutWatch>, | |
| /// The client keeps a sender of its own, to close the consumer: the channel doesn't end while the task runs. | |
| requests: mpsc::UnboundedReceiver<Request>, | |
| /// A member's registrations with the controller, in flight. | |
| registrations: FuturesUnordered<Registration>, | |
| /// The last registration: its generation and link, kept after its connection closes until a newer one replaces | |
| /// it. | |
| session: Option<(u64, Link)>, | |
| session_pushes: SelectAll<Pushes>, | |
| /// Unsubscribes in flight. | |
| endings: FuturesUnordered<Ending>, | |
| links: HashMap<u64, Link>, | |
| subscriptions: FuturesUnordered<Subscription>, | |
| /// Subscribes in flight, and where they registered, once they did: to close them if the consumer goes before | |
| /// they complete. | |
| registering: HashMap<(u64, u64), Registering>, | |
| closes: FuturesUnordered<Closing>, | |
| asks: FuturesUnordered<Asking>, | |
| pushes: SelectAll<Pushes>, | |
| /// Receives, in the order they came. | |
| waiters: VecDeque<Waiter>, | |
| /// Messages given back by receives that went away, for the next ones, and messages waiting for their schema. | |
| returned: VecDeque<ReceivedMessage>, | |
| /// The schemas the messages were written with, for a consumer that decodes with them. | |
| writers: Writers, | |
| subscribed: Option<oneshot::Sender<Result<()>>>, | |
| close_replies: Vec<oneshot::Sender<Result<()>>>, | |
| closed: bool, | |
| timer: Option<(Instant, Sleep)>, | |
| } | |
| impl Task { | |
| pub(crate) fn new( | |
| machine: Machine, | |
| client: local::PulsarClient, | |
| topic: String, | |
| watch: Option<LayoutWatch>, | |
| requests: mpsc::UnboundedReceiver<Request>, | |
| subscribed: oneshot::Sender<Result<()>>, | |
| writers: Writers, | |
| ) -> Self { | |
| Self { | |
| machine, | |
| client, | |
| topic, | |
| watch, | |
| requests, | |
| registrations: FuturesUnordered::new(), | |
| session: None, | |
| session_pushes: SelectAll::new(), | |
| endings: FuturesUnordered::new(), | |
| links: HashMap::new(), | |
| subscriptions: FuturesUnordered::new(), | |
| registering: HashMap::new(), | |
| closes: FuturesUnordered::new(), | |
| asks: FuturesUnordered::new(), | |
| pushes: SelectAll::new(), | |
| waiters: VecDeque::new(), | |
| returned: VecDeque::new(), | |
| writers, | |
| subscribed: Some(subscribed), | |
| close_replies: Vec::new(), | |
| closed: false, | |
| timer: None, | |
| } | |
| } | |
| pub(crate) async fn run(mut self) { | |
| poll_fn(|cx| self.poll(cx)).await; | |
| // Requests that came in as the consumer closed fail as they drop: their senders see no answer coming. | |
| self.requests.close(); | |
| while self.requests.try_recv().is_ok() {} | |
| // Subscribes that never completed: close them, so that the broker doesn't keep a consumer nobody reads. | |
| // Dropping them unregisters their consumer ids. | |
| let pending: Vec<(ConnHandle, u64)> = | |
| self.registering.values().filter_map(|registered| registered.borrow().clone()).collect(); | |
| self.subscriptions = FuturesUnordered::new(); | |
| for (connection, consumer_id) in pending { | |
| let _ = connection.request(move |request_id| close_command(consumer_id, request_id)).await; | |
| } | |
| } | |
| fn poll(&mut self, cx: &mut Context<'_>) -> Poll<()> { | |
| loop { | |
| let mut progressed = false; | |
| progressed |= self.poll_requests(cx); | |
| progressed |= self.poll_layouts(cx); | |
| progressed |= self.poll_session(cx); | |
| progressed |= self.poll_subscriptions(cx); | |
| progressed |= self.poll_pushes(cx); | |
| progressed |= self.poll_closes(cx); | |
| progressed |= self.poll_asks(cx); | |
| // Before the timer: a receive whose time is up takes the messages in first. | |
| progressed |= self.serve(); | |
| // After serving, which may start a fetch. | |
| progressed |= self.writers.poll(cx); | |
| progressed |= self.poll_timer(cx); | |
| // An action may start a future (a subscribe, a close) that must be polled before going to sleep. | |
| progressed |= self.drain_actions(); | |
| if self.closed && self.closes.is_empty() { | |
| return Poll::Ready(()); | |
| } | |
| if !progressed { | |
| return Poll::Pending; | |
| } | |
| } | |
| } | |
| fn poll_requests(&mut self, cx: &mut Context<'_>) -> bool { | |
| let mut progressed = false; | |
| // Once closing, requests wait for the end of the task, which fails them. | |
| while !self.machine.is_closed() | |
| && let Poll::Ready(Some(request)) = self.requests.poll_next_unpin(cx) | |
| { | |
| progressed = true; | |
| let now = Instant::now(); | |
| match request { | |
| Request::Receive { max, deadline, reply } => { | |
| self.waiters.push_back(Waiter { max, deadline, got: Vec::new(), reply }); | |
| } | |
| Request::Return(delivery) => self.take_back(delivery), | |
| Request::Ack { id, reply } => { | |
| let Machine::Queue(queue) = &mut self.machine else { continue }; | |
| queue.acknowledge(&id, now); | |
| let _ = reply.send(Ok(())); | |
| } | |
| Request::Nack { id } => { | |
| let Machine::Queue(queue) = &mut self.machine else { continue }; | |
| queue.negative_acknowledge(&id, now); | |
| } | |
| Request::Checkpoint { reply } => { | |
| let Machine::Checkpoint(reader) = &self.machine else { continue }; | |
| let _ = reply.send(reader.checkpoint()); | |
| } | |
| Request::Close { reply } => { | |
| self.close_replies.extend(reply); | |
| self.machine.close(); | |
| } | |
| } | |
| } | |
| progressed | |
| } | |
| fn poll_layouts(&mut self, cx: &mut Context<'_>) -> bool { | |
| let Some(watch) = &mut self.watch else { return false }; | |
| let mut progressed = false; | |
| while let Poll::Ready(Some(layout)) = watch.updates.poll_next_unpin(cx) { | |
| progressed = true; | |
| self.machine.on_layout(layout, Instant::now()); | |
| } | |
| progressed | |
| } | |
| /// A member's registrations, what the controller pushes to it, and the ends of its unsubscribes. | |
| fn poll_session(&mut self, cx: &mut Context<'_>) -> bool { | |
| let Machine::Checkpoint(reader) = &mut self.machine else { return false }; | |
| let mut progressed = false; | |
| while let Poll::Ready(Some((generation, outcome))) = self.registrations.poll_next_unpin(cx) { | |
| progressed = true; | |
| match outcome { | |
| Ok(Session { link, pushes, assignment }) => { | |
| // Its pushes, from here: none of them goes before the answer. | |
| self.session_pushes.push(Box::pin(pushes.map(move |push| (0, generation, push)))); | |
| self.session = Some((generation, link)); | |
| reader.on_registered(generation, &assignment, Instant::now()); | |
| } | |
| Err(error) => reader.on_register_failed(generation, error, Instant::now()), | |
| } | |
| } | |
| while let Poll::Ready(Some((_, generation, push))) = self.session_pushes.poll_next_unpin(cx) { | |
| progressed = true; | |
| let now = Instant::now(); | |
| let update = match &push { | |
| Push::Command(frame) => frame.command_view().ok().and_then(|command| { | |
| let update = command.scalableTopicAssignmentUpdate.as_option()?; | |
| update.assignment.as_option()?.to_owned_message().ok() | |
| }), | |
| Push::Closed(_) => None, | |
| }; | |
| match update { | |
| Some(assignment) => reader.on_assignment(generation, &assignment, now), | |
| // The connection closed. The link stays until a new registration replaces it: an unsubscribe asked | |
| // meanwhile fails on it, and is done all the same. | |
| None => reader.on_session_lost(generation, now), | |
| } | |
| } | |
| while let Poll::Ready(Some(generation)) = self.endings.poll_next_unpin(cx) { | |
| progressed = true; | |
| reader.on_unregistered(generation); | |
| } | |
| progressed | |
| } | |
| fn poll_subscriptions(&mut self, cx: &mut Context<'_>) -> bool { | |
| let mut progressed = false; | |
| while let Poll::Ready(Some(subscribed)) = self.subscriptions.poll_next_unpin(cx) { | |
| progressed = true; | |
| let Subscribed { segment, generation, outcome } = subscribed; | |
| self.registering.remove(&(segment, generation)); | |
| match outcome { | |
| Ok((link, pushes)) => { | |
| let consumer_id = link.consumer_id; | |
| self.pushes.push(Box::pin(pushes.map(move |push| (segment, generation, push)))); | |
| self.links.insert(segment, link); | |
| self.machine.on_subscribed(segment, generation, consumer_id); | |
| } | |
| Err(error) => self.machine.on_subscribe_failed(segment, generation, error, Instant::now()), | |
| } | |
| } | |
| progressed | |
| } | |
| fn poll_pushes(&mut self, cx: &mut Context<'_>) -> bool { | |
| let mut progressed = false; | |
| while let Poll::Ready(Some((segment, generation, push))) = self.pushes.poll_next_unpin(cx) { | |
| progressed = true; | |
| match push { | |
| Push::Command(frame) => self.on_push(segment, generation, &frame), | |
| // The connection closed, and the consumer with it. | |
| Push::Closed(_) => self.unlink(segment, generation), | |
| } | |
| } | |
| progressed | |
| } | |
| fn on_push(&mut self, segment: u64, generation: u64, frame: &Frame) { | |
| let Ok(command) = frame.command_view() else { return }; | |
| let Ok(command) = command.to_owned_message() else { return }; | |
| match command.r#type { | |
| EnumValue::Known(Type::MESSAGE) => { | |
| // A message comes with its payload: the connection decodes it. | |
| let Some(section) = &frame.payload else { return }; | |
| self.machine.on_message(segment, generation, &command.message, section); | |
| } | |
| EnumValue::Known(Type::REACHED_END_OF_TOPIC) => self.machine.on_reached_end_of_topic(segment, generation), | |
| // The broker closed the consumer (an unload, a deleted segment) or moved the topic: the only other | |
| // commands it pushes to a Shared consumer or a reader. | |
| _ => self.unlink(segment, generation), | |
| } | |
| } | |
| /// The segment's consumer of `generation` is gone from its connection: forget its link, if it is still the | |
| /// current one, and tell the consumer. | |
| fn unlink(&mut self, segment: u64, generation: u64) { | |
| self.links.retain(|&s, link| (s, link.generation) != (segment, generation)); | |
| self.machine.on_disconnected(segment, generation, Instant::now()); | |
| } | |
| fn poll_closes(&mut self, cx: &mut Context<'_>) -> bool { | |
| let mut progressed = false; | |
| while let Poll::Ready(Some((segment, generation))) = self.closes.poll_next_unpin(cx) { | |
| progressed = true; | |
| self.machine.on_closed(segment, generation, Instant::now()); | |
| } | |
| progressed | |
| } | |
| fn poll_asks(&mut self, cx: &mut Context<'_>) -> bool { | |
| let mut progressed = false; | |
| while let Poll::Ready(Some((segment, generation, id))) = self.asks.poll_next_unpin(cx) { | |
| progressed = true; | |
| // Only a Checkpoint consumer asks. | |
| let Machine::Checkpoint(reader) = &mut self.machine else { continue }; | |
| match id { | |
| Some(id) => reader.on_last_message_id(segment, generation, id, Instant::now()), | |
| None => reader.on_last_message_id_failed(segment, generation, Instant::now()), | |
| } | |
| } | |
| progressed | |
| } | |
| fn poll_timer(&mut self, cx: &mut Context<'_>) -> bool { | |
| let receive = self.waiters.iter().filter_map(|waiter| waiter.deadline).min(); | |
| let Some(deadline) = self.machine.poll_timeout().into_iter().chain(receive).min() else { | |
| self.timer = None; | |
| return false; | |
| }; | |
| // A sleep only completes once its deadline has passed: either way, the deadline is reached. | |
| if deadline > Instant::now() && self.poll_sleep(deadline, cx).is_pending() { | |
| return false; | |
| } | |
| self.timer = None; | |
| let now = Instant::now(); | |
| self.machine.handle_timeout(now); | |
| // The receives whose time is up get what they have. | |
| let (due, waiting): (VecDeque<Waiter>, VecDeque<Waiter>) = std::mem::take(&mut self.waiters) | |
| .into_iter() | |
| .partition(|waiter| waiter.deadline.is_some_and(|deadline| deadline <= now)); | |
| self.waiters = waiting; | |
| for waiter in due { | |
| self.answer(waiter); | |
| } | |
| true | |
| } | |
| /// Polls the sleep until `deadline`, starting a new one when the deadline changed. | |
| fn poll_sleep(&mut self, deadline: Instant, cx: &mut Context<'_>) -> Poll<()> { | |
| if self.timer.as_ref().is_none_or(|(at, _)| *at != deadline) { | |
| self.timer = Some((deadline, Box::pin(compio::time::sleep_until(deadline)))); | |
| } | |
| let (_, sleep) = self.timer.as_mut().unwrap(); | |
| sleep.as_mut().poll(cx) | |
| } | |
| /// Hands the messages in to the receives, in the order they came: each takes what it asked for before the next | |
| /// gets any. A message is taken from the consumer only for a receive, so that the broker's permits follow what | |
| /// the application takes. | |
| fn serve(&mut self) -> bool { | |
| if self.machine.is_closed() { | |
| // The receives fail: their answer never comes. The broker delivers again the messages they had, and those | |
| // given back. | |
| self.waiters.clear(); | |
| self.returned.clear(); | |
| return false; | |
| } | |
| let mut progressed = false; | |
| while let Some(waiter) = self.waiters.front_mut() { | |
| // A receive that went away is answered at once: its answer comes back, with whatever it had. | |
| let gone = waiter.reply.is_canceled(); | |
| while !gone && waiter.got.len() < waiter.max { | |
| let Some(message) = self.returned.pop_front().or_else(|| self.machine.next_message()) else { break }; | |
| // A message whose schema is on its way waits for it, and the messages after it. | |
| let Some(writer) = self.writers.resolve(&message) else { | |
| self.returned.push_front(message); | |
| break; | |
| }; | |
| waiter.got.push((message, writer)); | |
| progressed = true; | |
| } | |
| if !gone && waiter.got.len() < waiter.max { | |
| break; | |
| } | |
| let waiter = self.waiters.pop_front().expect("the first receive"); | |
| self.answer(waiter); | |
| progressed = true; | |
| } | |
| progressed | |
| } | |
| /// Answers a receive: its messages reach the application. One that went away gives its messages back, for the | |
| /// next ones. | |
| fn answer(&mut self, waiter: Waiter) { | |
| let mut undo: Vec<(i64, u64, EntryId)> = Vec::new(); | |
| for (message, _) in &waiter.got { | |
| let segment = message.id.segment_id; | |
| if let Some(before) = self.machine.deliver(message) | |
| && !undo.iter().any(|(s, _, _)| *s == segment) | |
| { | |
| undo.push((segment, message.attachment, before)); | |
| } | |
| } | |
| if let Err(delivery) = waiter.reply.send(Delivery { messages: waiter.got, undo }) { | |
| self.take_back(delivery); | |
| } | |
| } | |
| /// Takes back messages that didn't reach the application, for the next receives. A Checkpoint consumer's | |
| /// checkpoint names what it named before them again. | |
| fn take_back(&mut self, delivery: Delivery) { | |
| for (segment, attachment, position) in delivery.undo { | |
| let Machine::Checkpoint(reader) = &mut self.machine else { break }; | |
| reader.rewind(segment, attachment, position); | |
| } | |
| for (message, _) in delivery.messages.into_iter().rev() { | |
| self.returned.push_front(message); | |
| } | |
| } | |
| fn drain_actions(&mut self) -> bool { | |
| let mut progressed = false; | |
| while let Some(action) = self.machine.poll_action() { | |
| progressed = true; | |
| match action { | |
| Action::Register { generation } => self.register(generation), | |
| Action::Unregister { generation } => self.unregister(generation), | |
| Action::Connect { segment, generation, topic } => self.connect(segment, generation, topic), | |
| Action::Send { segment, command } => self.send(segment, *command), | |
| Action::CloseConsumer { segment, generation } => self.close_consumer(segment, generation), | |
| Action::GetLastMessageId { segment, generation } => self.ask(segment, generation), | |
| Action::Subscribed(result) => { | |
| let subscribed = self.subscribed.take().expect("a consumer subscribes once"); | |
| // Nobody waits for it any more, as the subscribe was dropped: close it, before the broker | |
| // gives it messages that nobody takes. | |
| if subscribed.send(result.map_err(subscribe_error)).is_err() { | |
| self.machine.close(); | |
| } | |
| } | |
| Action::Closed => { | |
| self.closed = true; | |
| for reply in self.close_replies.drain(..) { | |
| let _ = reply.send(Ok(())); | |
| } | |
| } | |
| } | |
| } | |
| progressed | |
| } | |
| /// Registers a member of a group with the topic's controller. | |
| fn register(&mut self, generation: u64) { | |
| let Machine::Checkpoint(reader) = &self.machine else { return }; | |
| let Some(command) = reader.register_command(0) else { return }; | |
| let client = self.client.clone(); | |
| let topic = self.topic.clone(); | |
| self.registrations.push(Box::pin(async move { (generation, register(&client, &topic, command).await) })); | |
| } | |
| /// Leaves the controller's group on the registration's connection. | |
| fn unregister(&mut self, generation: u64) { | |
| let (_, link) = self.session.take().expect("the registration that unregisters"); | |
| self.endings.push(Box::pin(async move { | |
| let consumer_id = link.consumer_id; | |
| let command = move |request_id| { | |
| let mut command = AssignmentSession::unregister_command(consumer_id); | |
| command.scalableTopicUnsubscribe.get_or_insert_default().request_id = request_id; | |
| command | |
| }; | |
| // Best effort: on any failure, the controller's grace period takes over. | |
| let _ = link.connection.request(command).await; | |
| generation | |
| })); | |
| } | |
| fn connect(&mut self, segment: u64, generation: u64, topic: String) { | |
| let Some(command) = self.machine.subscribe_command(segment) else { return }; | |
| self.writers.connect(segment, &topic); | |
| let client = self.client.clone(); | |
| let registered = Rc::new(RefCell::new(None)); | |
| self.registering.insert((segment, generation), registered.clone()); | |
| self.subscriptions.push(Box::pin(async move { | |
| let outcome = subscribe(&client, &topic, generation, command, ®istered).await; | |
| Subscribed { segment, generation, outcome } | |
| })); | |
| } | |
| /// Sends a flow, an ack or a redelivery request on the segment consumer's connection. Without a link, the | |
| /// connection just went: the consumer heard it from the pushes. A connection that is going is noticed from the | |
| /// pushes too. | |
| fn send(&self, segment: u64, command: BaseCommand) { | |
| let Some(link) = self.links.get(&segment) else { return }; | |
| let _ = link.connection.send(command); | |
| } | |
| /// Asks for the segment's last message id on its reader's connection. Without a link, the connection just went: | |
| /// the consumer heard it from the pushes, and forgot what it asked. | |
| fn ask(&mut self, segment: u64, generation: u64) { | |
| let Some(link) = self.links.get(&segment) else { return }; | |
| let (connection, consumer_id) = (link.connection.clone(), link.consumer_id); | |
| self.asks.push(Box::pin(async move { | |
| let response = connection.request(move |request_id| last_message_id_command(consumer_id, request_id)).await; | |
| (segment, generation, response.ok().and_then(|frame| last_message_id(&frame))) | |
| })); | |
| } | |
| /// Closes the segment's consumer on the broker. Without a link, the connection just went: the consumer heard it | |
| /// from the pushes. | |
| fn close_consumer(&mut self, segment: u64, generation: u64) { | |
| let Some(link) = self.links.remove(&segment) else { return }; | |
| debug_assert_eq!(link.generation, generation); | |
| self.closes.push(Box::pin(async move { | |
| let consumer_id = link.consumer_id; | |
| let _ = link.connection.request(move |request_id| close_command(consumer_id, request_id)).await; | |
| (segment, generation) | |
| })); | |
| } | |
| } | |
| /// Looks up a segment's topic, connects, and subscribes a consumer there. | |
| pub(super) async fn subscribe( | |
| client: &local::PulsarClient, | |
| topic: &str, | |
| generation: u64, | |
| mut command: BaseCommand, | |
| registered: &RefCell<Option<(ConnHandle, u64)>>, | |
| ) -> std::result::Result<Linked, RegisterError> { | |
| let address = client.lookup(topic).await?; | |
| let connection = client.connection(&address).await?; | |
| let (consumer_id, pushes) = connection.register(IdKind::Consumer).await?; | |
| // From here, a failure unregisters the consumer id as the link drops. | |
| let link = Link { generation, connection, consumer_id }; | |
| command.subscribe.get_or_insert_default().consumer_id = consumer_id; | |
| *registered.borrow_mut() = Some((link.connection.clone(), consumer_id)); | |
| link.connection | |
| .request(move |request_id| { | |
| let mut command = command; | |
| command.subscribe.get_or_insert_default().request_id = request_id; | |
| command | |
| }) | |
| .await?; | |
| Ok((link, pushes)) | |
| } | |
| pub(super) fn close_command(consumer_id: u64, request_id: u64) -> BaseCommand { | |
| BaseCommand { | |
| r#type: Type::CLOSE_CONSUMER.into(), | |
| close_consumer: CommandCloseConsumer { consumer_id, request_id, ..Default::default() }.into(), | |
| ..Default::default() | |
| } | |
| } | |
| fn last_message_id_command(consumer_id: u64, request_id: u64) -> BaseCommand { | |
| BaseCommand { | |
| r#type: Type::GET_LAST_MESSAGE_ID.into(), | |
| getLastMessageId: CommandGetLastMessageId { consumer_id, request_id, ..Default::default() }.into(), | |
| ..Default::default() | |
| } | |
| } | |
| /// The last message id of a `CommandGetLastMessageIdResponse`. | |
| fn last_message_id(frame: &Frame) -> Option<EntryId> { | |
| let command = frame.command_view().ok()?.to_owned_message().ok()?; | |
| Some(EntryId::from_proto(&command.getLastMessageIdResponse.last_message_id)) | |
| } | |
| /// The public error for a subscribe that failed. | |
| pub(crate) fn subscribe_error(error: RegisterError) -> Error { | |
| match error { | |
| RegisterError::Server { error, message } => Error::new(server_error_kind(EnumValue::Known(error)), message), | |
| // Retried until the operation timeout. | |
| RegisterError::Unavailable(reason) => Error::new(ErrorKind::Timeout, reason), | |
| } | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use apache_pulsar_protocol::proto::ServerError; | |
| use super::*; | |
| #[test] | |
| fn subscribe_failures_map_to_kinds() { | |
| let refused = RegisterError::Server { error: ServerError::AuthorizationError, message: "no".into() }; | |
| assert_eq!(subscribe_error(refused).kind(), ErrorKind::Authorization); | |
| let unavailable = subscribe_error(RegisterError::Unavailable("no broker".into())); | |
| assert_eq!((unavailable.kind(), unavailable.to_string()), (ErrorKind::Timeout, "Timeout: no broker".into())); | |
| } | |
| } |