Skip to main content

kafka_client_engine/producer/boundary/
capture.rs

1//! Linear public-boundary time capture retained across record conversion.
2
3use std::{
4    fmt,
5    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
6};
7
8use crate::clock::{DeadlineCapture, MonotonicClock};
9
10/// Per-call producer admission options captured before conversion or validation.
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub struct ProducerSendOptions {
13    delivery_timeout: Duration,
14}
15
16impl ProducerSendOptions {
17    /// Creates options with one end-to-end delivery timeout.
18    pub const fn new(delivery_timeout: Duration) -> Self {
19        Self { delivery_timeout }
20    }
21
22    /// Returns the end-to-end delivery timeout.
23    pub const fn delivery_timeout(self) -> Duration {
24        self.delivery_timeout
25    }
26}
27
28/// Stable reason the engine could not capture a producer call boundary.
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30pub enum ProducerSendCaptureErrorKind {
31    /// The monotonic deadline cannot be represented.
32    DeadlineUnrepresentable,
33    /// The boundary Unix timestamp cannot be represented.
34    TimestampUnrepresentable,
35}
36
37/// Failure before producer record ownership crosses into engine conversion.
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39pub struct ProducerSendCaptureError {
40    kind: ProducerSendCaptureErrorKind,
41}
42
43impl ProducerSendCaptureError {
44    /// Returns the stable boundary-capture failure category.
45    pub const fn kind(self) -> ProducerSendCaptureErrorKind {
46        self.kind
47    }
48
49    const fn new(kind: ProducerSendCaptureErrorKind) -> Self {
50        Self { kind }
51    }
52}
53
54impl fmt::Display for ProducerSendCaptureError {
55    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
56        formatter.write_str(match self.kind {
57            ProducerSendCaptureErrorKind::DeadlineUnrepresentable => {
58                "producer delivery deadline cannot be represented"
59            }
60            ProducerSendCaptureErrorKind::TimestampUnrepresentable => {
61                "producer boundary timestamp cannot be represented"
62            }
63        })
64    }
65}
66
67impl std::error::Error for ProducerSendCaptureError {}
68
69/// One non-cloneable producer call boundary consumed by one admission attempt.
70#[must_use = "a captured producer boundary must be consumed by one admission path"]
71#[derive(Debug)]
72pub struct ProducerSendCapture {
73    deadline: DeadlineCapture,
74    default_timestamp_ms: i64,
75}
76
77impl ProducerSendCapture {
78    pub(super) fn capture(
79        clock: &MonotonicClock,
80        options: ProducerSendOptions,
81    ) -> Result<Self, ProducerSendCaptureError> {
82        let deadline = clock
83            .capture_deadline_after(options.delivery_timeout())
84            .map_err(|_error| {
85                ProducerSendCaptureError::new(ProducerSendCaptureErrorKind::DeadlineUnrepresentable)
86            })?;
87        let Some(default_timestamp_ms) = unix_timestamp_milliseconds() else {
88            return Err(ProducerSendCaptureError::new(
89                ProducerSendCaptureErrorKind::TimestampUnrepresentable,
90            ));
91        };
92        Ok(Self {
93            deadline,
94            default_timestamp_ms,
95        })
96    }
97
98    pub(crate) fn capture_transaction(
99        clock: &MonotonicClock,
100        timeout: Duration,
101    ) -> Result<Self, ProducerSendCaptureError> {
102        if timeout.is_zero() {
103            return Err(ProducerSendCaptureError::new(
104                ProducerSendCaptureErrorKind::DeadlineUnrepresentable,
105            ));
106        }
107        Self::capture(clock, ProducerSendOptions::new(timeout))
108    }
109
110    /// Returns the original absolute monotonic deadline reserved for driver handoff.
111    pub const fn absolute_deadline(&self) -> Instant {
112        self.deadline.operation_deadline().transport()
113    }
114
115    /// Returns the create timestamp captured at the same public call boundary.
116    ///
117    /// Facades retain this scalar so a successful `CreateTime` response can use
118    /// the exact timestamp encoded into the record when Kafka supplies no log
119    /// append timestamp.
120    pub const fn default_timestamp_milliseconds(&self) -> i64 {
121        self.default_timestamp_ms
122    }
123
124    pub(crate) const fn into_parts(self) -> (DeadlineCapture, i64) {
125        (self.deadline, self.default_timestamp_ms)
126    }
127}
128
129/// One non-cloneable batch call boundary shared by every record in that call.
130#[must_use = "a captured producer batch boundary must be consumed by one admission path"]
131#[derive(Debug)]
132pub struct ProducerBatchSendCapture {
133    deadline: DeadlineCapture,
134    default_timestamp_ms: i64,
135}
136
137impl ProducerBatchSendCapture {
138    pub(super) fn capture(
139        clock: &MonotonicClock,
140        options: ProducerSendOptions,
141    ) -> Result<Self, ProducerSendCaptureError> {
142        let single = ProducerSendCapture::capture(clock, options)?;
143        let (deadline, default_timestamp_ms) = single.into_parts();
144        Ok(Self {
145            deadline,
146            default_timestamp_ms,
147        })
148    }
149
150    /// Returns the one absolute monotonic deadline shared by the batch.
151    pub const fn absolute_deadline(&self) -> Instant {
152        self.deadline.operation_deadline().transport()
153    }
154
155    /// Returns the create timestamp shared by records without explicit timestamps.
156    pub const fn default_timestamp_milliseconds(&self) -> i64 {
157        self.default_timestamp_ms
158    }
159
160    pub(super) const fn into_parts(self) -> (DeadlineCapture, i64) {
161        (self.deadline, self.default_timestamp_ms)
162    }
163}
164
165fn unix_timestamp_milliseconds() -> Option<i64> {
166    let elapsed = SystemTime::now().duration_since(UNIX_EPOCH).ok()?;
167    i64::try_from(elapsed.as_millis()).ok()
168}