Skip to main content

fetchlet_http/actix_server/
service.rs

1use std::sync::Arc;
2
3use actix_web::{HttpRequest, HttpResponse, Route, web};
4use serde::Serialize;
5use serde_json::Value;
6
7use fetchlet::AppHandle;
8
9use super::body::{ForwardedBody, collect};
10use super::convert::{declared_body, request_head, response};
11use crate::{Error, PublicOrigin, RequestContext};
12
13type ContextFactory = Arc<dyn Fn(&HttpRequest) -> Result<Value, Error> + Send + Sync>;
14
15type TrustedContextFactory = Arc<dyn Fn(&HttpRequest) -> fetchlet::Context + Send + Sync>;
16
17type ErrorCallback = Arc<dyn Fn(&Error) + Send + Sync>;
18
19/// An actix-web handler for a shared fetchlet application.
20///
21/// The configured public origin supplies the scheme and authority; the
22/// incoming path, query, method, headers and body are kept. The default
23/// context's client address is the peer address. By default the payload is
24/// collected within the application's request body budget before the handler
25/// runs; [`ActixService::stream_request_bodies`] passes it as a stream.
26/// Responses keep repeated headers such as Set-Cookie and stream their bodies.
27/// Dropping the request, for example when the client disconnects, cancels the
28/// invocation.
29///
30/// With the `actix-websocket` feature, a handler accepts a WebSocket with
31/// `upgradeWebSocket(request)` from `fetchlet/runtime`, as with
32/// `AxumService`: the invocation holds one of
33/// `Instances::max_held_connections`, actix-ws completes the handshake, and
34/// messages cross between the connection and the handler's socket. With
35/// every place taken, an upgrade request is answered with 503 before
36/// JavaScript runs; with none configured, the handler sees it as an
37/// ordinary request.
38#[derive(Clone)]
39pub struct ActixService {
40    app: AppHandle,
41    origin: PublicOrigin,
42    context: Option<ContextFactory>,
43    trusted_context: Option<TrustedContextFactory>,
44    on_error: Option<ErrorCallback>,
45    stream_request_bodies: bool,
46}
47
48impl ActixService {
49    pub fn new(app: AppHandle, public_origin: &str) -> Result<Self, Error> {
50        Ok(Self {
51            app,
52            origin: PublicOrigin::parse(public_origin)?,
53            context: None,
54            trusted_context: None,
55            on_error: None,
56            stream_request_bodies: false,
57        })
58    }
59
60    /// Supply application metadata, the Fetch entry's second argument, in
61    /// place of the default [`RequestContext`].
62    pub fn context<C, F>(mut self, context: F) -> Self
63    where
64        C: Serialize,
65        F: Fn(&HttpRequest) -> C + Send + Sync + 'static,
66    {
67        self.context = Some(Arc::new(move |request| {
68            serde_json::to_value(context(request)).map_err(Error::Context)
69        }));
70        self
71    }
72
73    /// Derive the trusted [`fetchlet::Context`] of each request in Rust.
74    ///
75    /// The Context stays out of JavaScript and reaches in-process routes
76    /// registered with [`fetchlet::OriginRouter::internal`].
77    pub fn trusted_context(
78        mut self,
79        context: impl Fn(&HttpRequest) -> fetchlet::Context + Send + Sync + 'static,
80    ) -> Self {
81        self.trusted_context = Some(Arc::new(context));
82        self
83    }
84
85    /// Observe detailed errors in Rust while HTTP responses use general messages.
86    pub fn on_error(mut self, callback: impl Fn(&Error) + Send + Sync + 'static) -> Self {
87        self.on_error = Some(Arc::new(callback));
88        self
89    }
90
91    /// Pass incoming payloads to the handler as a stream instead of collecting them.
92    ///
93    /// A declared `Content-Length` over the request body budget is still
94    /// rejected with 413 before execution. Bytes over the budget without a
95    /// declared length, and payload failures, reach the handler as errors of
96    /// its body stream, so the handler decides the response status.
97    pub fn stream_request_bodies(mut self) -> Self {
98        self.stream_request_bodies = true;
99        self
100    }
101
102    /// A route for `App::default_service` or `App::route`.
103    pub fn route(self) -> Route {
104        web::to(move |request: HttpRequest, payload: web::Payload| {
105            let service = self.clone();
106            async move { service.handle(request, payload).await }
107        })
108    }
109
110    /// Answer a request, with general error responses.
111    ///
112    /// With the `actix-websocket` feature, a request that asks to upgrade to
113    /// WebSocket may hold its invocation as a connection; see
114    /// [`ActixService`].
115    pub async fn handle(&self, request: HttpRequest, payload: web::Payload) -> HttpResponse {
116        #[cfg(feature = "actix-websocket")]
117        if super::websocket::asks_for_upgrade(&request) {
118            return super::websocket::serve(self, request, payload).await;
119        }
120        match self.fetch(&request, payload).await {
121            Ok(answer) => response(answer),
122            Err(error) => self.error_response(&error),
123        }
124    }
125
126    /// A general error response, after the error callback observed it.
127    pub(super) fn error_response(&self, error: &Error) -> HttpResponse {
128        if let Some(callback) = &self.on_error {
129            callback(error);
130        }
131        response(error.response())
132    }
133
134    #[cfg(feature = "actix-websocket")]
135    pub(super) fn app(&self) -> &AppHandle {
136        &self.app
137    }
138
139    /// The request head with the public origin and the trusted context, and
140    /// the application metadata.
141    pub(super) fn prepare(
142        &self,
143        request: &HttpRequest,
144    ) -> Result<(http::request::Parts, Value), Error> {
145        let mut head = request_head(request, &self.origin)?;
146        let context = match &self.context {
147            Some(context) => context(request)?,
148            None => serde_json::to_value(RequestContext::new(
149                request.peer_addr().map(|address| address.ip()),
150            ))
151            .map_err(Error::Context)?,
152        };
153        if let Some(trusted) = &self.trusted_context {
154            head.extensions.insert(trusted(request));
155        }
156        Ok((head, context))
157    }
158
159    /// Run the handler, returning detailed errors.
160    pub async fn fetch(
161        &self,
162        request: &HttpRequest,
163        payload: web::Payload,
164    ) -> Result<http::Response<fetchlet::Body>, Error> {
165        let (head, context) = self.prepare(request)?;
166        let limit = self.app.limits().request_body_bytes;
167        let (declared, has_body) = declared_body(&head);
168        let body = if !has_body {
169            fetchlet::Body::empty()
170        } else if self.stream_request_bodies {
171            // The invocation checks the declared length and the bytes it reads.
172            fetchlet::Body::from_http_body(ForwardedBody::spawn(payload, declared))
173        } else {
174            if let (Some(limit), Some(declared)) = (limit, declared)
175                && declared > limit as u64
176            {
177                return Err(fetchlet::Error::LimitExceeded("request body bytes").into());
178            }
179            fetchlet::Body::from(collect(payload, limit).await?)
180        };
181        let request = http::Request::from_parts(head, body);
182        Ok(self.app.fetch_with_context(request, &context).await?)
183    }
184}