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