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