Skip to main content

MessageBuilder

Struct MessageBuilder 

Source
pub struct MessageBuilder { /* private fields */ }
Expand description

Holds a message and its sending options; both can be recovered from an enqueue error.

The builder does not send by itself; resources are requested only when a send, enqueue, or prepare method is called. Dropping an unused builder only drops the message body.

Implementations§

Source§

impl MessageBuilder

Source

pub fn options(self, options: SendOptions) -> Self

Replaces all sending options for this message and resets the enqueue-wait start time.

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. An absolute deadline supplied in the options is not moved forward automatically.

§Use cases

Set a priority, timeout, cancellation group, or disconnect-wait policy for one message 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. WaitForReconnect lets an unsent message wait for a connection, but does not enable the session’s reconnection policy by itself.

§Example
use open_net::{
    ws::{DisconnectedPolicy, SendOptions, Sender},
    Result,
};
use std::time::{Duration, Instant};

async fn publish_latest_state(sender: &Sender) -> Result<()> {
    sender
        .message("state:active")
        .options(SendOptions {
            disconnected: DisconnectedPolicy::WaitForReconnect,
            enqueue_timeout: Some(Duration::from_secs(2)),
            deadline: Some(Instant::now() + Duration::from_secs(15)),
            ..Default::default()
        })
        .send()
        .await
}
Source

pub async fn send(self) -> Result<()>

Enqueues the message according to the configured policy and waits for its local WebSocket write to complete.

§Use cases

Suitable for sequential workflows that customize one message but do not need to manage a 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 server processed the message; use the session request interface when a protocol response is required.

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 Self::enqueue to obtain a receipt and then call MessageReceipt::cancel.

§Example
use open_net::{
    ws::{SendOptions, Sender},
    Result,
};
use std::time::{Duration, Instant};

async fn publish_with_deadline(sender: &Sender) -> Result<()> {
    sender
        .message("status:ready")
        .options(SendOptions {
            deadline: Some(Instant::now() + Duration::from_secs(5)),
            ..Default::default()
        })
        .send()
        .await?;
    Ok(())
}
Source

pub async fn enqueue(self) -> Result<MessageReceipt, EnqueueError<Self>>

Waits for resources according to the configured policy, submits the message, and returns a receipt without waiting for the write to complete.

When capacity is unavailable, waits asynchronously subject to enqueue_timeout, the overall deadline, cancellation, and session state. A failed EnqueueError retains the complete builder, including the message, options, and the start time of the first resource attempt; retrying that builder directly does not restore a full enqueue-timeout budget.

§Use cases

Suitable when a send needs a custom priority or deadline while another task tracks the write. Use Self::prepare when resources should be reserved first and sending should be allowed only after local business state has been recorded.

§Example
use open_net::{
    ws::{MessageReceipt, Priority, SendOptions, Sender},
    Result,
};
use std::time::Duration;

async fn queue_alert(sender: &Sender) -> Result<MessageReceipt> {
    let receipt = sender
        .message("alert:disk-low")
        .options(SendOptions {
            priority: Priority::High,
            enqueue_timeout: Some(Duration::from_millis(500)),
            ..Default::default()
        })
        .enqueue()
        .await?;
    println!("Enqueued operation: {}", receipt.id());
    Ok(receipt) // The caller can await receipt.written() later.
}
Source

pub fn try_enqueue(self) -> Result<MessageReceipt, EnqueueError<Self>>

Attempts to enqueue immediately under the configured policy, without waiting for send resources.

Unlike Self::enqueue, returns crate::error::ErrorKind::QueueFull immediately when resources are unavailable; all other validation, cancellation, and deadline rules still apply. Failure retains the complete builder and the initial enqueue timestamp, so asynchronous enqueue can continue waiting. This method does not require the calling thread to enter a Tokio runtime.

§Use cases

Suitable for paths that try a fast submission first and, on backpressure, either wait or hand the work to an application scheduler. Retrying the recovered builder preserves its priority and other settings; the message need not be reconstructed.

§Example
use open_net::{error::ErrorKind, ws::{SendOptions, Sender}, Result};
use std::time::Duration;

async fn submit_or_wait(sender: &Sender) -> Result<()> {
    let builder = sender.message("report:ready").options(SendOptions {
        enqueue_timeout: Some(Duration::from_secs(1)), ..Default::default()
    });
    let receipt = match builder.try_enqueue() {
        Ok(receipt) => receipt,
        Err(failure) if failure.error().kind() == ErrorKind::QueueFull => {
            // Continue the original one-second enqueue budget instead of resetting it on every retry.
            failure.into_inner().enqueue().await?
        }
        Err(failure) => return Err(failure.into_error()),
    };
    receipt.written().await
}
Source

pub async fn prepare(self) -> Result<PreparedMessage, EnqueueError<Self>>

Waits for and reserves send resources, returning a message that has not yet been submitted to the writer.

Uses the same resource-wait, timeout, and cancellation policies as Self::enqueue, but requires a subsequent call to PreparedMessage::commit to send. On failure, the complete builder can be recovered. On success, a receipt can be obtained first; dropping the PreparedMessage directly cancels the operation and releases the reserved resources.

§Use cases

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 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 succeed. enqueue_timeout limits only the wait to acquire resources, not the interval between a successful reservation and commit.

§Example
use open_net::{ws::Sender, Result};

async fn publish_if_needed(sender: &Sender, still_needed: bool) -> Result<()> {
    let prepared = sender.message("refresh:inventory").prepare().await?;
    println!(
        "Registered operation before sending: {}",
        prepared.receipt().id()
    );
    if !still_needed {
        drop(prepared); // It was not submitted, so this message will not be written.
        return Ok(());
    }
    let receipt = prepared.commit()?;
    receipt.written().await
}
Source

pub fn try_prepare(self) -> Result<PreparedMessage, EnqueueError<Self>>

Attempts to reserve send resources immediately, without waiting for capacity or submitting the message.

Returns crate::error::ErrorKind::QueueFull when resources are unavailable; all other validation, cancellation, and deadline rules are the same as for Self::prepare. Failure retains the complete builder and its original admission timestamp. After success, 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.

§Use cases

Suitable for optional reporting from a synchronous callback: record and submit only when 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.

§Example
use open_net::{
    error::ErrorKind,
    ws::{MessageReceipt, Sender},
    Result,
};

fn submit_optional_report(sender: &Sender) -> Result<Option<MessageReceipt>> {
    let prepared = match sender.message("metrics:snapshot").try_prepare() {
        Ok(prepared) => prepared,
        Err(failure) if failure.error().kind() == ErrorKind::QueueFull => {
            return Ok(None); // This sample may be skipped without blocking the callback.
        }
        Err(failure) => return Err(failure.into_error()),
    };
    println!(
        "Registered operation before commit: {}",
        prepared.receipt().id()
    );
    Ok(Some(prepared.commit()?))
}

Trait Implementations§

Source§

impl Debug for MessageBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more