open_net/api/ws/
routing.rs1use super::{IncomingMessage, RequestId, RequestRegistration};
2use crate::error::{ErrorKind, ErrorStage};
3use crate::module::ws_client::native_pending::NativePending;
4use crate::{BoxError, NetError, Result};
5use std::fmt;
6use std::panic::{catch_unwind, AssertUnwindSafe};
7use std::sync::{Arc, Weak};
8
9pub trait ResponseProtocol: Send + Sync + 'static {
11 fn route(&self, incoming: &IncomingMessage) -> std::result::Result<ResponseRoute, BoxError>;
13}
14
15#[derive(Clone, Debug)]
17pub enum ResponseRoute {
18 Unmatched,
20 Intermediate {
22 request_id: RequestId,
24 },
25 Final {
27 request_id: RequestId,
29 },
30}
31
32#[derive(Clone, Default)]
34pub enum ResponseRouting {
35 #[default]
37 Disabled,
38 Protocol(
40 Arc<dyn ResponseProtocol>,
42 ),
43 Manual,
45}
46
47impl ResponseRouting {
48 pub fn protocol<P: ResponseProtocol>(protocol: P) -> Self {
50 Self::Protocol(Arc::new(protocol))
51 }
52
53 pub(crate) fn route(&self, incoming: &IncomingMessage) -> Result<ResponseRoute> {
55 let Self::Protocol(protocol) = self else {
56 return Ok(ResponseRoute::Unmatched);
57 };
58 match catch_unwind(AssertUnwindSafe(|| protocol.route(incoming))) {
59 Ok(Ok(route)) => Ok(route),
60 Ok(Err(error)) => {
61 Err(NetError::with_source(ErrorKind::Protocol, error)
62 .with_stage(ErrorStage::Response))
63 }
64 Err(payload) => {
65 if let Err(second_payload) = catch_unwind(AssertUnwindSafe(|| drop(payload))) {
68 std::mem::forget(second_payload);
69 }
70 Err(NetError::from(ErrorKind::CallbackPanicked).with_stage(ErrorStage::Response))
71 }
72 }
73 }
74}
75
76impl fmt::Debug for ResponseRouting {
77 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
78 formatter.write_str(match self {
79 Self::Disabled => "Disabled",
80 Self::Protocol(_) => "Protocol",
81 Self::Manual => "Manual",
82 })
83 }
84}
85
86#[derive(Clone)]
88pub struct ResponseResolver {
89 pending: Weak<NativePending>,
91}
92
93impl ResponseResolver {
94 pub(crate) fn new(pending: Weak<NativePending>) -> Self {
96 Self { pending }
97 }
98 pub fn resolve(
102 &self,
103 registration: &RequestRegistration,
104 incoming: &IncomingMessage,
105 ) -> Result<ResolveOutcome> {
106 if incoming.message().is_none() {
107 return Err(NetError::input(
108 "incoming",
109 "control frames cannot complete a request",
110 ));
111 }
112 if !Weak::ptr_eq(&self.pending, ®istration.pending()) {
113 return Ok(ResolveOutcome::ForeignOrigin);
114 }
115 match self.pending.upgrade() {
116 Some(pending) => pending.resolve(registration, incoming),
117 None => Ok(ResolveOutcome::StaleOrFinished),
118 }
119 }
120}
121
122impl fmt::Debug for ResponseResolver {
123 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
124 formatter
125 .debug_struct("ResponseResolver")
126 .finish_non_exhaustive()
127 }
128}
129
130#[derive(Clone, Copy, Debug, Eq, PartialEq)]
132pub enum ResolveOutcome {
133 Resolved,
135 StaleOrFinished,
137 ForeignOrigin,
139}