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#[derive(Clone)]
21pub struct HandshakeProvider {
22 inner: ProviderKind,
24}
25
26#[derive(Clone)]
28enum ProviderKind {
29 Async(
31 Arc<AsyncProvider>,
34 ),
35 Blocking(
37 Arc<BlockingProvider>,
39 ),
40}
41
42impl HandshakeProvider {
43 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 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#[derive(Clone)]
140pub struct HandshakeAttempt {
141 pub client_id: ClientId,
143 pub session_id: SessionId,
145 pub cycle_id: CycleId,
147 pub attempt_id: AttemptId,
149 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#[derive(Clone)]
170pub struct HandshakeHeaders {
171 pub headers: HeaderMap,
175 pub credential_version: Option<String>,
178}
179
180impl HandshakeHeaders {
181 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
223struct Owned<T> {
228 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 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
303struct GuardedFuture {
306 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 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;