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) => {
100 let provided = {
101 let _scope = crate::common::retirement::ExecutionScope::enter();
102 provider(attempt)
103 };
104 match provided {
106 Ok(future) => GuardedFuture::new(future).await,
107 Err(error) => Err(error),
108 }
109 }
110 ProviderKind::Blocking(provider) => {
111 run_blocking_with_spawn(provider.clone(), attempt, slots, |job| {
112 threads.spawn("open-net-ws-context-provider", job)
113 })
114 .await
115 }
116 };
117 result.map_err(|error| {
118 let mut context = error.context().clone();
119 context.client_id = Some(identity.0);
120 context.session_id = Some(identity.1);
121 context.attempt_id = Some(identity.2);
122 error.with_context(context)
123 })
124 }
125}
126
127impl fmt::Debug for HandshakeProvider {
128 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
129 let mode = match self.inner {
130 ProviderKind::Async(_) => "async",
131 ProviderKind::Blocking(_) => "blocking",
132 };
133 formatter
134 .debug_struct("HandshakeProvider")
135 .field("mode", &mode)
136 .finish_non_exhaustive()
137 }
138}
139
140#[derive(Clone)]
144pub struct HandshakeAttempt {
145 pub client_id: ClientId,
147 pub session_id: SessionId,
149 pub cycle_id: CycleId,
151 pub attempt_id: AttemptId,
153 pub metadata: Arc<Metadata>,
155}
156
157impl fmt::Debug for HandshakeAttempt {
158 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
159 formatter
160 .debug_struct("HandshakeAttempt")
161 .field("client_id", &self.client_id)
162 .field("session_id", &self.session_id)
163 .field("cycle_id", &self.cycle_id)
164 .field("attempt_id", &self.attempt_id)
165 .field("metadata_count", &self.metadata.len())
166 .finish()
167 }
168}
169
170#[derive(Clone)]
174pub struct HandshakeHeaders {
175 pub headers: HeaderMap,
179 pub credential_version: Option<String>,
182}
183
184impl HandshakeHeaders {
185 pub fn new(headers: HeaderMap) -> Self {
187 Self {
188 headers,
189 credential_version: None,
190 }
191 }
192}
193
194impl fmt::Debug for HandshakeHeaders {
195 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
196 formatter
197 .debug_struct("HandshakeHeaders")
198 .field("header_count", &self.headers.len())
199 .field(
200 "credential_version_bytes",
201 &self.credential_version.as_ref().map(String::len),
202 )
203 .finish()
204 }
205}
206
207pub(crate) fn validate_headers(headers: &HeaderMap) -> Result<()> {
208 use http::header::{CONNECTION, HOST, SEC_WEBSOCKET_KEY, SEC_WEBSOCKET_VERSION, UPGRADE};
209 if [
210 HOST,
211 CONNECTION,
212 UPGRADE,
213 SEC_WEBSOCKET_KEY,
214 SEC_WEBSOCKET_VERSION,
215 ]
216 .iter()
217 .any(|name| headers.contains_key(name))
218 {
219 return Err(NetError::input(
220 "headers",
221 "must not override SDK-managed WebSocket handshake headers",
222 ));
223 }
224 Ok(())
225}
226
227struct Owned<T> {
232 value: Option<T>,
235}
236
237impl<T> Owned<T> {
238 fn new(value: T) -> Self {
239 Self { value: Some(value) }
240 }
241 fn take(&mut self) -> Result<T> {
242 self.value.take().ok_or_else(internal_failure)
243 }
244}
245
246impl<T> Drop for Owned<T> {
247 fn drop(&mut self) {
248 retire(self.value.take());
249 }
250}
251
252fn retire<T>(value: T) -> bool {
253 match catch_unwind(AssertUnwindSafe(|| drop(value))) {
254 Ok(()) => false,
255 Err(payload) => {
256 crate::log_e!(crate::common::log::log_def::LogType::WSC;
257 "ws.handshake.retire", "arg_value|stage|error", "redacted", "provider", "user_value_cleanup_panicked");
258 dispose_payload(payload);
259 true
260 }
261 }
262}
263
264fn dispose_payload(payload: Box<dyn std::any::Any + Send>) {
265 if let Err(secondary) = catch_unwind(AssertUnwindSafe(|| drop(payload))) {
267 crate::log_e!(crate::common::log::log_def::LogType::WSC;
268 "ws.handshake.dispose_payload", "arg_payload|stage|error", "redacted", "provider", "panic_payload_cleanup_panicked");
269 std::mem::forget(secondary);
270 }
271}
272
273fn internal_failure() -> NetError {
274 NetError::from(ErrorKind::Internal).with_stage(ErrorStage::Provider)
275}
276
277fn callback_failure() -> NetError {
278 NetError::from(ErrorKind::CallbackPanicked).with_stage(ErrorStage::Provider)
279}
280
281fn caught<T>(outcome: std::thread::Result<T>) -> Result<T> {
282 outcome.map_err(|payload| {
283 dispose_payload(payload);
284 callback_failure()
285 })
286}
287
288fn resolve_provider_outcome(
289 outcome: std::thread::Result<ProviderOutput>,
290) -> Result<HandshakeHeaders> {
291 resolve_provider_output(caught(outcome)?)
292}
293
294fn resolve_provider_output(output: ProviderOutput) -> Result<HandshakeHeaders> {
295 let mut headers = Owned::new(output.map_err(NetError::provider)?);
296 if let Some(version) = headers
297 .value
298 .as_ref()
299 .and_then(|headers| headers.credential_version.as_deref())
300 {
301 super::value_limits::validate_credential_version(version)
302 .map_err(|error| error.with_stage(ErrorStage::Provider))?;
303 }
304 headers.take()
305}
306
307struct GuardedFuture {
310 future: Owned<ProviderFuture>,
312}
313
314impl GuardedFuture {
315 fn new(future: ProviderFuture) -> Self {
316 Self {
317 future: Owned::new(future),
318 }
319 }
320
321 fn complete_poll(
322 &mut self,
323 outcome: std::thread::Result<Poll<ProviderOutput>>,
324 ) -> Poll<Result<HandshakeHeaders>> {
325 match caught(outcome) {
326 Ok(Poll::Pending) => Poll::Pending,
327 Ok(Poll::Ready(output)) => {
328 let mut output = Owned::new(output);
329 if retire(self.future.value.take()) {
330 return Poll::Ready(Err(callback_failure()));
331 }
332 Poll::Ready(output.take().and_then(resolve_provider_output))
333 }
334 Err(error) => {
335 retire(self.future.value.take());
336 Poll::Ready(Err(error))
337 }
338 }
339 }
340}
341
342impl Future for GuardedFuture {
343 type Output = Result<HandshakeHeaders>;
344
345 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
346 let _scope = crate::common::retirement::ExecutionScope::enter();
347 let Some(future) = self.future.value.as_mut() else {
348 return Poll::Ready(Err(internal_failure()));
349 };
350 let outcome = catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx)));
351 self.complete_poll(outcome)
352 }
353}
354
355impl Drop for GuardedFuture {
356 fn drop(&mut self) {
357 let _scope = crate::common::retirement::ExecutionScope::enter();
358 retire(self.future.value.take());
359 }
360}
361
362async fn run_blocking_with_spawn(
363 provider: Arc<BlockingProvider>,
364 attempt: HandshakeAttempt,
365 slots: Arc<Semaphore>,
366 spawn: impl FnOnce(Box<dyn FnOnce() + Send + 'static>) -> std::io::Result<()>,
367) -> Result<HandshakeHeaders> {
368 let permit = slots.try_acquire_owned().map_err(|error| {
369 NetError::with_source(ErrorKind::ResourceExhausted, error).with_stage(ErrorStage::Provider)
370 })?;
371 let (sent, received) = oneshot::channel();
372 let job = Box::new(move || {
373 let _permit = permit;
374 let result = provider(attempt);
375 retire(provider);
377 if let Err(result) = sent.send(Owned::new(result)) {
378 drop(result);
379 }
380 });
381 spawn(job).map_err(|error| {
382 NetError::with_source(ErrorKind::RuntimeUnavailable, error).with_stage(ErrorStage::Provider)
383 })?;
384 let mut output = received.await.map_err(|error| {
385 NetError::with_source(ErrorKind::RuntimeUnavailable, error).with_stage(ErrorStage::Provider)
386 })?;
387 output.take()?
388}
389
390#[cfg(test)]
391#[path = "handshake_tests.rs"]
392mod tests;