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