Skip to main content

open_net/api/ws/
request_client.rs

1use super::{
2    dispatch, Request, RequestHandle, RequestOptions, RequestSnapshot, Response, SessionId,
3};
4use crate::error::ErrorKind;
5use crate::module::ws_client::session_runtime::SessionRuntime;
6use crate::{EnqueueError, NetError, Result};
7use std::fmt;
8use std::sync::Arc;
9use std::time::Instant;
10use tokio::sync::oneshot;
11
12/// Request entry point bound to one session. It constructs requests and
13/// exposes snapshots of requests awaiting responses.
14#[derive(Clone)]
15pub struct RequestClient {
16    /// Shared session runtime and pending-request table.
17    pub(crate) runtime: Arc<SessionRuntime>,
18}
19impl RequestClient {
20    /// Returns the logical session identifier for this request entry point.
21    pub fn session_id(&self) -> SessionId {
22        self.runtime.id
23    }
24    /// Creates a builder for a request owned by this session.
25    pub fn request(&self, request: Request) -> RequestBuilder {
26        RequestBuilder {
27            client: self.clone(),
28            request,
29            options: RequestOptions::default(),
30            admission_started: None,
31        }
32    }
33    /// Enqueues a request and waits for its final response.
34    ///
35    /// The returned error covers admission, local writing, cancellation, and
36    /// response timeout; a successful response means the response was routed to
37    /// this request, not that any separate application side effect is committed.
38    pub async fn execute(&self, request: Request) -> Result<Response> {
39        self.request(request).send().await
40    }
41    /// Returns snapshots of requests currently waiting for responses.
42    pub fn pending_snapshot(&self) -> Result<Vec<RequestSnapshot>> {
43        self.runtime.pending.snapshot()
44    }
45}
46impl fmt::Debug for RequestClient {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        f.debug_struct("RequestClient")
49            .field("session_id", &self.session_id())
50            .finish()
51    }
52}
53/// Holds request content and execution options. If registration or enqueueing
54/// fails, the builder is returned with the error for inspection or retry.
55#[must_use]
56#[derive(Debug)]
57pub struct RequestBuilder {
58    /// Session and pending-response table used by this request.
59    client: RequestClient,
60    /// The request ID, message, and metadata to be sent.
61    request: Request,
62    /// The sending, registration and response waiting strategies for this request.
63    options: RequestOptions,
64    /// Time of the first registration or enqueue attempt; `None` before an
65    /// attempt or after options have been reset.
66    admission_started: Option<Instant>,
67}
68impl RequestBuilder {
69    /// Replaces all request options and resets the admission-time origin.
70    pub fn options(mut self, options: RequestOptions) -> Self {
71        self.options = options;
72        self.admission_started = None;
73        self
74    }
75    /// Admits the request and waits for its final response.
76    pub async fn send(self) -> Result<Response> {
77        self.enqueue()
78            .await
79            .map_err(EnqueueError::into_error)?
80            .response()
81            .await
82    }
83    /// Waits for admission, commits the request, and returns a response receipt.
84    ///
85    /// On failure, the error retains this builder so the request can be inspected
86    /// or retried without reconstructing its message.
87    pub async fn enqueue(mut self) -> std::result::Result<RequestReceipt, EnqueueError<Self>> {
88        match self.admit().await.and_then(PreparedRequest::commit) {
89            Ok(receipt) => Ok(receipt),
90            Err(error) => Err(EnqueueError::new(self, error)),
91        }
92    }
93    /// Attempts admission without waiting for queue capacity.
94    pub fn try_enqueue(mut self) -> std::result::Result<RequestReceipt, EnqueueError<Self>> {
95        match self.try_admit().and_then(PreparedRequest::commit) {
96            Ok(receipt) => Ok(receipt),
97            Err(error) => Err(EnqueueError::new(self, error)),
98        }
99    }
100    /// Waits for admission and returns a reserved request that is not committed.
101    ///
102    /// Dropping the prepared value cancels the reservation and releases its
103    /// capacity; call [`PreparedRequest::commit`] to make it eligible for send.
104    pub async fn prepare(mut self) -> std::result::Result<PreparedRequest, EnqueueError<Self>> {
105        match self.admit().await {
106            Ok(prepared) => Ok(prepared),
107            Err(error) => Err(EnqueueError::new(self, error)),
108        }
109    }
110    /// Attempts to reserve request resources without waiting for capacity.
111    pub fn try_prepare(mut self) -> std::result::Result<PreparedRequest, EnqueueError<Self>> {
112        match self.try_admit() {
113            Ok(prepared) => Ok(prepared),
114            Err(error) => Err(EnqueueError::new(self, error)),
115        }
116    }
117    async fn admit(&mut self) -> Result<PreparedRequest> {
118        let started = *self.admission_started.get_or_insert_with(Instant::now);
119        let admission = dispatch::prepare(
120            &self.client.runtime,
121            self.request.message(),
122            &self.options.send,
123            started,
124            Some((&self.request, &self.options)),
125            true,
126        )
127        .await?;
128        PreparedRequest::new(admission)
129    }
130    fn try_admit(&mut self) -> Result<PreparedRequest> {
131        let started = *self.admission_started.get_or_insert_with(Instant::now);
132        let admission = dispatch::try_prepare(
133            &self.client.runtime,
134            self.request.message(),
135            &self.options.send,
136            started,
137            Some((&self.request, &self.options)),
138        )?;
139        PreparedRequest::new(admission)
140    }
141}
142/// A receipt for a submitted request, holding a control handle and a response receiver that can only be consumed once.
143#[must_use]
144#[derive(Debug)]
145pub struct RequestReceipt {
146    /// Independently cloneable request observation and termination handles.
147    handle: RequestHandle,
148    /// A one-time channel to receive the final response or the reason why the request failed.
149    response: oneshot::Receiver<Result<Response>>,
150}
151impl RequestReceipt {
152    /// Borrows the handle used to observe or terminate this request.
153    pub fn handle(&self) -> &RequestHandle {
154        &self.handle
155    }
156    /// Waits for the response or the request's terminal failure.
157    ///
158    /// Dropping this future stops waiting but does not cancel the request.
159    pub async fn response(self) -> Result<Response> {
160        self.response
161            .await
162            .map_err(|_| NetError::from(ErrorKind::EngineDropped))?
163    }
164}
165/// Request that has registered and reserved send resources but has not yet been
166/// submitted. Dropping it cancels the reservation and operation.
167#[must_use]
168pub struct PreparedRequest {
169    /// Send-queue reservation and cancellation cleanup for an unsubmitted request.
170    admission: dispatch::Admission,
171    /// Observation and termination handle registered for this request.
172    handle: RequestHandle,
173    /// Response receiver handed to the submission receipt; `None` after commit
174    /// takes ownership of it.
175    response: Option<oneshot::Receiver<Result<Response>>>,
176}
177impl PreparedRequest {
178    fn new(mut admission: dispatch::Admission) -> Result<Self> {
179        let (handle, response) = admission
180            .request
181            .take()
182            .ok_or_else(|| NetError::from(ErrorKind::Internal))?;
183        Ok(Self {
184            admission,
185            handle,
186            response: Some(response),
187        })
188    }
189    /// Borrows the request handle before commit.
190    pub fn handle(&self) -> &RequestHandle {
191        &self.handle
192    }
193    /// Commits the reservation and returns a receipt for the same operation.
194    ///
195    /// This is a local synchronous transition: it does not wait for a network
196    /// write or a peer response. Cancellation, close, or an expired deadline can
197    /// still make the commit fail.
198    pub fn commit(mut self) -> Result<RequestReceipt> {
199        let response = self
200            .response
201            .take()
202            .ok_or_else(|| NetError::from(ErrorKind::Internal))?;
203        self.admission.commit()?;
204        Ok(RequestReceipt {
205            handle: self.handle.clone(),
206            response,
207        })
208    }
209}
210impl fmt::Debug for PreparedRequest {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        f.debug_struct("PreparedRequest")
213            .field("handle", &self.handle)
214            .finish()
215    }
216}