Skip to main content

open_net/api/ws/
handshake.rs

1use super::{AttemptId, ClientId, CycleId, SessionId};
2use crate::error::{ErrorKind, ErrorStage};
3use crate::{BoxError, HeaderMap, Metadata, NetError, Result};
4use std::fmt;
5use std::future::Future;
6use std::panic::{catch_unwind, AssertUnwindSafe};
7use std::pin::Pin;
8use std::sync::Arc;
9use std::task::{Context, Poll};
10use tokio::sync::{oneshot, Semaphore};
11
12type ProviderOutput = std::result::Result<HandshakeHeaders, BoxError>;
13type ProviderFuture = Pin<Box<dyn Future<Output = ProviderOutput> + Send + 'static>>;
14type AsyncProvider = dyn Fn(HandshakeAttempt) -> Result<ProviderFuture> + Send + Sync;
15type BlockingProvider = dyn Fn(HandshakeAttempt) -> Result<HandshakeHeaders> + Send + Sync;
16
17/// Provider that generates dynamic request headers for each WebSocket handshake.
18/// It supports asynchronous and blocking callbacks; clones share the callback,
19/// and the SDK converts callback and future panics into classified errors.
20#[derive(Clone)]
21pub struct HandshakeProvider {
22    /// Shared callbacks and how they are executed.
23    inner: ProviderKind,
24}
25
26/// The internal implementation of the handshake request header provider.
27#[derive(Clone)]
28enum ProviderKind {
29    /// Future returned by the asynchronous callback.
30    Async(
31        /// Shared asynchronous callback that returns a future for computing
32        /// handshake request headers.
33        Arc<AsyncProvider>,
34    ),
35    /// Execute blocking callbacks on separate threads subject to concurrency quotas.
36    Blocking(
37        /// A shared blocking callback that directly returns handshake request headers or errors.
38        Arc<BlockingProvider>,
39    ),
40}
41
42impl HandshakeProvider {
43    /// Creates an asynchronous provider invoked for each handshake attempt.
44    ///
45    /// Callback panics and future polling failures are converted to classified errors.
46    pub fn new<F, Fut>(provider: F) -> Self
47    where
48        F: Fn(HandshakeAttempt) -> Fut + Send + Sync + 'static,
49        Fut: Future<Output = ProviderOutput> + Send + 'static,
50    {
51        let callback = Owned::new(provider);
52        Self {
53            inner: ProviderKind::Async(Arc::new(move |attempt| {
54                let provider = callback.value.as_ref().ok_or_else(internal_failure)?;
55                caught(catch_unwind(AssertUnwindSafe(|| provider(attempt))))
56                    .map(|future| Box::pin(future) as ProviderFuture)
57            })),
58        }
59    }
60
61    /// Creates a provider whose callback runs on a dedicated blocking worker.
62    ///
63    /// The configured blocking-handshake quota limits concurrent callback execution.
64    pub fn blocking<F>(provider: F) -> Self
65    where
66        F: Fn(HandshakeAttempt) -> ProviderOutput + Send + Sync + 'static,
67    {
68        let callback = Owned::new(provider);
69        Self {
70            inner: ProviderKind::Blocking(Arc::new(move |attempt| {
71                let provider = callback.value.as_ref().ok_or_else(internal_failure)?;
72                resolve_provider_outcome(catch_unwind(AssertUnwindSafe(|| provider(attempt))))
73            })),
74        }
75    }
76
77    #[cfg(test)]
78    pub(crate) async fn provide(
79        &self,
80        attempt: HandshakeAttempt,
81        slots: Arc<Semaphore>,
82    ) -> Result<HandshakeHeaders> {
83        self.provide_with_threads(
84            attempt,
85            slots,
86            Arc::new(crate::common::retirement::ThreadRegistry::new()),
87        )
88        .await
89    }
90
91    pub(crate) async fn provide_with_threads(
92        &self,
93        attempt: HandshakeAttempt,
94        slots: Arc<Semaphore>,
95        threads: Arc<crate::common::retirement::ThreadRegistry>,
96    ) -> Result<HandshakeHeaders> {
97        let identity = (attempt.client_id, attempt.session_id, attempt.attempt_id);
98        let result = match &self.inner {
99            ProviderKind::Async(provider) => match {
100                let _scope = crate::common::retirement::ExecutionScope::enter();
101                provider(attempt)
102            } {
103                Ok(future) => GuardedFuture::new(future).await,
104                Err(error) => Err(error),
105            },
106            ProviderKind::Blocking(provider) => {
107                run_blocking_with_spawn(provider.clone(), attempt, slots, |job| {
108                    threads.spawn("open-net-ws-context-provider", job)
109                })
110                .await
111            }
112        };
113        result.map_err(|error| {
114            let mut context = error.context().clone();
115            context.client_id = Some(identity.0);
116            context.session_id = Some(identity.1);
117            context.attempt_id = Some(identity.2);
118            error.with_context(context)
119        })
120    }
121}
122
123impl fmt::Debug for HandshakeProvider {
124    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
125        let mode = match self.inner {
126            ProviderKind::Async(_) => "async",
127            ProviderKind::Blocking(_) => "blocking",
128        };
129        formatter
130            .debug_struct("HandshakeProvider")
131            .field("mode", &mode)
132            .finish_non_exhaustive()
133    }
134}
135
136/// Identity and caller metadata for one handshake attempt, exposed to dynamic
137/// header callbacks and connection events. `Debug` reports only the metadata
138/// entry count and never its contents.
139#[derive(Clone)]
140pub struct HandshakeAttempt {
141    /// The ID of the client instance that initiated the handshake.
142    pub client_id: ClientId,
143    /// The connection session ID to which this attempt belongs.
144    pub session_id: SessionId,
145    /// The connection or reconnection cycle identifier to which this attempt belongs.
146    pub cycle_id: CycleId,
147    /// Identifies this specific handshake attempt.
148    pub attempt_id: AttemptId,
149    /// Shared metadata inherited from connection options; the SDK does not automatically send this as a request header.
150    pub metadata: Arc<Metadata>,
151}
152
153impl fmt::Debug for HandshakeAttempt {
154    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
155        formatter
156            .debug_struct("HandshakeAttempt")
157            .field("client_id", &self.client_id)
158            .field("session_id", &self.session_id)
159            .field("cycle_id", &self.cycle_id)
160            .field("attempt_id", &self.attempt_id)
161            .field("metadata_count", &self.metadata.len())
162            .finish()
163    }
164}
165
166/// Additional request headers and an optional credential-version marker returned
167/// by the dynamic handshake provider. `Debug` reports only the header count and
168/// version length, never their contents.
169#[derive(Clone)]
170pub struct HandshakeHeaders {
171    /// Additional request headers for this handshake. They must not override
172    /// SDK-managed `Host`, `Connection`, `Upgrade`, `Sec-WebSocket-Key`, or
173    /// `Sec-WebSocket-Version` headers.
174    pub headers: HeaderMap,
175    /// Credential version used to correlate connection and failure events, up to 256 UTF-8 bytes;
176    /// `None` means no version is provided, and the SDK does not automatically add this field to the request header.
177    pub credential_version: Option<String>,
178}
179
180impl HandshakeHeaders {
181    /// Creates handshake headers with no credential-version marker.
182    pub fn new(headers: HeaderMap) -> Self {
183        Self {
184            headers,
185            credential_version: None,
186        }
187    }
188}
189
190impl fmt::Debug for HandshakeHeaders {
191    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
192        formatter
193            .debug_struct("HandshakeHeaders")
194            .field("header_count", &self.headers.len())
195            .field(
196                "credential_version_bytes",
197                &self.credential_version.as_ref().map(String::len),
198            )
199            .finish()
200    }
201}
202
203pub(crate) fn validate_headers(headers: &HeaderMap) -> Result<()> {
204    use http::header::{CONNECTION, HOST, SEC_WEBSOCKET_KEY, SEC_WEBSOCKET_VERSION, UPGRADE};
205    if [
206        HOST,
207        CONNECTION,
208        UPGRADE,
209        SEC_WEBSOCKET_KEY,
210        SEC_WEBSOCKET_VERSION,
211    ]
212    .iter()
213    .any(|name| headers.contains_key(name))
214    {
215        return Err(NetError::input(
216            "headers",
217            "must not override SDK-managed WebSocket handshake headers",
218        ));
219    }
220    Ok(())
221}
222
223/// Wraps user values held by the SDK so they can be released without holding
224/// internal locks, while preventing destructor panics from escaping. Values
225/// handed to the caller are removed from this wrapper and then follow normal
226/// ownership rules.
227struct Owned<T> {
228    /// Value not yet handed over or released; `None` means this wrapper no
229    /// longer owns a value.
230    value: Option<T>,
231}
232
233impl<T> Owned<T> {
234    fn new(value: T) -> Self {
235        Self { value: Some(value) }
236    }
237    fn take(&mut self) -> Result<T> {
238        self.value.take().ok_or_else(internal_failure)
239    }
240}
241
242impl<T> Drop for Owned<T> {
243    fn drop(&mut self) {
244        retire(self.value.take());
245    }
246}
247
248fn retire<T>(value: T) -> bool {
249    match catch_unwind(AssertUnwindSafe(|| drop(value))) {
250        Ok(()) => false,
251        Err(payload) => {
252            crate::log_e!(crate::common::log::log_def::LogType::WSC;
253                "ws.handshake.retire", "arg_value|stage|error", "redacted", "provider", "user_value_cleanup_panicked");
254            dispose_payload(payload);
255            true
256        }
257    }
258}
259
260fn dispose_payload(payload: Box<dyn std::any::Any + Send>) {
261    // Only a second unwind while destroying a caught panic payload is abandoned.
262    if let Err(secondary) = catch_unwind(AssertUnwindSafe(|| drop(payload))) {
263        crate::log_e!(crate::common::log::log_def::LogType::WSC;
264            "ws.handshake.dispose_payload", "arg_payload|stage|error", "redacted", "provider", "panic_payload_cleanup_panicked");
265        std::mem::forget(secondary);
266    }
267}
268
269fn internal_failure() -> NetError {
270    NetError::from(ErrorKind::Internal).with_stage(ErrorStage::Provider)
271}
272
273fn callback_failure() -> NetError {
274    NetError::from(ErrorKind::CallbackPanicked).with_stage(ErrorStage::Provider)
275}
276
277fn caught<T>(outcome: std::thread::Result<T>) -> Result<T> {
278    outcome.map_err(|payload| {
279        dispose_payload(payload);
280        callback_failure()
281    })
282}
283
284fn resolve_provider_outcome(
285    outcome: std::thread::Result<ProviderOutput>,
286) -> Result<HandshakeHeaders> {
287    resolve_provider_output(caught(outcome)?)
288}
289
290fn resolve_provider_output(output: ProviderOutput) -> Result<HandshakeHeaders> {
291    let mut headers = Owned::new(output.map_err(NetError::provider)?);
292    if let Some(version) = headers
293        .value
294        .as_ref()
295        .and_then(|headers| headers.credential_version.as_deref())
296    {
297        super::value_limits::validate_credential_version(version)
298            .map_err(|error| error.with_stage(ErrorStage::Provider))?;
299    }
300    headers.take()
301}
302
303/// Future wrapper that isolates panics while an asynchronous handshake callback
304/// is polled or dropped.
305struct GuardedFuture {
306    /// User future protected during completion, failure, or cancellation cleanup.
307    future: Owned<ProviderFuture>,
308}
309
310impl GuardedFuture {
311    fn new(future: ProviderFuture) -> Self {
312        Self {
313            future: Owned::new(future),
314        }
315    }
316
317    fn complete_poll(
318        &mut self,
319        outcome: std::thread::Result<Poll<ProviderOutput>>,
320    ) -> Poll<Result<HandshakeHeaders>> {
321        match caught(outcome) {
322            Ok(Poll::Pending) => Poll::Pending,
323            Ok(Poll::Ready(output)) => {
324                let mut output = Owned::new(output);
325                if retire(self.future.value.take()) {
326                    return Poll::Ready(Err(callback_failure()));
327                }
328                Poll::Ready(output.take().and_then(resolve_provider_output))
329            }
330            Err(error) => {
331                retire(self.future.value.take());
332                Poll::Ready(Err(error))
333            }
334        }
335    }
336}
337
338impl Future for GuardedFuture {
339    type Output = Result<HandshakeHeaders>;
340
341    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
342        let _scope = crate::common::retirement::ExecutionScope::enter();
343        let Some(future) = self.future.value.as_mut() else {
344            return Poll::Ready(Err(internal_failure()));
345        };
346        let outcome = catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx)));
347        self.complete_poll(outcome)
348    }
349}
350
351impl Drop for GuardedFuture {
352    fn drop(&mut self) {
353        let _scope = crate::common::retirement::ExecutionScope::enter();
354        retire(self.future.value.take());
355    }
356}
357
358async fn run_blocking_with_spawn(
359    provider: Arc<BlockingProvider>,
360    attempt: HandshakeAttempt,
361    slots: Arc<Semaphore>,
362    spawn: impl FnOnce(Box<dyn FnOnce() + Send + 'static>) -> std::io::Result<()>,
363) -> Result<HandshakeHeaders> {
364    let permit = slots.try_acquire_owned().map_err(|error| {
365        NetError::with_source(ErrorKind::ResourceExhausted, error).with_stage(ErrorStage::Provider)
366    })?;
367    let (sent, received) = oneshot::channel();
368    let job = Box::new(move || {
369        let _permit = permit;
370        let result = provider(attempt);
371        // The real closure retains its quota through provider-capture and rejected-result cleanup.
372        retire(provider);
373        if let Err(result) = sent.send(Owned::new(result)) {
374            drop(result);
375        }
376    });
377    spawn(job).map_err(|error| {
378        NetError::with_source(ErrorKind::RuntimeUnavailable, error).with_stage(ErrorStage::Provider)
379    })?;
380    let mut output = received.await.map_err(|error| {
381        NetError::with_source(ErrorKind::RuntimeUnavailable, error).with_stage(ErrorStage::Provider)
382    })?;
383    output.take()?
384}
385
386#[cfg(test)]
387#[path = "handshake_tests.rs"]
388mod tests;