Skip to main content

open_net/api/ws/
routing.rs

1use 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
9/// Application-defined protocol that classifies inbound messages for request correlation.
10pub trait ResponseProtocol: Send + Sync + 'static {
11    /// Classifies one inbound message without mutating the session.
12    fn route(&self, incoming: &IncomingMessage) -> std::result::Result<ResponseRoute, BoxError>;
13}
14
15/// Correlation classification produced for one inbound message.
16#[derive(Clone, Debug)]
17pub enum ResponseRoute {
18    /// The message does not match any pending request.
19    Unmatched,
20    /// An intermediate message that leaves the request pending.
21    Intermediate {
22        /// Identifier of the request receiving the intermediate message.
23        request_id: RequestId,
24    },
25    /// A final response that completes the request.
26    Final {
27        /// Identifier of the completed request.
28        request_id: RequestId,
29    },
30}
31
32/// Strategy used to associate inbound messages with requests.
33#[derive(Clone, Default)]
34pub enum ResponseRouting {
35    /// Disable correlation; the session cannot expose request completions.
36    #[default]
37    Disabled,
38    /// Classify messages automatically with an application protocol.
39    Protocol(
40        /// Shared, thread-safe classifier implementation.
41        Arc<dyn ResponseProtocol>,
42    ),
43    /// Let application code resolve requests explicitly with a resolver token.
44    Manual,
45}
46
47impl ResponseRouting {
48    /// Wraps a protocol implementation for use by one or more sessions.
49    pub fn protocol<P: ResponseProtocol>(protocol: P) -> Self {
50        Self::Protocol(Arc::new(protocol))
51    }
52
53    /// Classifies a message before locking the pending-request table.
54    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                // A user panic payload may itself contain a panicking destructor.
66                // Isolate its retirement independently from the protocol invocation.
67                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/// Resolver for manual routing; it can complete registrations from its own session only.
87#[derive(Clone)]
88pub struct ResponseResolver {
89    /// Weak reference to the pending table; does not keep the session alive.
90    pending: Weak<NativePending>,
91}
92
93impl ResponseResolver {
94    /// Resolves an inbound business message against a request registration.
95    pub(crate) fn new(pending: Weak<NativePending>) -> Self {
96        Self { pending }
97    }
98    /// Associates a business message with a request registration from this resolver's session.
99    ///
100    /// Returns whether the registration was completed, stale, or owned by another origin.
101    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, &registration.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/// Result of manually associating an inbound message with a request registration.
131#[derive(Clone, Copy, Debug, Eq, PartialEq)]
132pub enum ResolveOutcome {
133    /// The response was accepted and the request completed.
134    Resolved,
135    /// The registration or dispatch token was stale, expired, or already finished.
136    StaleOrFinished,
137    /// The registration or message belongs to another resolver, session, or connection.
138    ForeignOrigin,
139}