Skip to main content

kafka_client_engine/transaction/initialization/
send_observer.rs

1//! Runtime-neutral observation of one accepted transactional record send.
2
3use std::{
4    fmt,
5    future::Future,
6    pin::Pin,
7    sync::Arc,
8    task::{Context, Poll},
9};
10
11use kafka_client_core::{TransactionEpoch, TransactionSendId};
12
13use crate::{
14    completion::{CompletionObserver, CompletionObserverError},
15    transaction::send::TransactionSendTerminal,
16};
17
18use super::{TransactionSendOutcome, TransactionToken, send_outcome::translate_send_terminal};
19
20/// Sole named observer for one accepted transactional record send.
21#[must_use = "dropping abandons observation without cancelling the accepted send"]
22pub struct TransactionSendObserver<'send, 'owner> {
23    inner: CompletionObserver<TransactionSendTerminal>,
24    _transaction: &'send mut TransactionToken<'owner>,
25    epoch: TransactionEpoch,
26    send_id: TransactionSendId,
27    topic: Option<Arc<str>>,
28    partition: Option<i32>,
29}
30
31impl<'send, 'owner> TransactionSendObserver<'send, 'owner> {
32    pub(super) const fn new(
33        inner: CompletionObserver<TransactionSendTerminal>,
34        transaction: &'send mut TransactionToken<'owner>,
35        epoch: TransactionEpoch,
36        send_id: TransactionSendId,
37        topic: Arc<str>,
38        partition: Option<i32>,
39    ) -> Self {
40        Self {
41            inner,
42            _transaction: transaction,
43            epoch,
44            send_id,
45            topic: Some(topic),
46            partition,
47        }
48    }
49
50    /// Blocks on the same bounded terminal cell used by [`Future::poll`].
51    pub fn wait(mut self) -> Result<TransactionSendOutcome, TransactionSendObserverError> {
52        let terminal = self.inner.wait().map_err(observer_error)?;
53        let topic = self
54            .topic
55            .take()
56            .ok_or(TransactionSendObserverError::AlreadyObserved)?;
57        translate_send_terminal(terminal, self.epoch, self.send_id, topic, self.partition)
58            .ok_or(TransactionSendObserverError::InternalInvariant)
59    }
60}
61
62impl Future for TransactionSendObserver<'_, '_> {
63    type Output = Result<TransactionSendOutcome, TransactionSendObserverError>;
64
65    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
66        let this = self.get_mut();
67        match Pin::new(&mut this.inner).poll(context) {
68            Poll::Ready(Ok(terminal)) => {
69                let Some(topic) = this.topic.take() else {
70                    return Poll::Ready(Err(TransactionSendObserverError::AlreadyObserved));
71                };
72                Poll::Ready(
73                    translate_send_terminal(
74                        terminal,
75                        this.epoch,
76                        this.send_id,
77                        topic,
78                        this.partition,
79                    )
80                    .ok_or(TransactionSendObserverError::InternalInvariant),
81                )
82            }
83            Poll::Ready(Err(error)) => Poll::Ready(Err(observer_error(error))),
84            Poll::Pending => Poll::Pending,
85        }
86    }
87}
88
89impl fmt::Debug for TransactionSendObserver<'_, '_> {
90    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
91        formatter
92            .debug_struct("TransactionSendObserver")
93            .finish_non_exhaustive()
94    }
95}
96
97/// Failure to observe or correlate one accepted transactional send.
98#[derive(Clone, Copy, Debug, Eq, PartialEq)]
99pub enum TransactionSendObserverError {
100    /// This linear observer already consumed its terminal.
101    AlreadyObserved,
102    /// The bounded completion generation is no longer live.
103    Stale,
104    /// The terminal did not match the exact accepted transaction and send.
105    InternalInvariant,
106}
107
108impl fmt::Display for TransactionSendObserverError {
109    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
110        formatter.write_str(match self {
111            Self::AlreadyObserved => "transactional send was already observed",
112            Self::Stale => "transactional send observer is stale",
113            Self::InternalInvariant => {
114                "transactional send terminal violated its accepted correlation"
115            }
116        })
117    }
118}
119
120impl std::error::Error for TransactionSendObserverError {}
121
122const fn observer_error(error: CompletionObserverError) -> TransactionSendObserverError {
123    match error {
124        CompletionObserverError::AlreadyObserved => TransactionSendObserverError::AlreadyObserved,
125        CompletionObserverError::Stale => TransactionSendObserverError::Stale,
126    }
127}