Skip to main content

xmtp_mls_streams/local_delivery/
types.rs

1use thiserror::Error;
2use xmtp_common::{ErrorCode, RetryableError, time::Duration};
3use xmtp_db::StorageError;
4
5pub use xmtp_db::delivery::DeliveryFilter as LocalDeliveryFilter;
6
7use xmtp_mls_core::policy::StreamPolicy;
8use xmtp_mls_engine::subscriptions::incoming::stream_api::RecoveryFailure;
9
10const LEASE_RENEWAL_DIVISOR: u32 = 3;
11
12/// Bounds local reads and maintains exclusive default-consumer ownership.
13#[derive(Debug, Clone, Copy)]
14pub(crate) struct LocalDeliveryConfig {
15    /// Maximum candidates fetched in one local read.
16    pub batch_size: u32,
17    /// Maximum candidate bytes, checked before message blobs are loaded.
18    pub max_bytes: u64,
19    /// Maximum wait before checking cross-process writes and missed local wakes.
20    pub poll_interval: Duration,
21    /// Time before another process can take over an unrenewed default consumer.
22    pub lease_duration: Duration,
23    /// Renewal interval; must be shorter than the lease duration.
24    pub renew_interval: Duration,
25}
26
27impl Default for LocalDeliveryConfig {
28    fn default() -> Self {
29        Self::from(&StreamPolicy::default())
30    }
31}
32
33impl From<&StreamPolicy> for LocalDeliveryConfig {
34    fn from(settings: &StreamPolicy) -> Self {
35        Self {
36            batch_size: settings.max_local_read_rows,
37            max_bytes: settings.max_local_read_bytes,
38            poll_interval: settings.active_database_poll_interval,
39            lease_duration: settings.default_consumer_lease_duration,
40            renew_interval: settings.default_consumer_lease_duration / LEASE_RENEWAL_DIVISOR,
41        }
42    }
43}
44
45impl LocalDeliveryConfig {
46    pub(super) fn validate(self) -> Result<(), LocalDeliveryError> {
47        if self.batch_size == 0
48            || self.max_bytes == 0
49            || self.poll_interval.is_zero()
50            || self.renew_interval.is_zero()
51            || self.renew_interval >= self.lease_duration
52        {
53            return Err(LocalDeliveryError::InvalidConfiguration);
54        }
55        self.lease_until(0)?;
56        Ok(())
57    }
58
59    pub(super) fn lease_until(self, now: i64) -> Result<i64, LocalDeliveryError> {
60        now.checked_add(self.lease_duration_ns()?)
61            .ok_or(LocalDeliveryError::InvalidConfiguration)
62    }
63
64    pub(super) fn lease_duration_ns(self) -> Result<i64, LocalDeliveryError> {
65        i64::try_from(self.lease_duration.as_nanos())
66            .map_err(|_| LocalDeliveryError::InvalidConfiguration)
67    }
68}
69
70#[derive(Debug, Error, ErrorCode)]
71pub enum LocalDeliveryError {
72    /// Preserve the first terminal failure for every pending token.
73    #[error(transparent)]
74    #[error_code(inherit)]
75    SessionFailure(std::sync::Arc<LocalDeliveryError>),
76    /// The retained item has no decoded message. Not retryable.
77    #[error("The delivery item has no enriched message")]
78    EnrichedMessageUnavailable,
79    /// This stream exhausted its network retry budget. Not retryable; a new stream may retry.
80    #[error("The message reader exhausted its network recovery budget after {attempts} attempts: {}", source.as_ref().map(|error| error.to_string()).unwrap_or_else(|| "the recovery deadline elapsed without a transport error".into()))]
81    NetworkRecoveryExhausted {
82        attempts: u32,
83        #[source]
84        source: Option<std::sync::Arc<xmtp_mls_engine::subscriptions::incoming::IncomingError>>,
85    },
86    /// A terminal network error stopped this stream. A transient configuration
87    /// admission failure may be retried by opening a new reader.
88    #[error("The message reader network failed: {0}")]
89    NetworkFailure(
90        #[source] std::sync::Arc<xmtp_mls_engine::subscriptions::incoming::IncomingError>,
91    ),
92    /// The client's server configuration changed. Not retryable on this client.
93    #[error(transparent)]
94    #[error_code(inherit)]
95    Blocked(#[from] xmtp_mls_server_config::server_configuration::BlockedConnection),
96    /// Database receipt, lease, cursor, or acknowledgement failure. May be retryable.
97    #[error(transparent)]
98    #[error_code(inherit)]
99    Storage(#[from] StorageError),
100    /// The callback failed or its token was dropped before acknowledgement. Not retryable.
101    #[error("The delivered message was not acknowledged")]
102    AcknowledgementRejected,
103    /// A previous acknowledgement write failed. Reopen to retry delivery. Not retryable.
104    #[error("Delivery stopped after acknowledgement persistence failed")]
105    AcknowledgementFailed,
106    /// Scope, filters, or retained content changed before dispatch. Reselect without acknowledgement.
107    #[error("The queued message belongs to an old delivery selection")]
108    SelectionChanged,
109    /// The batch or timing settings cannot maintain a valid consumer lease. Not retryable.
110    #[error("The local delivery configuration is invalid")]
111    InvalidConfiguration,
112    /// This reader has been closed. Not retryable.
113    #[error("The local message reader is closed")]
114    Closed,
115}
116
117impl From<RecoveryFailure> for LocalDeliveryError {
118    fn from(failure: RecoveryFailure) -> Self {
119        match failure {
120            RecoveryFailure::Exhausted { attempts, source } => {
121                Self::NetworkRecoveryExhausted { attempts, source }
122            }
123            RecoveryFailure::Terminal(error) => Self::NetworkFailure(error),
124        }
125    }
126}
127
128impl xmtp_mls_core::worker::NeedsDbReconnect for LocalDeliveryError {
129    #[deny(clippy::wildcard_enum_match_arm)]
130    fn needs_db_reconnect(&self) -> bool {
131        match self {
132            Self::SessionFailure(error) => error.needs_db_reconnect(),
133            Self::NetworkRecoveryExhausted { source, .. } => source
134                .as_ref()
135                .is_some_and(|error| error.needs_db_reconnect()),
136            Self::NetworkFailure(error) => error.needs_db_reconnect(),
137            Self::Storage(error) => error.db_needs_connection(),
138            Self::EnrichedMessageUnavailable
139            | Self::Blocked(..)
140            | Self::AcknowledgementRejected
141            | Self::AcknowledgementFailed
142            | Self::SelectionChanged
143            | Self::InvalidConfiguration
144            | Self::Closed => false,
145        }
146    }
147}
148
149impl RetryableError for LocalDeliveryError {
150    fn is_retryable(&self) -> bool {
151        match self {
152            Self::Storage(error) => error.is_retryable(),
153            Self::NetworkFailure(error) => xmtp_api::preflight::failure(error.as_ref())
154                .is_some_and(RetryableError::is_retryable),
155            _ => false,
156        }
157    }
158
159    fn rate_limit_delay(&self) -> Option<xmtp_common::time::Duration> {
160        match self {
161            Self::NetworkRecoveryExhausted {
162                source: Some(error),
163                ..
164            }
165            | Self::NetworkFailure(error) => error.rate_limit_delay(),
166            _ => None,
167        }
168    }
169}