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#[derive(Clone, Debug)]
132pub struct RequestSnapshot {
133    /// Identifier of the underlying send operation.
134    pub operation_id: OperationId,
135    /// Application-level identifier used to match a response.
136    pub request_id: RequestId,
137    /// Logical session that owns the request.
138    pub session_id: SessionId,
139    /// Physical connection assigned to the request, or `None` before one is
140    /// assigned.
141    pub connection_id: Option<ConnectionId>,
142    /// Time at which the request entered the pending-response table.
143    pub registered_at: Instant,
144    /// Original response deadline, excluding manual-dispatch grace; `None`
145    /// means no deadline has been established yet.
146    pub response_deadline: Option<Instant>,
147    /// Copy of the request metadata captured by this query.
148    pub metadata: Metadata,
149    /// Send-operation snapshot captured by the same query.
150    pub operation: OperationSnapshot,
151}
152
153/// Shareable handle for observing or explicitly terminating a request.
154///
155/// The handle does not retain the request payload. Clones operate on the same
156/// operation, while the registration credential keeps termination scoped to
157/// the original registration.
158#[derive(Clone)]
159pub struct RequestHandle {
160    /// Shared operation state used to observe write progress and the terminal
161    /// result.
162    core: Arc<OperationControl>,
163    /// Registration credential that prevents terminating a later request with
164    /// the same protocol identifier.
165    registration: RequestRegistration,
166}
167
168impl RequestHandle {
169    pub(crate) fn new(core: Arc<OperationControl>, registration: RequestRegistration) -> Self {
170        Self { core, registration }
171    }
172    /// Returns the identifier of the underlying send operation.
173    pub fn id(&self) -> OperationId {
174        self.core.id()
175    }
176    /// Returns the application-level request identifier used for response matching.
177    pub fn request_id(&self) -> &RequestId {
178        self.registration.request_id()
179    }
180    /// Returns the registration credential associated with this handle.
181    pub fn registration(&self) -> &RequestRegistration {
182        &self.registration
183    }
184    /// Reads a point-in-time snapshot of the request's send operation.
185    pub fn state(&self) -> Result<OperationSnapshot> {
186        self.core.snapshot()
187    }
188    /// Requests cancellation before delivery, or after delivery while waiting
189    /// for a response. The returned outcome describes the race with completion.
190    pub fn cancel(&self) -> Result<TerminationOutcome> {
191        self.terminate(
192            NetError::from(ErrorKind::Cancelled),
193            TaskEndCause::Cancelled,
194        )
195    }
196    /// Marks the request as expired and applies the same race rules as
197    /// [`Self::cancel`].
198    pub fn expire(&self) -> Result<TerminationOutcome> {
199        self.terminate(NetError::from(ErrorKind::TimedOut), TaskEndCause::Expired)
200    }
201    /// Waits until the underlying message has completed its local write.
202    ///
203    /// This does not mean that the peer received or processed the message;
204    /// response completion is reported by the request's response receiver.
205    pub async fn written(&self) -> Result<WriteOutcome> {
206        self.core.written().await
207    }
208
209    fn terminate(&self, error: NetError, cause: TaskEndCause) -> Result<TerminationOutcome> {
210        if let Some(pending) = self.registration.pending.upgrade() {
211            pending.terminate(self.request_id(), self.registration.token, error, cause)
212        } else if self.core.snapshot()?.result.is_some() {
213            Ok(TerminationOutcome::AlreadyFinished)
214        } else {
215            Err(NetError::from(ErrorKind::EngineDropped))
216        }
217    }
218}
219
220impl fmt::Debug for RequestHandle {
221    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
222        formatter
223            .debug_struct("RequestHandle")
224            .field("id", &self.id())
225            .field("registration", &self.registration)
226            .field("state", &self.state())
227            .finish()
228    }
229}