Skip to main content

open_net/api/ws/
request_control.rs

1use super::{
2    ConnectionId, OperationId, OperationSnapshot, RequestId, SessionId, TaskEndCause,
3    TerminationOutcome, WriteOutcome,
4};
5use crate::error::ErrorKind;
6use crate::module::ws_client::native_pending::NativePending;
7use crate::module::ws_client::operation_control::OperationControl;
8use crate::{Metadata, NetError, Result};
9use std::fmt;
10use std::sync::{Arc, Mutex, Weak};
11use std::time::Instant;
12
13/// Correlation credentials for one request registration.
14///
15/// The credential does not keep the pending-request table alive. Its token and
16/// table identity prevent a stale handle from terminating a later request that
17/// reuses the same protocol request ID.
18#[derive(Clone)]
19pub struct RequestRegistration {
20    /// Application-level identifier used to match a response.
21    request_id: RequestId,
22    /// Logical session that owns this registration.
23    session_id: SessionId,
24    /// Time at which the request entered the pending-response table.
25    registered_at: Instant,
26    /// Generation token distinguishing registrations that reuse a request ID.
27    token: u64,
28    /// Weak reference to the originating pending table, used for ownership
29    /// validation and termination.
30    pending: Weak<NativePending>,
31    /// Shared response-timing state. The deadline may be established lazily
32    /// when the request is written, and is shared by all credential clones.
33    timing: Arc<RegistrationTiming>,
34}
35
36/// Response-timing state shared by all handles for one registration.
37pub(crate) struct RegistrationTiming {
38    /// Original response deadline, excluding any bounded manual-dispatch grace
39    /// period. `None` means the deadline has not been established yet.
40    deadline: Mutex<Option<Instant>>,
41}
42
43impl RegistrationTiming {
44    pub(crate) fn new(deadline: Option<Instant>) -> Self {
45        Self {
46            deadline: Mutex::new(deadline),
47        }
48    }
49
50    pub(crate) fn deadline(&self) -> Result<Option<Instant>> {
51        self.deadline
52            .lock()
53            .map(|value| *value)
54            .map_err(NetError::from_poison)
55    }
56
57    pub(crate) fn establish(&self, deadline: Instant) -> Result<()> {
58        let mut current = self.deadline.lock().map_err(NetError::from_poison)?;
59        if current.is_none() {
60            *current = Some(deadline);
61        }
62        Ok(())
63    }
64}
65
66impl RequestRegistration {
67    pub(crate) fn new(
68        request_id: RequestId,
69        session_id: SessionId,
70        registered_at: Instant,
71        token: u64,
72        pending: Weak<NativePending>,
73        timing: Arc<RegistrationTiming>,
74    ) -> Self {
75        Self {
76            request_id,
77            session_id,
78            registered_at,
79            token,
80            pending,
81            timing,
82        }
83    }
84
85    /// Returns the application-level identifier used for response matching.
86    pub fn request_id(&self) -> &RequestId {
87        &self.request_id
88    }
89    /// Returns the logical session that owns this registration.
90    pub fn session_id(&self) -> SessionId {
91        self.session_id
92    }
93    /// Returns when this registration entered the pending table.
94    pub fn registered_at(&self) -> Instant {
95        self.registered_at
96    }
97
98    /// Returns the original response deadline, excluding bounded grace for
99    /// manual response dispatch.
100    pub fn response_deadline(&self) -> Result<Option<Instant>> {
101        self.timing.deadline()
102    }
103
104    pub(crate) fn token(&self) -> u64 {
105        self.token
106    }
107    pub(crate) fn pending(&self) -> Weak<NativePending> {
108        self.pending.clone()
109    }
110    pub(crate) fn belongs_to(&self, pending: &NativePending) -> bool {
111        std::ptr::eq(self.pending.as_ptr(), pending)
112    }
113}
114
115impl fmt::Debug for RequestRegistration {
116    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
117        formatter
118            .debug_struct("RequestRegistration")
119            .field("request_id", &self.request_id)
120            .field("session_id", &self.session_id)
121            .field("registered_at", &self.registered_at)
122            .field("response_deadline", &self.response_deadline())
123            .finish_non_exhaustive()
124    }
125}
126
127/// Stand-alone snapshot of a pending request at query time.
128///
129/// The snapshot does not retain the request payload and does not freeze later
130/// state transitions.
131///
132/// `Debug` summarizes the business identifier and metadata while retaining operation diagnostics.
133#[derive(Clone)]
134pub struct RequestSnapshot {
135    /// Identifier of the underlying send operation.
136    pub operation_id: OperationId,
137    /// Application-level identifier used to match a response.
138    pub request_id: RequestId,
139    /// Logical session that owns the request.
140    pub session_id: SessionId,
141    /// Physical connection assigned to the request, or `None` before one is
142    /// assigned.
143    pub connection_id: Option<ConnectionId>,
144    /// Time at which the request entered the pending-response table.
145    pub registered_at: Instant,
146    /// Original response deadline, excluding manual-dispatch grace; `None`
147    /// means no deadline has been established yet.
148    pub response_deadline: Option<Instant>,
149    /// Copy of the request metadata captured by this query.
150    pub metadata: Metadata,
151    /// Send-operation snapshot captured by the same query.
152    pub operation: OperationSnapshot,
153}
154
155impl fmt::Debug for RequestSnapshot {
156    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
157        formatter
158            .debug_struct("RequestSnapshot")
159            .field("operation_id", &self.operation_id)
160            .field("request_id", &self.request_id)
161            .field("session_id", &self.session_id)
162            .field("connection_id", &self.connection_id)
163            .field("registered_at", &self.registered_at)
164            .field("response_deadline", &self.response_deadline)
165            .field("metadata_entries", &self.metadata.len())
166            .field("operation", &self.operation)
167            .finish()
168    }
169}
170
171/// Shareable handle for observing or explicitly terminating a request.
172///
173/// The handle does not retain the request payload. Clones operate on the same
174/// operation, while the registration credential keeps termination scoped to
175/// the original registration.
176#[derive(Clone)]
177pub struct RequestHandle {
178    /// Shared operation state used to observe write progress and the terminal
179    /// result.
180    core: Arc<OperationControl>,
181    /// Registration credential that prevents terminating a later request with
182    /// the same protocol identifier.
183    registration: RequestRegistration,
184}
185
186impl RequestHandle {
187    /// Returns the `WsRequest` diagnostic reference for this request registration.
188    ///
189    /// The SDK allocates the observation while preparing admission and binds it to
190    /// this registration's operation control. It can include queueing, local
191    /// transport writing, response matching, and delivery boundaries when those
192    /// phases were observed. For a retried logical request, this reference belongs
193    /// to an individual registration; the enclosing
194    /// [`super::WsRequestOperationHandle::quality_ref`] identifies its parent
195    /// logical operation when both observations were retained.
196    ///
197    /// `None` means no observation was allocated, including Off/dormant or excluded
198    /// WebSocket collection, unavailable owner, or exhausted diagnostic capacity.
199    /// Reading this value does not activate collection or wait for a response.
200    /// Resolve it with the owning engine's `QualityDoctor::lookup`; references
201    /// neither pin reports nor guarantee that all phase events were retained.
202    #[cfg(feature = "quality-doctor")]
203    pub fn quality_ref(&self) -> Option<crate::api::quality::QualityReportRef> {
204        self.core.quality_ref()
205    }
206    #[cfg(feature = "quality-doctor")]
207    pub(crate) fn quality_parent(&self, parent: crate::api::quality::QualityReportRef) {
208        if let Some(probe) = self.core.quality() {
209            probe.parent(parent);
210        }
211    }
212    pub(crate) fn retry_report(&self) -> crate::api::retry::RetryReport {
213        self.core.retry_report()
214    }
215
216    pub(crate) fn has_selected_result(&self) -> bool {
217        self.core.is_finished()
218    }
219
220    /// Compete with response/failure selection under the same pending/core
221    /// authority, then let the existing response channel publish that winner.
222    pub(crate) fn expire_operation_attempt(&self) {
223        self.core
224            .prepare_termination(self.core.deadline_error(), TaskEndCause::Expired)
225            .dispatch();
226    }
227
228    pub(crate) fn new(core: Arc<OperationControl>, registration: RequestRegistration) -> Self {
229        Self { core, registration }
230    }
231    /// Returns the identifier of the underlying send operation.
232    pub fn id(&self) -> OperationId {
233        self.core.id()
234    }
235    /// Returns the application-level request identifier used for response matching.
236    pub fn request_id(&self) -> &RequestId {
237        self.registration.request_id()
238    }
239    /// Returns the registration credential associated with this handle.
240    pub fn registration(&self) -> &RequestRegistration {
241        &self.registration
242    }
243    /// Reads a point-in-time snapshot of the request's send operation.
244    pub fn state(&self) -> Result<OperationSnapshot> {
245        self.core.snapshot()
246    }
247    /// Requests cancellation before delivery, or after delivery while waiting
248    /// for a response. The returned outcome describes the race with completion.
249    pub fn cancel(&self) -> Result<TerminationOutcome> {
250        self.terminate(
251            NetError::from(ErrorKind::Cancelled),
252            TaskEndCause::Cancelled,
253        )
254    }
255    /// Marks the request as expired and applies the same race rules as
256    /// [`Self::cancel`].
257    pub fn expire(&self) -> Result<TerminationOutcome> {
258        self.terminate(NetError::from(ErrorKind::TimedOut), TaskEndCause::Expired)
259    }
260    /// Waits until the underlying message has completed its local write.
261    ///
262    /// This does not mean that the peer received or processed the message;
263    /// response completion is reported by the request's response receiver.
264    pub async fn written(&self) -> Result<WriteOutcome> {
265        self.core.written().await
266    }
267
268    fn terminate(&self, error: NetError, cause: TaskEndCause) -> Result<TerminationOutcome> {
269        if let Some(pending) = self.registration.pending.upgrade() {
270            pending.terminate(self.request_id(), self.registration.token, error, cause)
271        } else if self.core.snapshot()?.result.is_some() {
272            Ok(TerminationOutcome::AlreadyFinished)
273        } else {
274            Err(NetError::from(ErrorKind::EngineDropped))
275        }
276    }
277}
278
279impl fmt::Debug for RequestHandle {
280    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
281        formatter
282            .debug_struct("RequestHandle")
283            .field("id", &self.id())
284            .field("registration", &self.registration)
285            .field("state", &self.state())
286            .finish()
287    }
288}