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    ///
13    /// Runs synchronously on the connection's receive task, before publication
14    /// to application receivers. Keep it short and nonblocking: blocking I/O,
15    /// sleeping, or expensive parsing delays subsequent frames, including
16    /// heartbeat Pongs. Offload heavy processing after minimal classification,
17    /// or use [`ResponseRouting::Manual`] for application-owned resolution.
18    fn route(&self, incoming: &IncomingMessage) -> std::result::Result<ResponseRoute, BoxError>;
19}
20
21/// Correlation classification produced for one inbound message.
22#[derive(Clone, Debug)]
23pub enum ResponseRoute {
24    /// The message does not match any pending request.
25    Unmatched,
26    /// An intermediate message that leaves the request pending.
27    Intermediate {
28        /// Identifier of the request receiving the intermediate message.
29        request_id: RequestId,
30    },
31    /// A final response that completes the request.
32    Final {
33        /// Identifier of the completed request.
34        request_id: RequestId,
35    },
36}
37
38/// Strategy used to associate inbound messages with requests.
39#[derive(Clone, Default)]
40pub enum ResponseRouting {
41    /// Disable correlation; the session cannot expose request completions.
42    #[default]
43    Disabled,
44    /// Classify messages automatically with an application protocol.
45    Protocol(
46        /// Shared, thread-safe classifier implementation.
47        Arc<dyn ResponseProtocol>,
48    ),
49    /// Let application code resolve requests explicitly with a resolver token.
50    Manual,
51}
52
53impl ResponseRouting {
54    /// Wraps a protocol implementation for use by one or more sessions.
55    pub fn protocol<P: ResponseProtocol>(protocol: P) -> Self {
56        Self::Protocol(Arc::new(protocol))
57    }
58
59    /// Classifies a message before locking the pending-request table.
60    pub(crate) fn route(&self, incoming: &IncomingMessage) -> Result<ResponseRoute> {
61        let Self::Protocol(protocol) = self else {
62            return Ok(ResponseRoute::Unmatched);
63        };
64        match catch_unwind(AssertUnwindSafe(|| protocol.route(incoming))) {
65            Ok(Ok(route)) => Ok(route),
66            Ok(Err(error)) => {
67                Err(NetError::with_source(ErrorKind::Protocol, error)
68                    .with_stage(ErrorStage::Response))
69            }
70            Err(payload) => {
71                // A user panic payload may itself contain a panicking destructor.
72                // Isolate its retirement independently from the protocol invocation.
73                if let Err(second_payload) = catch_unwind(AssertUnwindSafe(|| drop(payload))) {
74                    std::mem::forget(second_payload);
75                }
76                Err(NetError::from(ErrorKind::CallbackPanicked).with_stage(ErrorStage::Response))
77            }
78        }
79    }
80}
81
82impl fmt::Debug for ResponseRouting {
83    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
84        formatter.write_str(match self {
85            Self::Disabled => "Disabled",
86            Self::Protocol(_) => "Protocol",
87            Self::Manual => "Manual",
88        })
89    }
90}
91
92/// Resolver for manual routing; it can complete registrations from its own session only.
93#[derive(Clone)]
94pub struct ResponseResolver {
95    /// Weak reference to the pending table; does not keep the session alive.
96    pending: Weak<NativePending>,
97}
98
99impl ResponseResolver {
100    /// Resolves an inbound business message against a request registration.
101    pub(crate) fn new(pending: Weak<NativePending>) -> Self {
102        Self { pending }
103    }
104    /// Associates a business message with a request registration from this resolver's session.
105    ///
106    /// Returns whether the registration was completed, stale, or owned by another origin.
107    pub fn resolve(
108        &self,
109        registration: &RequestRegistration,
110        incoming: &IncomingMessage,
111    ) -> Result<ResolveOutcome> {
112        if incoming.message().is_none() {
113            return Err(NetError::input(
114                "incoming",
115                "control frames cannot complete a request",
116            ));
117        }
118        if !Weak::ptr_eq(&self.pending, &registration.pending()) {
119            return Ok(ResolveOutcome::ForeignOrigin);
120        }
121        match self.pending.upgrade() {
122            Some(pending) => pending.resolve(registration, incoming),
123            None => Ok(ResolveOutcome::StaleOrFinished),
124        }
125    }
126}
127
128impl fmt::Debug for ResponseResolver {
129    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
130        formatter
131            .debug_struct("ResponseResolver")
132            .finish_non_exhaustive()
133    }
134}
135
136/// Result of manually associating an inbound message with a request registration.
137#[derive(Clone, Copy, Debug, Eq, PartialEq)]
138pub enum ResolveOutcome {
139    /// The response was accepted and the request completed.
140    Resolved,
141    /// The registration or dispatch token was stale, expired, or already finished.
142    StaleOrFinished,
143    /// The registration or message belongs to another resolver, session, or connection.
144    ForeignOrigin,
145}