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