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(|_| {
163                crate::log_e!(crate::LogType::WSC; "ws.request.response",
164                    "session_id|operation_id", self.handle.registration().session_id().as_u64(), self.handle.id().as_u64());
165                NetError::from(ErrorKind::EngineDropped)
166            })?
167    }
168}
169/// Request that has registered and reserved send resources but has not yet been
170/// submitted. Dropping it cancels the reservation and operation.
171#[must_use]
172pub struct PreparedRequest {
173    /// Send-queue reservation and cancellation cleanup for an unsubmitted request.
174    admission: dispatch::Admission,
175    /// Observation and termination handle registered for this request.
176    handle: RequestHandle,
177    /// Response receiver handed to the submission receipt; `None` after commit
178    /// takes ownership of it.
179    response: Option<oneshot::Receiver<Result<Response>>>,
180}
181impl PreparedRequest {
182    fn new(mut admission: dispatch::Admission) -> Result<Self> {
183        let (handle, response) = admission.request.take().ok_or_else(|| {
184            dispatch::log_invariant(&admission.control, "request_registration_missing");
185            NetError::from(ErrorKind::Internal)
186        })?;
187        Ok(Self {
188            admission,
189            handle,
190            response: Some(response),
191        })
192    }
193    /// Borrows the request handle before commit.
194    pub fn handle(&self) -> &RequestHandle {
195        &self.handle
196    }
197    /// Commits the reservation and returns a receipt for the same operation.
198    ///
199    /// This is a local synchronous transition: it does not wait for a network
200    /// write or a peer response. Cancellation, close, or an expired deadline can
201    /// still make the commit fail.
202    pub fn commit(mut self) -> Result<RequestReceipt> {
203        let response = self.response.take().ok_or_else(|| {
204            dispatch::log_invariant(&self.admission.control, "prepared_response_missing");
205            NetError::from(ErrorKind::Internal)
206        })?;
207        self.admission.commit()?;
208        Ok(RequestReceipt {
209            handle: self.handle.clone(),
210            response,
211        })
212    }
213}
214impl fmt::Debug for PreparedRequest {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        f.debug_struct("PreparedRequest")
217            .field("handle", &self.handle)
218            .finish()
219    }
220}