Skip to main content

rings_node/onion/native/
mod.rs

1//! The native handle of a node's onion runtime: `tcp` streams, `https` requests, and multi-stage
2//! `invoke` Kleisli pipelines over client-sealed loops.
3
4use std::time::Duration;
5
6use crate::error::Error;
7use crate::error::Result;
8use crate::onion::circuit::OnionInvokeBackend;
9use crate::onion::https::OnionHttpsCall;
10use crate::onion::https::OnionHttpsClient;
11use crate::onion::https::OnionHttpsResponse;
12use crate::onion::invoke_descriptor::OnionInvokePolicy;
13use crate::onion::pipeline::OnionInvokePipeline;
14use crate::onion::proxy::OnionProxyProtocol;
15use crate::onion::proxy::OnionProxyRoute;
16use crate::onion::route::OnionPipelineRoute;
17use crate::onion::runtime::OnionRuntime;
18use crate::onion::session::client::OnionCreditWindow;
19use crate::onion::session::dial::OnionSessionRequest;
20use crate::onion::signature::OnionBackendName;
21use crate::onion::signature::OnionInvokeShape;
22use crate::onion::tcp::NativeOnionOpenStream;
23use crate::onion::udp::NativeOnionUdpSession;
24use crate::onion::udp::OnionUdpBindMode;
25use crate::onion::OnionLoopClass;
26use crate::onion::OnionProxyTarget;
27use crate::onion::OnionRoute;
28use crate::onion::OnionRouteError;
29use crate::onion::OnionServiceName;
30use crate::processor::Processor;
31
32/// Native handle for TCP streams, HTTPS requests, and Kleisli pipelines over onion loops.
33#[derive(Clone)]
34pub struct NativeOnionCircuitHandle {
35    /// The installed runtime.
36    runtime: OnionRuntime,
37}
38
39impl NativeOnionCircuitHandle {
40    /// The native handle of `runtime`, which a provider installed once in its registry
41    /// ([`Provider::onion_circuit`](crate::provider::Provider::onion_circuit)).
42    pub(crate) const fn new(runtime: OnionRuntime) -> Self {
43        Self { runtime }
44    }
45
46    /// Register an intermediate `invoke` backend `⟦(shape, backend)⟧` on this node's Σ-algebra
47    /// (#834 D2). If the node's role already advertises `(shape, backend)` in its
48    /// [`crate::onion::OnionInvokeOffer`], that signed quota policy takes precedence over `policy`.
49    pub fn register_invoke(
50        &self,
51        shape: OnionInvokeShape,
52        backend: OnionBackendName,
53        policy: OnionInvokePolicy,
54        backend_impl: impl OnionInvokeBackend + 'static,
55    ) -> Result<()> {
56        self.runtime
57            .register_invoke(shape, backend, policy, backend_impl)
58    }
59
60    /// Select a multi-stage route for `pipeline` from `processor`'s directory and evaluate it at
61    /// `pipeline.loop_class()` (#834 D4, L3).
62    pub async fn invoke_pipeline(
63        &self,
64        processor: &Processor,
65        pipeline: &OnionInvokePipeline,
66        input: &[u8],
67    ) -> Result<Vec<u8>> {
68        let route = processor.build_onion_pipeline_route(pipeline).await?;
69        self.invoke_pipeline_over_route(&route, pipeline, input)
70            .await
71    }
72
73    /// Evaluate `pipeline` over an already selected `route` at `pipeline.loop_class()` (#834 L3).
74    pub async fn invoke_pipeline_over_route(
75        &self,
76        route: &OnionPipelineRoute,
77        pipeline: &OnionInvokePipeline,
78        input: &[u8],
79    ) -> Result<Vec<u8>> {
80        self.invoke_pipeline_over_route_with_options(
81            route,
82            pipeline,
83            pipeline.loop_class(),
84            input,
85            None,
86        )
87        .await
88    }
89
90    /// Evaluate `pipeline` over `route` at explicit loop `class` and optional caller `timeout`
91    /// (clamped to the loop's expiry `x`).
92    pub async fn invoke_pipeline_over_route_with_options(
93        &self,
94        route: &OnionPipelineRoute,
95        pipeline: &OnionInvokePipeline,
96        class: OnionLoopClass,
97        input: &[u8],
98        timeout: Option<Duration>,
99    ) -> Result<Vec<u8>> {
100        self.runtime
101            .invoke_with_class_and_timeout(route, pipeline, class, input, timeout)
102            .await
103    }
104
105    /// Select a `tcp` route to `target` from `processor`'s directory and open a session over it
106    /// at [`OnionLoopClass::DEFAULT`].
107    pub async fn open_tcp_target(
108        &self,
109        processor: &Processor,
110        target: OnionProxyTarget,
111    ) -> Result<NativeOnionOpenStream> {
112        self.open_tcp_target_with_class(processor, target, OnionLoopClass::DEFAULT)
113            .await
114    }
115
116    /// Select a `tcp` route to `target` from `processor`'s directory and open a session of loop
117    /// class `class` (`b`) over it.
118    pub async fn open_tcp_target_with_class(
119        &self,
120        processor: &Processor,
121        target: OnionProxyTarget,
122        class: OnionLoopClass,
123    ) -> Result<NativeOnionOpenStream> {
124        let route = processor
125            .build_onion_proxy_route(OnionProxyProtocol::TcpConnect, target)
126            .await?;
127        self.open_tcp_stream_with_class(route.route, route.target, class)
128            .await
129    }
130
131    /// Open a `tcp` session over `route` at [`OnionLoopClass::DEFAULT`] and wait until the exit
132    /// has connected `target`.
133    pub async fn open_tcp_stream(
134        &self,
135        route: OnionRoute,
136        target: OnionProxyTarget,
137    ) -> Result<NativeOnionOpenStream> {
138        self.open_tcp_stream_with_class(route, target, OnionLoopClass::DEFAULT)
139            .await
140    }
141
142    /// Open a `tcp` session of loop class `class` (`b`) over `route` and wait until the exit has
143    /// connected `target`.
144    pub async fn open_tcp_stream_with_class(
145        &self,
146        route: OnionRoute,
147        target: OnionProxyTarget,
148        class: OnionLoopClass,
149    ) -> Result<NativeOnionOpenStream> {
150        if route.service_name() != &OnionServiceName::tcp() {
151            return Err(Error::OnionRouteError(
152                OnionRouteError::PayloadServiceMismatch {
153                    payload_service: OnionServiceName::tcp().as_str().to_string(),
154                    route_service: route.service().to_string(),
155                },
156            ));
157        }
158        self.runtime
159            .open(OnionSessionRequest {
160                route,
161                symbol: OnionServiceName::tcp(),
162                target,
163                class,
164                window: OnionCreditWindow::DEFAULT,
165            })
166            .await
167            .map(NativeOnionOpenStream::new)
168    }
169
170    /// Select a `udp` route for `mode` from `processor`'s directory and open an unconnected OS UDP
171    /// datagram session at [`OnionLoopClass::DEFAULT`], awaiting the exit's bound endpoint.
172    pub async fn open_udp_target(
173        &self,
174        processor: &Processor,
175        mode: OnionUdpBindMode,
176    ) -> Result<NativeOnionUdpSession> {
177        self.open_udp_target_with_class(processor, mode, OnionLoopClass::DEFAULT)
178            .await
179    }
180
181    /// Select a `udp` route for `mode` from `processor`'s directory and open an unconnected OS UDP
182    /// datagram session of loop class `class` (`b`), awaiting the exit's bound endpoint.
183    pub async fn open_udp_target_with_class(
184        &self,
185        processor: &Processor,
186        mode: OnionUdpBindMode,
187        class: OnionLoopClass,
188    ) -> Result<NativeOnionUdpSession> {
189        let route = processor
190            .build_onion_proxy_route(OnionProxyProtocol::UdpDatagram, mode.to_target())
191            .await?;
192        let resolved_mode = OnionUdpBindMode::from_target(&route.target)?;
193        self.open_udp_session_with_class(route.route, resolved_mode, class)
194            .await
195    }
196
197    /// Open a `udp` session over `route` at [`OnionLoopClass::DEFAULT`] and await the exit's bound
198    /// socket endpoint.
199    pub async fn open_udp_session(
200        &self,
201        route: OnionRoute,
202        mode: OnionUdpBindMode,
203    ) -> Result<NativeOnionUdpSession> {
204        self.open_udp_session_with_class(route, mode, OnionLoopClass::DEFAULT)
205            .await
206    }
207
208    /// Open a `udp` session of loop class `class` (`b`) over `route` and await the exit's bound
209    /// socket endpoint.
210    pub async fn open_udp_session_with_class(
211        &self,
212        route: OnionRoute,
213        mode: OnionUdpBindMode,
214        class: OnionLoopClass,
215    ) -> Result<NativeOnionUdpSession> {
216        if route.service_name() != &OnionServiceName::udp() {
217            return Err(Error::OnionRouteError(
218                OnionRouteError::PayloadServiceMismatch {
219                    payload_service: OnionServiceName::udp().as_str().to_string(),
220                    route_service: route.service().to_string(),
221                },
222            ));
223        }
224        let stream = self
225            .runtime
226            .open(OnionSessionRequest {
227                route,
228                symbol: OnionServiceName::udp(),
229                target: mode.to_target(),
230                class,
231                window: OnionCreditWindow::DEFAULT,
232            })
233            .await?;
234        NativeOnionUdpSession::from_stream(stream).await
235    }
236
237    /// Send `call` to `route.target` over `route` and wait for the exit's response.
238    pub async fn request_https(
239        &self,
240        route: &OnionProxyRoute,
241        call: OnionHttpsCall,
242    ) -> Result<OnionHttpsResponse> {
243        OnionHttpsClient::new(self.runtime.clone())
244            .request(route, call)
245            .await
246    }
247
248    /// Send `call` to `route.target` over `route` in a session of loop class `class` (`b`) and
249    /// wait for the exit's response.
250    pub async fn request_https_with_class(
251        &self,
252        route: &OnionProxyRoute,
253        call: OnionHttpsCall,
254        class: OnionLoopClass,
255    ) -> Result<OnionHttpsResponse> {
256        OnionHttpsClient::new(self.runtime.clone())
257            .request_with_class(route, call, class)
258            .await
259    }
260}
261
262#[cfg(test)]
263mod tests;