Skip to main content

open_net/api/ws/
send.rs

1use super::{
2    dispatch, Message, OperationId, OperationSnapshot, SendOptions, SessionId, TerminationOutcome,
3};
4use crate::module::ws_client::{
5    operation_control::OperationControl, session_runtime::SessionRuntime,
6};
7use crate::{EnqueueError, Result};
8use std::fmt;
9use std::sync::Arc;
10use std::time::Instant;
11
12/// Entry point for sending messages, permanently bound to the session that created it; clones
13/// continue to share that session.
14///
15/// Obtain a sender from [`super::Session::sender`] and distribute it to multiple application
16/// tasks. The application must still retain the original [`super::Session`]: dropping the
17/// session cancels it, and retaining a sender cannot prevent shutdown. The sender remains
18/// usable after that session reconnects; a newly created session requires a new sender.
19///
20/// Use [`Self::send`] when only the local write result matters, [`Self::enqueue`] when the
21/// operation must be tracked or cancelled separately, and [`Self::try_enqueue`] when waiting
22/// for queue capacity is not possible. Configure per-message priority, deadlines, and related
23/// settings through [`Self::message`].
24#[derive(Clone)]
25pub struct Sender {
26    /// Shared runtime state, send queue, and operation manager for the owning session.
27    pub(crate) runtime: Arc<SessionRuntime>,
28}
29impl Sender {
30    /// Returns the logical session identifier to which this sender is bound.
31    ///
32    /// # Use cases
33    ///
34    /// Associate application logs and send receipts with the correct session when several sessions run in parallel. Cloning the sender or reconnecting the same session does not
35    /// change this identifier; it does not identify any particular physical connection.
36    ///
37    /// # Example
38    ///
39    /// ```no_run
40    /// use open_net::ws::Session;
41    ///
42    /// fn log_sender(session: &Session) {
43    ///     let sender = session.sender();
44    ///     println!(
45    ///         "Sender session: {}, owner session: {}",
46    ///         sender.session_id(),
47    ///         session.id(),
48    ///     );
49    /// }
50    /// ```
51    pub fn session_id(&self) -> SessionId {
52        self.runtime.id
53    }
54    /// Checks whether the owning session has been cancelled or terminated, or the client has requested shutdown.
55    ///
56    /// # Use cases
57    ///
58    /// Quickly decide whether to stop producing messages before constructing more work for a
59    /// finished session. A `false` result does not mean that the session is currently connected:
60    /// it may still be connecting or waiting to reconnect. Initiating a graceful session close
61    /// does not guarantee an immediate `true`; wait for the session close result to confirm that
62    /// it has ended. The session can still close between this check and a send, so always handle errors returned by the sending methods.
63    ///
64    /// # Example
65    ///
66    /// ```no_run
67    /// use open_net::{ws::Sender, Result};
68    ///
69    /// async fn publish_status(sender: &Sender) -> Result<()> {
70    ///     if sender.is_closed() {
71    ///         return Ok(()); // The session has ended; stop this status update.
72    ///     }
73    ///     sender.send("status:online").await?;
74    ///     Ok(())
75    /// }
76    /// ```
77    pub fn is_closed(&self) -> bool {
78        self.runtime.is_closed()
79    }
80    /// Creates a builder holding the message body, initially using [`SendOptions::default`].
81    ///
82    /// This method only constructs the message; it does not reserve queue capacity or send it.
83    /// Strings become text messages, while byte slices, `Vec<u8>`, and similar values become binary messages. A [`Message`] can also be supplied explicitly.
84    ///
85    /// # Use cases
86    ///
87    /// When a message needs a custom priority, enqueue timeout, disconnection policy, or cancellation group, create a builder first, then configure it with
88    /// [`MessageBuilder::options`] and choose whether to send or reserve its resources.
89    ///
90    /// # Example
91    ///
92    /// ```no_run
93    /// use open_net::{
94    ///     ws::{Priority, SendOptions, Sender},
95    ///     Result,
96    /// };
97    /// use std::time::Duration;
98    ///
99    /// async fn publish_alert(sender: &Sender) -> Result<()> {
100    ///     sender
101    ///         .message("alert:temperature-high")
102    ///         .options(SendOptions {
103    ///             priority: Priority::High,
104    ///             enqueue_timeout: Some(Duration::from_secs(1)),
105    ///             ..Default::default()
106    ///         })
107    ///         .send()
108    ///         .await
109    /// }
110    /// ```
111    pub fn message(&self, message: impl Into<Message>) -> MessageBuilder {
112        MessageBuilder {
113            sender: self.clone(),
114            message: message.into(),
115            options: SendOptions::default(),
116            admission_started: None,
117        }
118    }
119    /// Uses the default sending policy, waits for the message to be queued, and waits for the local WebSocket write to complete.
120    ///
121    /// Equivalent to `self.message(message).send().await`. By default, sending is rejected when
122    /// disconnected, capacity shortages are awaited without a separate enqueue timeout, and each write attempt has a 10-second limit with no retry. Success confirms only the local
123    /// write; it does not confirm that the server received or processed the message.
124    ///
125    /// # Use cases
126    ///
127    /// Suitable for simple sequential flows such as status notifications or chat messages, where the next step follows the local write. Errors such as disconnection, session
128    /// closure, or a write timeout are returned directly. This interface does not retain a failed message for retrieval; use [`Self::enqueue`] when enqueue failures must preserve
129    /// the message or the operation must be cancelled explicitly.
130    ///
131    /// # Example
132    ///
133    /// ```no_run
134    /// use open_net::error::ReceiveError;
135    /// use open_net::network::{NetworkConfig, NetworkStatusPolicy, TlsConfig};
136    /// use open_net::subscription::{CallbackContext, Subscription};
137    /// use open_net::ws::{
138    ///     ConnectOptions, ConnectionEvent, ConnectionEventKind, ConnectionSnapshot, HeartbeatConfig,
139    ///     IncomingMessage, Message, RetryDecision, TaskEvent, TaskEventOptions, TcpKeepaliveConfig,
140    ///     WebSocketClientConfig,
141    /// };
142    /// use open_net::{HeaderValue, OpenNet, OpenNetConfig};
143    /// use open_net::tls::CryptoProvider;
144    /// use std::sync::Arc;
145    /// use std::thread;
146    /// use std::time::Duration;
147    ///
148    /// # const WS_BASE_URL: &str = "wss://example.com/api/ws";
149    /// # async fn example() -> open_net::Result<()> {
150    /// let provider: Arc<CryptoProvider> =
151    ///     Arc::new(rustls_openssl::default_provider());
152    /// let network = NetworkConfig::default()
153    ///     .with_network_status_policy(NetworkStatusPolicy::Ignore)
154    ///     .with_tls(TlsConfig::default().with_crypto_provider(Arc::clone(&provider)));
155    /// let net = OpenNet::new_with_config(
156    ///     OpenNetConfig::default()
157    ///         .with_runtime_worker_threads(2)
158    ///         .with_network_config(network.clone()),
159    /// )?;
160    /// let mut config = WebSocketClientConfig::default();
161    /// config.queues.normal.max_items = 128;
162    /// config.queues.urgent.max_items = 32;
163    /// config.requests.max_pending = 128;
164    /// config.frames.max_message_size = Some(8 * 1024 * 1024);
165    /// config.frames.data_frame_payload_size = Some(32 * 1024); // Large messages are framed automatically.
166    /// config.tcp.nodelay = true;
167    /// config.tcp.keepalive = Some(TcpKeepaliveConfig::default());
168    /// // The SDK handles Ping/Pong; the application does not need to emulate PB heartbeats with control frames.
169    /// config.heartbeat = Some(HeartbeatConfig {
170    ///     interval: Duration::from_secs(20),
171    ///     pong_timeout: Duration::from_secs(45),
172    ///     ..HeartbeatConfig::default()
173    /// });
174    /// config.close_timeout = Duration::from_secs(2);
175    /// config.validate()?;
176    ///
177    /// // Explicitly override the client network configuration here; the default is direct access,
178    /// // and wss uses the default trusted root certificates.
179    /// // Other creation methods: net.create_ws_client(CLIENT_NAME).await?;
180    /// // net.create_ws_client_with_config(CLIENT_NAME, config).await?.
181    /// let client = net
182    ///     .create_ws_client_with_network_config("ws_1_thread_name", config, network)
183    ///     .await?;
184    /// let _shared = net.get_ws_client("ws_1_thread_name")?; // Like clone(), this points to the same client.
185    ///
186    /// let mut options = ConnectOptions::new(WS_BASE_URL);
187    /// options.headers.insert(
188    ///     "authorization",
189    ///     HeaderValue::from_static("Bearer example-token"),
190    /// );
191    /// options
192    ///     .headers
193    ///     .insert("x-client-name", HeaderValue::from_static("demo"));
194    ///
195    /// let current_thread = thread::current();
196    /// // A-thread_name: main, thread_id: ThreadId(1)
197    /// println!(
198    ///     "A-thread_name: {}, thread_id: {:?}",
199    ///     current_thread.name().map_or("unnamed", |name| name),
200    ///     current_thread.id()
201    /// );
202    /// let mut session = client.connect(options).await?;
203    ///
204    /// // Keep subscription handles alive until the function returns; dropping a handle unsubscribes it.
205    /// let _state_subscription: Subscription = session.on_state(
206    ///     |context: CallbackContext, state: open_net::Result<ConnectionSnapshot>| match state {
207    ///         Ok(state) => {
208    ///             let current_thread = thread::current();
209    ///             //  thread_name: open-net-ws-status-0, thread_id: ThreadId(18)
210    ///             println!(
211    ///                 "State callback[{}]: {state:?}, thread_name: {}, thread_id: {:?}",
212    ///                 context.id(),
213    ///                 current_thread.name().map_or("unnamed", |name| name),
214    ///                 current_thread.id()
215    ///             );
216    ///         }
217    ///         Err(error) => {
218    ///             eprintln!("Failed to receive state[{}]: {error}", context.id())
219    ///         }
220    ///     },
221    /// )?;
222    ///
223    /// let callback_sender = session.sender();
224    /// let _message_subscription: Subscription = session.on_message(
225    ///     move |context: CallbackContext, message: Result<IncomingMessage, ReceiveError>| {
226    ///         match message {
227    ///             Ok(message) => {
228    ///                 // thread_name: open-net-ws-data-callback, thread_id: ThreadId(20)
229    ///                 let current_thread = thread::current();
230    ///                 let kind = match message.message() {
231    ///                     Some(Message::Text(_)) => "text",
232    ///                     Some(Message::Binary(_)) => "binary",
233    ///                     None => "control",
234    ///                 };
235    ///                 // Log SDK identities and payload sizes; explicit body getters return original data.
236    ///                 println!(
237    ///                     "Message callback[{}]: client={} session={} connection={} kind={} message_bytes={:?}, thread_name: {}, thread_id: {:?}",
238    ///                     context.id(),
239    ///                     message.client_id(),
240    ///                     message.session_id(),
241    ///                     message.connection_id(),
242    ///                     kind,
243    ///                     message.message().map(Message::len),
244    ///                     current_thread.name().map_or("unnamed", |name| name),
245    ///                     current_thread.id()
246    ///                 );
247    ///             }
248    ///             Err(error) => {
249    ///                 println!("message_subscription->error: {}", error);
250    ///             }
251    ///         }
252    ///     },
253    /// )?;
254    ///
255    /// let _event_subscription: Subscription = session.on_event(
256    ///     |context: CallbackContext, event: Result<ConnectionEvent, ReceiveError>| match event {
257    ///         Ok(event) => {
258    ///             //  thread_name: open-net-ws-events-1, thread_id: ThreadId(22)
259    ///             let current_thread = thread::current();
260    ///             println!(
261    ///                 "Connection event[{}] #{}: client={} session={} at={:?}, thread_name: {}, thread_id: {:?}",
262    ///                 context.id(),
263    ///                 event.sequence,
264    ///                 event.client_id,
265    ///                 event.session_id,
266    ///                 event.occurred_at,
267    ///                 current_thread.name().map_or("unnamed", |name| name),
268    ///                 current_thread.id());
269    ///             // on_event records lifecycle events; observe immediate states such as network waits through on_state.
270    ///             match event.kind {
271    ///                 ConnectionEventKind::AttemptStarted { attempt } => {
272    ///                     println!(
273    ///                         "           Starting connection attempt: cycle={} attempt={} (initial connection or retry)",
274    ///                         attempt.cycle_id, attempt.attempt_id
275    ///                     );
276    ///                 }
277    ///                 ConnectionEventKind::Established { connection } => {
278    ///                     println!(
279    ///                         "           Connection established: connection={} cycle={} attempt={} connected_at={:?}",
280    ///                         connection.connection_id,
281    ///                         connection.cycle_id,
282    ///                         connection.attempt_id,
283    ///                         connection.connected_at
284    ///                     );
285    ///                 }
286    ///                 ConnectionEventKind::AttemptFailed {
287    ///                     attempt,
288    ///                     error,
289    ///                     retry,
290    ///                     ..
291    ///                 } => {
292    ///                     eprintln!(
293    ///                         "           Connection attempt failed: cycle={} attempt={} kind={:?} stage={:?} error={error}",
294    ///                         attempt.cycle_id,
295    ///                         attempt.attempt_id,
296    ///                         error.kind(),
297    ///                         error.context().stage
298    ///                     );
299    ///                     match retry {
300    ///                         RetryDecision::Scheduled { after } => {
301    ///                             println!(
302    ///                                 "           Retry scheduled: trying to connect again after a backoff of {} ms",
303    ///                                 after.as_millis()
304    ///                             );
305    ///                         }
306    ///                         RetryDecision::Stop => {
307    ///                             println!("          Stopping retries; waiting for the session-closed event");
308    ///                         }
309    ///                     }
310    ///                 }
311    ///                 ConnectionEventKind::Disconnected { connection, end } => {
312    ///                     // A single connection can disconnect and still reconnect; Closed marks the end of the session.
313    ///                     println!(
314    ///                         "               Connection disconnected: connection={} reason={:?} io_end={:?}",
315    ///                         connection.connection_id, end.reason, end.io_end
316    ///                     );
317    ///                     if let Some(close) = end.peer_close {
318    ///                         println!(
319    ///                             "           Peer close information: code={:?} reason_len={}",
320    ///                             close.code, close.reason.len()
321    ///                         );
322    ///                     }
323    ///                     if let Some(error) = end.error {
324    ///                         eprintln!("         Disconnection error: kind={:?} error={error}", error.kind());
325    ///                     }
326    ///                 }
327    ///                 ConnectionEventKind::Closed { result } => match result {
328    ///                     Ok(end) => {
329    ///                         println!("          Session closed; will not reconnect: reason={:?}", end.reason);
330    ///                         if let Some(last) = end.last_connection {
331    ///                             println!("          Last connection end information: {last:?}");
332    ///                         }
333    ///                     }
334    ///                     Err(error) => {
335    ///                         eprintln!(
336    ///                             "           Session ended unexpectedly; will not reconnect: kind={:?} error={error}",
337    ///                             error.kind()
338    ///                         );
339    ///                     }
340    ///                 },
341    ///                 // ConnectionEventKind is marked non_exhaustive to support future event variants.
342    ///                 other => println!("         Other connection event: {other:?}"),
343    ///             }
344    ///         }
345    ///         Err(error) => eprintln!("           Failed to receive connection event[{}]: {error}", context.id()),
346    ///     },
347    /// )?;
348    ///
349    /// let _task_subscription: Subscription = session.on_task(
350    ///     TaskEventOptions::default(),
351    ///     |context: CallbackContext, event: Result<TaskEvent, ReceiveError>| match event {
352    ///         Ok(event) => {
353    ///             // thread_name: open-net-task-events-1-0, thread_id: ThreadId(23)
354    ///             let current_thread = thread::current();
355    ///             // Phase, delivery evidence, cause, and result classify the operation without its original input.
356    ///             let result = event.result.as_ref().map_err(|error| error.kind());
357    ///             println!(
358    ///                 "Task callback[{}]: client={} session={} operation={} phase={:?} delivery={:?} cause={:?} result={:?}, thread_name: {}, thread_id: {:?}",
359    ///                 context.id(),
360    ///                 event.client_id,
361    ///                 event.session_id,
362    ///                 event.operation_id,
363    ///                 event.phase,
364    ///                 event.delivery,
365    ///                 event.cause,
366    ///                 result,
367    ///                 current_thread.name().map_or("unnamed", |name| name),
368    ///                 current_thread.id()
369    ///             );
370    ///         }
371    ///         Err(error) => eprintln!("Failed to receive task event[{}]: {error}", context.id()),
372    ///     },
373    /// )?;
374    ///
375    /// let sender = session.sender();
376    ///
377    /// // Omit the code for building the PB protocol
378    /// let message = Message::text("demo:message");
379    /// sender.send(message).await?;
380    ///
381    /// thread::sleep(Duration::from_secs(15));
382    ///
383    /// let shutdown = client.shutdown().await; // Permanently closes the client; no clone can reconnect.
384    /// let destroy = net.destroy_ws_client("ws_1_thread_name").await; // Also removes the registered name from the engine.
385    /// println!(
386    ///     "Client closed={}, shutdown={shutdown:?}, destroy={destroy:?}",
387    ///     client.is_shutdown()
388    /// );
389    /// shutdown?;
390    /// destroy?;
391    /// # Ok(())
392    /// # }
393    /// ```
394    pub async fn send(&self, message: impl Into<Message>) -> Result<()> {
395        self.message(message).send().await
396    }
397    /// Uses the default sending policy, waits for capacity, and returns a trackable receipt as soon as the message is submitted.
398    ///
399    /// Success means only that the message was enqueued; use [`MessageReceipt::written`] to wait for the local write. Capacity covers both the send queue and resources needed for
400    /// subscribed operation events, so a slow consumer can create backpressure. By default no
401    /// enqueue timeout is set and sending is rejected while disconnected; use [`Self::message`] to change these policies.
402    ///
403    /// # Use cases
404    ///
405    /// Suitable when production and completion tracking are separate: the producer continues after submission while another task retains the receipt to query status or cancel. A
406    /// failed [`EnqueueError`] retains the converted [`Message`]; use [`EnqueueError::into_parts`] to recover the body and decide whether to cache, discard, or resubmit it later.
407    ///
408    /// # Example
409    ///
410    /// ```no_run
411    /// use open_net::{
412    ///     ws::{Message, MessageReceipt, Sender},
413    ///     Result,
414    /// };
415    ///
416    /// async fn enqueue_report(
417    ///     sender: &Sender,
418    ///     pending: &mut Vec<MessageReceipt>,
419    ///     unsent: &mut Vec<Message>,
420    /// ) -> Result<()> {
421    ///     match sender.enqueue("report:ready").await {
422    ///         Ok(receipt) => pending.push(receipt), // Wait for written() later as a group.
423    ///         Err(failure) => {
424    ///             let (message, error) = failure.into_parts();
425    ///             unsent.push(message); // Preserve the body that was never enqueued.
426    ///             return Err(error);
427    ///         }
428    ///     }
429    ///     Ok(())
430    /// }
431    /// ```
432    pub async fn enqueue(
433        &self,
434        message: impl Into<Message>,
435    ) -> std::result::Result<MessageReceipt, EnqueueError<Message>> {
436        self.message(message).enqueue().await.map_err(|error| {
437            let (builder, error) = error.into_parts();
438            EnqueueError::new(builder.message, error)
439        })
440    }
441    /// Attempts to enqueue immediately with the default sending policy, without waiting for capacity or write completion.
442    ///
443    /// Returns [`crate::error::ErrorKind::QueueFull`] when queue or operation-event resources are temporarily exhausted. It can also fail because the client is disconnected, the
444    /// session is closed, the message is too large, or for other reasons. The converted message
445    /// is retained on failure. This synchronous entry point does not require the calling thread to enter a Tokio runtime, but the client worker tasks must remain alive.
446    ///
447    /// # Use cases
448    ///
449    /// Suitable for UI events, synchronous callbacks, and collection paths that cannot wait for
450    /// backpressure. The application can cache or coalesce messages when the queue is full; do not treat every error as queue-full and retry unconditionally.
451    ///
452    /// # Example
453    ///
454    /// ```no_run
455    /// use open_net::{error::ErrorKind, ws::{Message, MessageReceipt, Sender}, Result};
456    ///
457    /// fn submit_sample(
458    ///     sender: &Sender,
459    ///     backlog: &mut Vec<Message>,
460    /// ) -> Result<Option<MessageReceipt>> {
461    ///     match sender.try_enqueue("temperature:24") {
462    ///         Ok(receipt) => Ok(Some(receipt)),
463    ///         Err(failure) if failure.error().kind() == ErrorKind::QueueFull => {
464    ///             backlog.push(failure.into_inner()); // The application controls cache bounds and retry timing.
465    ///             Ok(None)
466    ///         }
467    ///         Err(failure) => Err(failure.into_error()),
468    ///     }
469    /// }
470    /// ```
471    pub fn try_enqueue(
472        &self,
473        message: impl Into<Message>,
474    ) -> std::result::Result<MessageReceipt, EnqueueError<Message>> {
475        self.message(message).try_enqueue().map_err(|error| {
476            let (builder, error) = error.into_parts();
477            EnqueueError::new(builder.message, error)
478        })
479    }
480}
481impl fmt::Debug for Sender {
482    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
483        f.debug_struct("Sender")
484            .field("session_id", &self.session_id())
485            .field("closed", &self.is_closed())
486            .finish()
487    }
488}
489
490/// Holds a message and its sending options; both can be recovered from an enqueue error.
491///
492/// The builder does not send by itself; resources are requested only when a send, enqueue, or
493/// prepare method is called. Dropping an unused builder only drops the message body.
494#[must_use]
495#[derive(Debug)]
496pub struct MessageBuilder {
497    /// Sending entry point for the session that owns the message.
498    sender: Sender,
499    /// Message content held by this builder until submission.
500    message: Message,
501    /// Queue, priority, timeout, and cancellation policies for this send.
502    options: SendOptions,
503    /// Time of the first enqueue admission attempt; `None` before admission or after options are reset.
504    admission_started: Option<Instant>,
505}
506impl MessageBuilder {
507    /// Replaces all sending options for this message and resets the enqueue-wait start time.
508    ///
509    /// This method only stores the options; validity is checked when resources are actually requested. Calling it again replaces every previous setting rather than merging fields.
510    /// An absolute `deadline` supplied in the options is not moved forward automatically.
511    ///
512    /// # Use cases
513    ///
514    /// Set a priority, timeout, cancellation group, or disconnect-wait policy for one message
515    /// without affecting other messages. After recovering a builder from an enqueue error, call this again only when the application intentionally needs a new enqueue-wait budget.
516    /// `WaitForReconnect` lets an unsent message wait for a connection, but does not enable the session's reconnection policy by itself.
517    ///
518    /// # Example
519    ///
520    /// ```no_run
521    /// use open_net::{
522    ///     ws::{DisconnectedPolicy, SendOptions, Sender},
523    ///     Result,
524    /// };
525    /// use std::time::{Duration, Instant};
526    ///
527    /// async fn publish_latest_state(sender: &Sender) -> Result<()> {
528    ///     sender
529    ///         .message("state:active")
530    ///         .options(SendOptions {
531    ///             disconnected: DisconnectedPolicy::WaitForReconnect,
532    ///             enqueue_timeout: Some(Duration::from_secs(2)),
533    ///             deadline: Some(Instant::now() + Duration::from_secs(15)),
534    ///             ..Default::default()
535    ///         })
536    ///         .send()
537    ///         .await
538    /// }
539    /// ```
540    pub fn options(mut self, options: SendOptions) -> Self {
541        self.options = options;
542        self.admission_started = None;
543        self
544    }
545    /// Enqueues the message according to the configured policy and waits for its local WebSocket write to complete.
546    ///
547    /// # Use cases
548    ///
549    /// Suitable for sequential workflows that customize one message but do not need to manage a
550    /// receipt separately. Enqueue and write failures are returned as [`crate::NetError`]; the builder and message are not returned with the error. Success does not mean that the
551    /// server processed the message; use the session request interface when a protocol response is required.
552    ///
553    /// Once the message has been submitted, dropping this method's waiting future does not retract the send. To cancel explicitly, configure a cancellation group or use
554    /// [`Self::enqueue`] to obtain a receipt and then call [`MessageReceipt::cancel`].
555    ///
556    /// # Example
557    ///
558    /// ```no_run
559    /// use open_net::{
560    ///     ws::{SendOptions, Sender},
561    ///     Result,
562    /// };
563    /// use std::time::{Duration, Instant};
564    ///
565    /// async fn publish_with_deadline(sender: &Sender) -> Result<()> {
566    ///     sender
567    ///         .message("status:ready")
568    ///         .options(SendOptions {
569    ///             deadline: Some(Instant::now() + Duration::from_secs(5)),
570    ///             ..Default::default()
571    ///         })
572    ///         .send()
573    ///         .await?;
574    ///     Ok(())
575    /// }
576    /// ```
577    pub async fn send(self) -> Result<()> {
578        self.enqueue()
579            .await
580            .map_err(EnqueueError::into_error)?
581            .written()
582            .await
583    }
584    /// Waits for resources according to the configured policy, submits the message, and returns a receipt without waiting for the write to complete.
585    ///
586    /// When capacity is unavailable, waits asynchronously subject to `enqueue_timeout`, the
587    /// overall `deadline`, cancellation, and session state. A failed [`EnqueueError`] retains the
588    /// complete builder, including the message, options, and the start time of the first resource
589    /// attempt; retrying that builder directly does not restore a full enqueue-timeout budget.
590    ///
591    /// # Use cases
592    ///
593    /// Suitable when a send needs a custom priority or deadline while another task tracks the
594    /// write. Use [`Self::prepare`] when resources should be reserved first and sending should be allowed only after local business state has been recorded.
595    ///
596    /// # Example
597    ///
598    /// ```no_run
599    /// use open_net::{
600    ///     ws::{MessageReceipt, Priority, SendOptions, Sender},
601    ///     Result,
602    /// };
603    /// use std::time::Duration;
604    ///
605    /// async fn queue_alert(sender: &Sender) -> Result<MessageReceipt> {
606    ///     let receipt = sender
607    ///         .message("alert:disk-low")
608    ///         .options(SendOptions {
609    ///             priority: Priority::High,
610    ///             enqueue_timeout: Some(Duration::from_millis(500)),
611    ///             ..Default::default()
612    ///         })
613    ///         .enqueue()
614    ///         .await?;
615    ///     println!("Enqueued operation: {}", receipt.id());
616    ///     Ok(receipt) // The caller can await receipt.written() later.
617    /// }
618    /// ```
619    pub async fn enqueue(mut self) -> std::result::Result<MessageReceipt, EnqueueError<Self>> {
620        match self.admit(true).await.and_then(PreparedMessage::commit) {
621            Ok(receipt) => Ok(receipt),
622            Err(error) => Err(EnqueueError::new(self, error)),
623        }
624    }
625    /// Attempts to enqueue immediately under the configured policy, without waiting for send resources.
626    ///
627    /// Unlike [`Self::enqueue`], returns [`crate::error::ErrorKind::QueueFull`] immediately when
628    /// resources are unavailable; all other validation, cancellation, and deadline rules still apply. Failure retains the complete builder and the initial enqueue timestamp, so
629    /// asynchronous enqueue can continue waiting. This method does not require the calling thread to enter a Tokio runtime.
630    ///
631    /// # Use cases
632    ///
633    /// Suitable for paths that try a fast submission first and, on backpressure, either wait or
634    /// hand the work to an application scheduler. Retrying the recovered builder preserves its priority and other settings; the message need not be reconstructed.
635    ///
636    /// # Example
637    ///
638    /// ```no_run
639    /// use open_net::{error::ErrorKind, ws::{SendOptions, Sender}, Result};
640    /// use std::time::Duration;
641    ///
642    /// async fn submit_or_wait(sender: &Sender) -> Result<()> {
643    ///     let builder = sender.message("report:ready").options(SendOptions {
644    ///         enqueue_timeout: Some(Duration::from_secs(1)), ..Default::default()
645    ///     });
646    ///     let receipt = match builder.try_enqueue() {
647    ///         Ok(receipt) => receipt,
648    ///         Err(failure) if failure.error().kind() == ErrorKind::QueueFull => {
649    ///             // Continue the original one-second enqueue budget instead of resetting it on every retry.
650    ///             failure.into_inner().enqueue().await?
651    ///         }
652    ///         Err(failure) => return Err(failure.into_error()),
653    ///     };
654    ///     receipt.written().await
655    /// }
656    /// ```
657    pub fn try_enqueue(mut self) -> std::result::Result<MessageReceipt, EnqueueError<Self>> {
658        match self.try_admit().and_then(PreparedMessage::commit) {
659            Ok(receipt) => Ok(receipt),
660            Err(error) => Err(EnqueueError::new(self, error)),
661        }
662    }
663    /// Waits for and reserves send resources, returning a message that has not yet been submitted to the writer.
664    ///
665    /// Uses the same resource-wait, timeout, and cancellation policies as [`Self::enqueue`], but
666    /// requires a subsequent call to [`PreparedMessage::commit`] to send. On failure, the complete
667    /// builder can be recovered. On success, a receipt can be obtained first; dropping the [`PreparedMessage`] directly cancels the operation and releases the reserved resources.
668    ///
669    /// # Use cases
670    ///
671    /// Suitable for recording local tracking state by operation ID or performing a final business-condition check before the message can be written. The reservation consumes
672    /// capacity, so commit or drop it promptly. The overall deadline and cancellation remain active; a successful reservation therefore does not guarantee that a later commit will
673    /// succeed. `enqueue_timeout` limits only the wait to acquire resources, not the interval between a successful reservation and commit.
674    ///
675    /// # Example
676    ///
677    /// ```no_run
678    /// use open_net::{ws::Sender, Result};
679    ///
680    /// async fn publish_if_needed(sender: &Sender, still_needed: bool) -> Result<()> {
681    ///     let prepared = sender.message("refresh:inventory").prepare().await?;
682    ///     println!(
683    ///         "Registered operation before sending: {}",
684    ///         prepared.receipt().id()
685    ///     );
686    ///     if !still_needed {
687    ///         drop(prepared); // It was not submitted, so this message will not be written.
688    ///         return Ok(());
689    ///     }
690    ///     let receipt = prepared.commit()?;
691    ///     receipt.written().await
692    /// }
693    /// ```
694    pub async fn prepare(mut self) -> std::result::Result<PreparedMessage, EnqueueError<Self>> {
695        match self.admit(true).await {
696            Ok(prepared) => Ok(prepared),
697            Err(error) => Err(EnqueueError::new(self, error)),
698        }
699    }
700    /// Attempts to reserve send resources immediately, without waiting for capacity or submitting the message.
701    ///
702    /// Returns [`crate::error::ErrorKind::QueueFull`] when resources are unavailable; all other validation, cancellation, and deadline rules are the same as for [`Self::prepare`].
703    /// Failure retains the complete builder and its original admission timestamp. After success,
704    /// call [`PreparedMessage::commit`] or drop the reservation to cancel the operation. This synchronous method does not require the calling thread to enter a Tokio runtime.
705    ///
706    /// # Use cases
707    ///
708    /// Suitable for optional reporting from a synchronous callback: record and submit only when
709    /// resources are immediately available, otherwise skip this report. A failed builder can also be handed to an application scheduler for retry when resources become available.
710    ///
711    /// # Example
712    ///
713    /// ```no_run
714    /// use open_net::{
715    ///     error::ErrorKind,
716    ///     ws::{MessageReceipt, Sender},
717    ///     Result,
718    /// };
719    ///
720    /// fn submit_optional_report(sender: &Sender) -> Result<Option<MessageReceipt>> {
721    ///     let prepared = match sender.message("metrics:snapshot").try_prepare() {
722    ///         Ok(prepared) => prepared,
723    ///         Err(failure) if failure.error().kind() == ErrorKind::QueueFull => {
724    ///             return Ok(None); // This sample may be skipped without blocking the callback.
725    ///         }
726    ///         Err(failure) => return Err(failure.into_error()),
727    ///     };
728    ///     println!(
729    ///         "Registered operation before commit: {}",
730    ///         prepared.receipt().id()
731    ///     );
732    ///     Ok(Some(prepared.commit()?))
733    /// }
734    /// ```
735    pub fn try_prepare(mut self) -> std::result::Result<PreparedMessage, EnqueueError<Self>> {
736        match self.try_admit() {
737            Ok(prepared) => Ok(prepared),
738            Err(error) => Err(EnqueueError::new(self, error)),
739        }
740    }
741    async fn admit(&mut self, wait: bool) -> Result<PreparedMessage> {
742        let started = *self.admission_started.get_or_insert_with(Instant::now);
743        let admission = dispatch::prepare(
744            &self.sender.runtime,
745            &self.message,
746            &self.options,
747            started,
748            None,
749            wait,
750        )
751        .await?;
752        Ok(PreparedMessage::new(admission))
753    }
754    fn try_admit(&mut self) -> Result<PreparedMessage> {
755        let started = *self.admission_started.get_or_insert_with(Instant::now);
756        let admission = dispatch::try_prepare(
757            &self.sender.runtime,
758            &self.message,
759            &self.options,
760            started,
761            None,
762        )?;
763        Ok(PreparedMessage::new(admission))
764    }
765}
766
767/// Shared receipt for a message operation; it can query state, request cancellation, or wait for
768/// the local write to complete.
769///
770/// Receipt clones observe the same operation, and dropping a receipt does not automatically cancel
771/// a submitted message. A successful local write does not mean that the peer received or processed
772/// it; use a request interface when an application response is required.
773#[must_use]
774#[derive(Clone)]
775pub struct MessageReceipt {
776    /// Message operation observed and controlled by all clones of its receipt.
777    core: Arc<OperationControl>,
778}
779impl MessageReceipt {
780    /// Snapshot of the raw message operation's attempts, transport writes and final stop reason.
781    /// The report remains stable after completion and is shared by receipt clones.
782    pub fn retry_report(&self) -> crate::api::retry::RetryReport {
783        self.core.retry_report()
784    }
785
786    /// Returns this message operation's identifier, shared by receipt clones and retries of the operation.
787    ///
788    /// # Use cases
789    ///
790    /// Correlate application logs with the `operation_id` in task events, or index pending items
791    /// in a user interface. Operation IDs are allocated within their session; records spanning sessions should also retain the session and client identities. Do not use this value
792    /// directly as an on-wire business request ID.
793    ///
794    /// # Example
795    ///
796    /// ```no_run
797    /// use open_net::{ws::Sender, Result};
798    ///
799    /// async fn log_submission(sender: &Sender) -> Result<()> {
800    ///     let receipt = sender.enqueue("report:ready").await?;
801    ///     println!(
802    ///         "Send operation {} for session {}",
803    ///         receipt.id(),
804    ///         receipt.session_id()
805    ///     );
806    ///     receipt.written().await
807    /// }
808    /// ```
809    pub fn id(&self) -> OperationId {
810        self.core.id()
811    }
812    /// Returns the logical session identifier that owns this message operation.
813    ///
814    /// # Use cases
815    ///
816    /// Use this value to route a send result back to the correct business session when receipts
817    /// from several sessions are collected together. It does not change if the session later
818    /// reconnects or ends, and it does not identify the physical connection used for this write.
819    ///
820    /// # Example
821    ///
822    /// ```no_run
823    /// use open_net::{ws::Sender, Result};
824    ///
825    /// async fn check_receipt_owner(sender: &Sender) -> Result<()> {
826    ///     let receipt = sender.enqueue("status:ready").await?;
827    ///     println!(
828    ///         "Receipt session: {}, sender session: {}",
829    ///         receipt.session_id(),
830    ///         sender.session_id(),
831    ///     );
832    ///     receipt.written().await
833    /// }
834    /// ```
835    pub fn session_id(&self) -> SessionId {
836        self.core.session_id()
837    }
838    /// Reads the current operation snapshot, including its phase, delivery evidence, and any determined final result.
839    ///
840    /// # Use cases
841    ///
842    /// Useful for displaying progress such as “queued”, “writing”, or “finished”, or for diagnosing whether a failed message may already have been written. A snapshot is only a
843    /// point-in-time read and does not lock in later results. Use `delivery` as delivery evidence;
844    /// `phase` alone cannot establish that the peer received the message. Use [`Self::written`]
845    /// when completion must be awaited. The outer `Result` reports whether the read succeeded; the operation's own outcome is stored in the snapshot's `result`.
846    ///
847    /// # Example
848    ///
849    /// ```no_run
850    /// use open_net::{ws::MessageReceipt, Result};
851    ///
852    /// fn show_progress(receipt: &MessageReceipt) -> Result<()> {
853    ///     let snapshot = receipt.state()?;
854    ///     println!(
855    ///         "Phase: {:?}; delivery evidence: {:?}",
856    ///         snapshot.phase, snapshot.delivery
857    ///     );
858    ///     if let Some(result) = snapshot.result {
859    ///         println!("Final result: {result:?}");
860    ///     }
861    ///     Ok(())
862    /// }
863    /// ```
864    pub fn state(&self) -> Result<OperationSnapshot> {
865        self.core.snapshot()
866    }
867    /// Requests cancellation of this message operation and returns the actual outcome after racing with completion, failure, and other terminal states.
868    ///
869    /// # Use cases
870    ///
871    /// Any receipt clone can request cancellation when a user withdraws a pending send or its
872    /// business data expires. [`TerminationOutcome::TerminatedBeforeWrite`] means cancellation
873    /// took effect before business data was written. [`TerminationOutcome::DeliveryUnknown`] means the data may have reached the peer and cannot be retracted.
874    /// [`TerminationOutcome::AlreadyFinished`] means a terminal state already existed and this
875    /// request changed nothing. An `Ok` return by itself does not mean cancellation succeeded or
876    /// that transport or callback tasks have exited. An ordinary message is finished once its write succeeds, so later cancellation returns `AlreadyFinished`; the shared
877    /// `TerminatedAfterWrite` variant is for request operations waiting for a response and is not reached by ordinary messages.
878    ///
879    /// # Example
880    ///
881    /// ```no_run
882    /// use open_net::{
883    ///     ws::{MessageReceipt, TerminationOutcome},
884    ///     Result,
885    /// };
886    ///
887    /// fn withdraw_message(receipt: &MessageReceipt) -> Result<()> {
888    ///     match receipt.cancel()? {
889    ///         TerminationOutcome::TerminatedBeforeWrite => println!("Canceled before writing"),
890    ///         TerminationOutcome::DeliveryUnknown => {
891    ///             println!("Delivery may have occurred; reconcile in the application")
892    ///         }
893    ///         TerminationOutcome::AlreadyFinished => println!("Operation had already finished"),
894    ///         // Request-only variant of the shared enum; ordinary messages never wait for a response.
895    ///         TerminationOutcome::TerminatedAfterWrite => {
896    ///             println!("Terminated after confirmed write")
897    ///         }
898    ///     }
899    ///     Ok(())
900    /// }
901    /// ```
902    pub fn cancel(&self) -> Result<TerminationOutcome> {
903        self.core.cancel()
904    }
905    /// Waits for this message's local WebSocket write to complete, returning the corresponding error if the operation previously failed.
906    ///
907    /// # Use cases
908    ///
909    /// Suitable for confirming the local write in another task after enqueueing, then updating
910    /// progress or advancing subsequent sends. Multiple receipt clones can wait concurrently,
911    /// and an already completed result can be awaited repeatedly. This method does not wait for
912    /// a server response or business processing, and it does not submit an uncommitted reservation.
913    ///
914    /// Dropping the waiting future only stops this wait; it does not cancel the message. This
915    /// method has no separate timeout parameter. To bound the total time including queueing and
916    /// reconnection, configure `SendOptions::deadline` before submission. A write error may leave delivery uncertain; use the delivery evidence in [`Self::state`] to handle it.
917    ///
918    /// # Example
919    ///
920    /// ```no_run
921    /// use open_net::{ws::Sender, Result};
922    ///
923    /// async fn publish_and_track(sender: &Sender) -> Result<()> {
924    ///     let receipt = sender.enqueue("report:ready").await?;
925    ///     let observer = receipt.clone();
926    ///     receipt.written().await?;
927    ///     observer.written().await?; // The successful result of the same operation can be read again.
928    ///     println!("Operation {} finished local writing", observer.id());
929    ///     Ok(())
930    /// }
931    /// ```
932    pub async fn written(&self) -> Result<()> {
933        self.core.written().await.map(|_| ())
934    }
935}
936impl fmt::Debug for MessageReceipt {
937    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
938        f.debug_struct("MessageReceipt")
939            .field("id", &self.id())
940            .field("session_id", &self.session_id())
941            .field("state", &self.state())
942            .finish()
943    }
944}
945
946/// Message with send resources reserved but not yet submitted; dropping it directly cancels the
947/// operation.
948///
949/// Created by [`MessageBuilder::prepare`] or [`MessageBuilder::try_prepare`]. The reservation
950/// consumes send capacity; call [`Self::commit`] promptly after recording local state, or drop it
951/// directly when the application abandons the send. Cancellation, session termination, or the
952/// overall deadline can invalidate the reservation.
953#[must_use]
954pub struct PreparedMessage {
955    /// Manages the queue reservation and cancellation cleanup while it is unsubmitted.
956    admission: dispatch::Admission,
957    /// Receipt used to observe the same message operation before and after submission.
958    receipt: MessageReceipt,
959}
960impl PreparedMessage {
961    fn new(admission: dispatch::Admission) -> Self {
962        let receipt = MessageReceipt {
963            core: admission.control.clone(),
964        };
965        Self { admission, receipt }
966    }
967    /// Borrows the reserved message's receipt, which can query its ID, observe state, or request cancellation before submission.
968    ///
969    /// # Use cases
970    ///
971    /// Clone the receipt into a local tracking table or pass it to another observer before the
972    /// message can be written. It refers to the same operation before and after submission; a
973    /// receipt clone neither submits the message nor extends the reservation's lifetime. If the
974    /// reservation is dropped, retained receipts observe its cancellation or existing terminal state.
975    ///
976    /// # Example
977    ///
978    /// ```no_run
979    /// use open_net::{ws::Sender, Result};
980    ///
981    /// async fn observe_before_commit(sender: &Sender) -> Result<()> {
982    ///     let prepared = sender.message("report:ready").prepare().await?;
983    ///     let observer = prepared.receipt().clone();
984    ///     println!("Operation ID before commit: {}", observer.id());
985    ///     let committed = prepared.commit()?;
986    ///     println!("Operation ID after commit: {}", committed.id());
987    ///     observer.written().await
988    /// }
989    /// ```
990    pub fn receipt(&self) -> &MessageReceipt {
991        &self.receipt
992    }
993    /// Consumes the reservation, submits the message to the send queue, and returns a receipt for the same operation.
994    ///
995    /// This method completes synchronously: it does not wait for capacity or a network write and
996    /// does not require the calling thread to enter a Tokio runtime. The operation is still checked for validity at submission; cancellation, closure, or expiration of the overall
997    /// deadline can cause failure. Failure returns only [`crate::NetError`]; the reservation and message body are not returned.
998    ///
999    /// # Use cases
1000    ///
1001    /// Use after local tracking has been recorded and business conditions have been confirmed,
1002    /// allowing the reserved message to enter send scheduling. Success means submission only;
1003    /// wait for [`MessageReceipt::written`] to confirm the local write. Consuming `self` ensures
1004    /// that one reservation can be submitted only once; this does not provide exactly-once processing by the server.
1005    ///
1006    /// # Example
1007    ///
1008    /// ```no_run
1009    /// use open_net::{ws::{MessageReceipt, OperationId, Sender}, Result};
1010    /// use std::collections::HashMap;
1011    ///
1012    /// fn register_and_commit(
1013    ///     sender: &Sender,
1014    ///     pending: &mut HashMap<OperationId, MessageReceipt>, // This table serves the current session only.
1015    /// ) -> Result<MessageReceipt> {
1016    ///     let prepared = sender.message("refresh:inventory").try_prepare()?;
1017    ///     let id = prepared.receipt().id();
1018    ///     pending.insert(id, prepared.receipt().clone());
1019    ///     match prepared.commit() {
1020    ///         Ok(receipt) => Ok(receipt),
1021    ///         Err(error) => {
1022    ///             pending.remove(&id); // Submission failed; remove the local record registered earlier.
1023    ///             Err(error)
1024    ///         }
1025    ///     }
1026    /// }
1027    /// ```
1028    pub fn commit(mut self) -> Result<MessageReceipt> {
1029        self.admission.commit()?;
1030        Ok(self.receipt.clone())
1031    }
1032}
1033impl fmt::Debug for PreparedMessage {
1034    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1035        f.debug_struct("PreparedMessage")
1036            .field("receipt", &self.receipt)
1037            .finish()
1038    }
1039}