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 pub(crate) async fn provide(
78 &self,
79 attempt: HandshakeAttempt,
80 slots: Arc<Semaphore>,
81 ) -> Result<HandshakeHeaders> {
82 let identity = (attempt.client_id, attempt.session_id, attempt.attempt_id);
83 let result = match &self.inner {
84 ProviderKind::Async(provider) => match provider(attempt) {
85 Ok(future) => GuardedFuture::new(future).await,
86 Err(error) => Err(error),
87 },
88 ProviderKind::Blocking(provider) => {
89 run_blocking_with_spawn(provider.clone(), attempt, slots, |job| {
90 std::thread::Builder::new()
91 .name("open-net-ws-context-provider".to_owned())
92 .spawn(job)
93 })
94 .await
95 }
96 };
97 result.map_err(|error| {
98 let mut context = error.context().clone();
99 context.client_id = Some(identity.0);
100 context.session_id = Some(identity.1);
101 context.attempt_id = Some(identity.2);
102 error.with_context(context)
103 })
104 }
105}
106
107impl fmt::Debug for HandshakeProvider {
108 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
109 let mode = match self.inner {
110 ProviderKind::Async(_) => "async",
111 ProviderKind::Blocking(_) => "blocking",
112 };
113 formatter
114 .debug_struct("HandshakeProvider")
115 .field("mode", &mode)
116 .finish_non_exhaustive()
117 }
118}
119
120#[derive(Clone)]
124pub struct HandshakeAttempt {
125 pub client_id: ClientId,
127 pub session_id: SessionId,
129 pub cycle_id: CycleId,
131 pub attempt_id: AttemptId,
133 pub metadata: Arc<Metadata>,
135}
136
137impl fmt::Debug for HandshakeAttempt {
138 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
139 formatter
140 .debug_struct("HandshakeAttempt")
141 .field("client_id", &self.client_id)
142 .field("session_id", &self.session_id)
143 .field("cycle_id", &self.cycle_id)
144 .field("attempt_id", &self.attempt_id)
145 .field("metadata_count", &self.metadata.len())
146 .finish()
147 }
148}
149
150#[derive(Clone)]
154pub struct HandshakeHeaders {
155 pub headers: HeaderMap,
159 pub credential_version: Option<String>,
162}
163
164impl HandshakeHeaders {
165 pub fn new(headers: HeaderMap) -> Self {
167 Self {
168 headers,
169 credential_version: None,
170 }
171 }
172}
173
174impl fmt::Debug for HandshakeHeaders {
175 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
176 formatter
177 .debug_struct("HandshakeHeaders")
178 .field("header_count", &self.headers.len())
179 .field(
180 "credential_version_bytes",
181 &self.credential_version.as_ref().map(String::len),
182 )
183 .finish()
184 }
185}
186
187pub(crate) fn validate_headers(headers: &HeaderMap) -> Result<()> {
188 use http::header::{CONNECTION, HOST, SEC_WEBSOCKET_KEY, SEC_WEBSOCKET_VERSION, UPGRADE};
189 if [
190 HOST,
191 CONNECTION,
192 UPGRADE,
193 SEC_WEBSOCKET_KEY,
194 SEC_WEBSOCKET_VERSION,
195 ]
196 .iter()
197 .any(|name| headers.contains_key(name))
198 {
199 return Err(NetError::input(
200 "headers",
201 "must not override SDK-managed WebSocket handshake headers",
202 ));
203 }
204 Ok(())
205}
206
207struct Owned<T> {
212 value: Option<T>,
215}
216
217impl<T> Owned<T> {
218 fn new(value: T) -> Self {
219 Self { value: Some(value) }
220 }
221 fn take(&mut self) -> Result<T> {
222 self.value.take().ok_or_else(internal_failure)
223 }
224}
225
226impl<T> Drop for Owned<T> {
227 fn drop(&mut self) {
228 retire(self.value.take());
229 }
230}
231
232fn retire<T>(value: T) -> bool {
233 match catch_unwind(AssertUnwindSafe(|| drop(value))) {
234 Ok(()) => false,
235 Err(payload) => {
236 crate::log_e!(crate::common::log::log_def::LogType::WSC;
237 "handshake_provider", "stage|error", "provider", "user_value_cleanup_panicked");
238 dispose_payload(payload);
239 true
240 }
241 }
242}
243
244fn dispose_payload(payload: Box<dyn std::any::Any + Send>) {
245 if let Err(secondary) = catch_unwind(AssertUnwindSafe(|| drop(payload))) {
247 crate::log_e!(crate::common::log::log_def::LogType::WSC;
248 "handshake_provider", "stage|error", "provider", "panic_payload_cleanup_panicked");
249 std::mem::forget(secondary);
250 }
251}
252
253fn internal_failure() -> NetError {
254 NetError::from(ErrorKind::Internal).with_stage(ErrorStage::Provider)
255}
256
257fn callback_failure() -> NetError {
258 NetError::from(ErrorKind::CallbackPanicked).with_stage(ErrorStage::Provider)
259}
260
261fn caught<T>(outcome: std::thread::Result<T>) -> Result<T> {
262 outcome.map_err(|payload| {
263 dispose_payload(payload);
264 callback_failure()
265 })
266}
267
268fn resolve_provider_outcome(
269 outcome: std::thread::Result<ProviderOutput>,
270) -> Result<HandshakeHeaders> {
271 resolve_provider_output(caught(outcome)?)
272}
273
274fn resolve_provider_output(output: ProviderOutput) -> Result<HandshakeHeaders> {
275 let mut headers = Owned::new(output.map_err(NetError::provider)?);
276 if let Some(version) = headers
277 .value
278 .as_ref()
279 .and_then(|headers| headers.credential_version.as_deref())
280 {
281 super::value_limits::validate_credential_version(version)
282 .map_err(|error| error.with_stage(ErrorStage::Provider))?;
283 }
284 headers.take()
285}
286
287struct GuardedFuture {
290 future: Owned<ProviderFuture>,
292}
293
294impl GuardedFuture {
295 fn new(future: ProviderFuture) -> Self {
296 Self {
297 future: Owned::new(future),
298 }
299 }
300
301 fn complete_poll(
302 &mut self,
303 outcome: std::thread::Result<Poll<ProviderOutput>>,
304 ) -> Poll<Result<HandshakeHeaders>> {
305 match caught(outcome) {
306 Ok(Poll::Pending) => Poll::Pending,
307 Ok(Poll::Ready(output)) => {
308 let mut output = Owned::new(output);
309 if retire(self.future.value.take()) {
310 return Poll::Ready(Err(callback_failure()));
311 }
312 Poll::Ready(output.take().and_then(resolve_provider_output))
313 }
314 Err(error) => {
315 retire(self.future.value.take());
316 Poll::Ready(Err(error))
317 }
318 }
319 }
320}
321
322impl Future for GuardedFuture {
323 type Output = Result<HandshakeHeaders>;
324
325 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
326 let Some(future) = self.future.value.as_mut() else {
327 return Poll::Ready(Err(internal_failure()));
328 };
329 let outcome = catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx)));
330 self.complete_poll(outcome)
331 }
332}
333
334async fn run_blocking_with_spawn(
335 provider: Arc<BlockingProvider>,
336 attempt: HandshakeAttempt,
337 slots: Arc<Semaphore>,
338 spawn: impl FnOnce(
339 Box<dyn FnOnce() + Send + 'static>,
340 ) -> std::io::Result<std::thread::JoinHandle<()>>,
341) -> Result<HandshakeHeaders> {
342 let permit = slots.try_acquire_owned().map_err(|error| {
343 NetError::with_source(ErrorKind::ResourceExhausted, error).with_stage(ErrorStage::Provider)
344 })?;
345 let (sent, received) = oneshot::channel();
346 let job = Box::new(move || {
347 let _permit = permit;
348 let result = provider(attempt);
349 retire(provider);
351 if let Err(result) = sent.send(Owned::new(result)) {
352 drop(result);
353 }
354 });
355 spawn(job).map(drop).map_err(|error| {
356 NetError::with_source(ErrorKind::RuntimeUnavailable, error).with_stage(ErrorStage::Provider)
357 })?;
358 let mut output = received.await.map_err(|error| {
359 NetError::with_source(ErrorKind::RuntimeUnavailable, error).with_stage(ErrorStage::Provider)
360 })?;
361 output.take()?
362}
363
364#[cfg(test)]
365#[path = "handshake_tests.rs"]
366mod tests;