Skip to main content

open_net/api/ws/
options.rs

1use super::config::deadline;
2use super::{validate_metadata, CancellationGroup};
3use crate::{Metadata, NetError, Result};
4use std::time::{Duration, Instant};
5
6/// Scheduling, cancellation, retry, and per-stage deadline configuration for
7/// one outbound message.
8#[derive(Clone, Debug)]
9pub struct SendOptions {
10    /// The normal or emergency sending channel used by the message. The default is the normal channel.
11    pub lane: MessageLane,
12    /// The scheduling priority within the normal channel; the emergency channel only accepts `Normal`.
13    pub priority: Priority,
14    /// Maximum time from the builder's first admission attempt until queue
15    /// resources are acquired; `None` imposes no separate admission limit.
16    /// Repeated admission attempts for the same builder use the original start
17    /// point, while the overall deadline remains in force.
18    pub enqueue_timeout: Option<Duration>,
19    /// The overall time limit for each actual write attempt, covering all shards of the message, defaults to 10 seconds.
20    pub write_timeout: Duration,
21    /// The original absolute deadline covering all stages, including queuing and reconnection waiting; `None` means there is no overall deadline.
22    pub deadline: Option<Instant>,
23    /// Retry permission after delivery failure; no retry by default. When retrying is allowed, the application must ensure the safety of repeated delivery.
24    pub retry: SendRetryPolicy,
25    /// How to handle cases where the connection is not connected during admission or the connection is interrupted during waiting. The default is to reject the request.
26    pub disconnected: DisconnectedPolicy,
27    /// A cancellation group that can uniformly cancel a group of operations; `None` means not to join the cancellation group.
28    pub cancellation: Option<CancellationGroup>,
29    /// Local application metadata attached to the send operation; it is not
30    /// automatically added to the wire message payload.
31    pub metadata: Metadata,
32}
33
34impl Default for SendOptions {
35    fn default() -> Self {
36        Self {
37            lane: MessageLane::default(),
38            priority: Priority::default(),
39            enqueue_timeout: None,
40            write_timeout: Duration::from_secs(10),
41            deadline: None,
42            retry: SendRetryPolicy::default(),
43            disconnected: DisconnectedPolicy::default(),
44            cancellation: None,
45            metadata: Metadata::new(),
46        }
47    }
48}
49
50impl SendOptions {
51    /// Checks configuration without starting timers or changing the deadline.
52    ///
53    /// A zero timeout or an elapsed absolute deadline represents an immediate
54    /// operational timeout, rather than an invalid configuration.
55    pub fn validate(&self) -> Result<()> {
56        if self.lane == MessageLane::Urgent && self.priority != Priority::Normal {
57            return Err(NetError::config(
58                "priority",
59                "must be Normal for the Urgent lane",
60            ));
61        }
62        if let Some(timeout) = self.enqueue_timeout {
63            deadline(timeout, "enqueue_timeout", true)?;
64        }
65        deadline(self.write_timeout, "write_timeout", true)?;
66        validate_metadata(&self.metadata)
67    }
68}
69
70/// Send queue channel; ordinary and emergency lanes have independent capacities.
71#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
72pub enum MessageLane {
73    /// The ordinary sending channel supports scheduling by priority and is the only channel allowed for tracked requests.
74    #[default]
75    Normal,
76    /// The emergency sending channel uses an independent queue and is processed first at the sending scheduling boundary.
77    Urgent,
78}
79
80/// The message scheduling priority in the ordinary sending channel.
81#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
82pub enum Priority {
83    /// Low priority.
84    Low,
85    /// Normal priority is also the default value and the value required for emergency channels.
86    #[default]
87    Normal,
88    /// High priority.
89    High,
90}
91
92/// Policy for a message that has not started sending when the session is
93/// disconnected or becomes disconnected.
94#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
95pub enum DisconnectedPolicy {
96    /// Only accepts the currently connected connection generation; fails the operation if it is not connected or the connection ends.
97    #[default]
98    Reject,
99    /// Allow an unsent message to wait for session reconnection, subject to its
100    /// cancellation and deadline limits.
101    WaitForReconnect,
102}
103
104/// Retry strategy for business-message write failures, configured independently
105/// of the connection's own reconnect policy.
106#[derive(Clone, Debug, Default)]
107pub enum SendRetryPolicy {
108    /// Do not retry business messages that have already been attempted to be sent.
109    #[default]
110    Never,
111    /// The application declares that redelivery is safe and allows resends within the configurable scope.
112    Idempotent {
113        /// The maximum number of additional retries after the initial transmission; zero means no additional retries.
114        max_retries: u32,
115    },
116}
117
118/// The sending, registration, and response wait limits for a tracked request.
119#[derive(Clone, Debug)]
120pub struct RequestOptions {
121    /// Request message sending configuration; requests can only use normal sending channels.
122    pub send: SendOptions,
123    /// Time limit to wait for a response from the selected starting point, default 30 seconds; zero means immediate expiration.
124    pub response_timeout: Duration,
125    /// Point at which response waiting begins; the default is after the request
126    /// has been written successfully.
127    pub response_timeout_origin: ResponseTimeoutOrigin,
128    /// The absolute deadline for completing the requested registration; `None` means not to limit the registration phase individually.
129    /// This restriction is no longer used after registration is completed, and `send.deadline` still binds the entire request.
130    pub registration_deadline: Option<Instant>,
131}
132
133impl Default for RequestOptions {
134    fn default() -> Self {
135        Self {
136            send: SendOptions::default(),
137            response_timeout: Duration::from_secs(30),
138            response_timeout_origin: ResponseTimeoutOrigin::default(),
139            registration_deadline: None,
140        }
141    }
142}
143
144impl RequestOptions {
145    /// Checks options while retaining the caller's original absolute deadlines.
146    pub fn validate(&self) -> Result<()> {
147        if self.send.lane != MessageLane::Normal {
148            return Err(NetError::config(
149                "send.lane",
150                "tracked requests require the Normal lane",
151            ));
152        }
153        self.send.validate().map_err(|error| {
154            if let Some(detail) = error.config_error() {
155                NetError::config(format!("send.{}", detail.field()), detail.reason())
156            } else {
157                error
158            }
159        })?;
160        deadline(self.response_timeout, "response_timeout", true)
161    }
162}
163
164/// Point at which the response-wait timeout starts.
165#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
166pub enum ResponseTimeoutOrigin {
167    /// Start timing when registration completes, so the timeout includes later
168    /// queueing and send time.
169    Registered,
170    /// Start timing after the request message is written successfully; time
171    /// spent registering, queueing, and writing is excluded from this timeout.
172    #[default]
173    Written,
174}