//! The http-shaped seam every webview host adapter shares. //! //! //! //! A hosted axum route and a Tauri custom-protocol handler are the same //! function wearing two coats. Both are handed a verb, a path, a query string //! and maybe a form body; both owe back a status, some headers and a rendered //! body; and both are talking to htmx on the other side. The coats are the //! parts that differ, and they are thin: how the bytes arrive, and which thread //! is allowed to block. //! //! So the middle lives here, in `http` types that neither host owns, and a host //! adapter is left with only its own coat. [`quasi_axum`] was the first caller //! and carried this code inline; the Tauri adapter is the second, and the //! [`htmx`] module said in its own doc comment that it would move when that //! happened. //! //! # What is here //! //! - [`decode`], which turns a request into the [`Method`], path and [`Params`] //! the router takes. [`quasi_router`] deliberately parses neither a query //! string nor a form body, because every host already has that code. //! - [`respond`] and [`refuse`], which turn the router's answer, or the //! adapter's own refusal, into a response. //! - [`Serves`], the seam to markup, which is a parameter rather than an //! implementation for the reason its own docs give. //! - [`htmx`], the two response headers and one client configuration an http //! host has to know to speak the webview transport correctly. //! //! # What is not here //! //! Anything that knows which host it is in. There is no runtime, no thread and //! no socket in this crate, and nothing in it is `async`: the blocking hop is a //! host's own problem and the two hosts solve it differently. That is what //! keeps this callable from a Tauri protocol handler, which has no executor of //! its own to hand work to. //! //! [`quasi_axum`]: https://makenot.work/git/max/quasi use quasi_router::{ Action, Address, Destination, Method, Node, Outcome, Params, Request, Response, RouteError, }; pub mod htmx; pub mod serves; pub use crate::serves::Serves; /// How much of a form body is read before the request is refused. /// /// A description-layer form is fields and choices, so a request an order of /// magnitude past this is a mistake or an attack rather than a long answer. /// File uploads do not come through here: a byte stream is not something a /// description describes, and each host keeps its own path for them. pub const DEFAULT_BODY_LIMIT: usize = 256 * 1024; /// The verbs the description layer has, as an `Allow` header value. /// /// Must list exactly what `translate` accepts, or the header promises a verb /// the decoder refuses. `PATCH` is the one HTTP has that this does not: nothing /// in either app writes one, and a verb with no consumer is a verb whose /// meaning nobody has had to decide. pub const ALLOWED_METHODS: &str = "GET, POST, DELETE, PUT"; /// A request, in the terms the router takes. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Incoming { /// Asking or telling. pub method: Method, /// The path, with no scheme, host or query on it. pub path: String, /// The form body: what the control sent. Empty on a read. pub payload: Params, /// The query string: the view the control was offered under. pub carried: Params, } /// What was asked, kept back so the answer can be placed in history. /// /// [`Incoming`] is consumed by the router, and the two facts history needs — was /// this a read, and of what address — outlive it. Taken here rather than /// re-derived from the http request, so the URL a push carries is exactly the /// one the route was reached at, params and all. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Asked { /// Asking or telling. Only a read can be a place. pub method: Method, /// The address this request was made at, carried params included. pub url: String, } impl Asked { /// What a request was, before the router takes it. #[must_use] pub fn new(incoming: &Incoming) -> Self { Self { method: incoming.method, url: route_url(&incoming.path, &incoming.carried), } } } impl From for Request { fn from(incoming: Incoming) -> Self { Self { method: incoming.method, path: incoming.path, captures: Params::new(), payload: incoming.payload, carried: incoming.carried, } } } /// A request the adapter turns away without troubling the router. /// /// Three, and all three are about the envelope rather than the address. A /// missing route is not here: that is a [`RouteError`] from the router, it is /// classified, and it renders a notice like any other failure. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Refusal { /// A verb the description layer does not have. Method, /// A form body past the limit. TooLarge, /// A form body that is not UTF-8. Malformed, } impl Refusal { /// The status this refusal answers with. #[must_use] pub const fn status(self) -> u16 { match self { Self::Method => 405, Self::TooLarge => 413, Self::Malformed => 400, } } } /// Read a request into the router's terms. /// /// `body` is the bytes the host already has. Reading them is the host's job /// because the two hosts read them differently, and by the time either calls /// this the read has happened. /// /// # The two halves stay apart /// /// The form body and the query string used to be absorbed into one bag here, /// form first, so that a form field beat a query argument of the same name. /// That merge was the bug: a screen carrying its view in the address sends its /// filters on every control, so a write about the same noun the filter filters /// on ended up with two meanings for one name and the handler read whichever /// landed first. goingson's mail screen met it twice in one afternoon. /// /// They are two things and they arrive separately, which is what HTTP already /// says: the query is where you are, the body is what you are telling it. The /// router adds the path captures as a third bag, since a capture is the route's /// own and was sent by nobody. pub fn decode( method: &http::Method, uri: &http::Uri, headers: &http::HeaderMap, body: &[u8], body_limit: usize, ) -> Result { let method = translate(method).ok_or(Refusal::Method)?; let mut payload = Params::new(); if method.mutates() && is_form(headers) { if body.len() > body_limit { return Err(Refusal::TooLarge); } let text = std::str::from_utf8(body).map_err(|_| Refusal::Malformed)?; payload.absorb(decode_pairs(text)); } Ok(Incoming { method, path: uri.path().to_owned(), payload, carried: decode_pairs(uri.query().unwrap_or_default()), }) } /// Turn the router's answer into a response. /// /// Takes the `Result` whole rather than the two halves separately, because a /// failure is not a special case here: it becomes a [`Node::Notice`] and is /// rendered as a fragment down the same path as everything else. That is /// decision 9 holding at the boundary and not only in the router. /// /// A host with a way of failing the router does not have, such as a panicking /// handler or a worker that died, reports it as /// [`RouteError::internal`] and gets the same treatment. pub fn respond( render: &R, outcome: Result, asked: &Asked, ) -> http::Response> { match outcome { Ok(answer) => { // Whether this answer is a place, decided here because this is the // one point that holds both halves: what was asked, and what the // router did about it. A control cannot know the second, which is // why no `hx-push-url` is ever emitted into markup. let address = placement(&answer, asked); // The notice is orthogonal to the outcome and is applied to all // three, including a redirect, which has no body to carry one. let trigger = answer .notice .as_ref() .map(|notice| htmx::notice_trigger(notice.kind, notice.tone, ¬ice.text)); let mut response = match answer.outcome { // An invalidation is not applied to a whole screen, and that is // not a case being dropped. Every slot is being replaced // already, so an out-of-band copy would be a second element // carrying an id the document now has twice. A handler that // says `.also()` on a screen is stating something the answer // already made true. Outcome::Screen(screen) => body(render, 200, render.screen(&screen), None), Outcome::Fragment { region, node } => { // The router said what it changed, so the client is told // rather than left to infer it from which element was // clicked. The webview renderer owes every slot an `id` // matching its `Slot::id` for this to land. // // The other slots the answer changed ride along behind the // targeted one, each named rather than aimed. Appended in // the order the router gave them, because a renderer // reordering them would be inventing a fact the response // did not state. let mut markup = render.fragment(&node); for stale in &answer.invalidates { markup.push_str(&render.invalidated(&stale.region, &stale.node)); } body(render, 200, markup, Some(format!("#{region}"))) } // Nor to a redirect, which has no body to carry one. The // destination answers next and answers with everything. Outcome::Goto(action) => redirect(&action), // Over what is already there. The retarget is the whole // difference from a screen: the answer lands in the overlay // container and the document under it is left alone. A // renderer with no such container says so by answering `None`, // and its `overlay` draws the screen instead. Outcome::Over(screen) => { let target = render.overlay_target().map(|id| format!("#{id}")); body(render, 200, render.overlay(&screen), target) } }; if let Some(trigger) = trigger && let Ok(value) = http::HeaderValue::from_str(&trigger) { response.headers_mut().insert(htmx::TRIGGER, value); } if let Some((header, url)) = address && let Ok(value) = http::HeaderValue::from_str(&url) { response.headers_mut().insert(header, value); } response } Err(error) => { let node = Node::Notice { kind: error.notice, tone: error.tone(), text: error.message.clone(), }; body( render, error.class.http_status(), render.fragment(&node), None, ) } } } /// Which history header this answer earns, and what address it carries. /// /// The override first, then the derivation, because the whole point of /// [`Address`] is to be able to say something the derivation cannot reach. /// /// The derivation: /// /// - a read answering with a whole screen is a place, at the address it was /// read from /// - a write answering with a screen is not: the address is where the form was, /// and going back to it should not re-offer the write's result as a page /// - a fragment is not a place, unless it says otherwise. This is where the /// addressable tab panel says otherwise /// - a [`Goto`](Outcome::Goto) sets nothing, because /// [`HX-Location`](htmx::LOCATION) issues the request client-side and htmx /// pushes for it, and [`HX-Redirect`](htmx::REDIRECT) is a real navigation fn placement(answer: &Response, asked: &Asked) -> Option<(&'static str, String)> { match &answer.address { Some(Address::Enters(url)) => return Some((htmx::PUSH_URL, url.clone())), Some(Address::Replaces(url)) => return Some((htmx::REPLACE_URL, url.clone())), Some(Address::Unchanged) => return None, None => {} } match answer.outcome { Outcome::Screen(_) if asked.method == Method::Get => { Some((htmx::PUSH_URL, asked.url.clone())) } _ => None, } } /// Send the user somewhere instead of answering with content. /// /// 200 and an empty body, with the whole answer in the header. See /// [`htmx::LOCATION`] for why this is not a 303. /// /// A route keeps its params, because a redirect back to a filtered list that /// drops the filter is a different place. An external address is taken as /// written: a `mailto:` or a `file://` has no query string this router built. fn redirect(action: &Action) -> http::Response> { let (header, address) = match &action.destination { // The view, not the payload. Going somewhere is an address, and an // address is what `carried` holds; a redirect that dropped the filter // would land on an unfiltered list. Destination::Route(path) => (htmx::LOCATION, route_url(path, &action.carried)), Destination::External(address) => (htmx::REDIRECT, address.clone()), }; let mut builder = http::Response::builder().status(200); if let Ok(value) = http::HeaderValue::from_str(&address) { builder = builder.header(header, value); } builder .body(Vec::new()) .expect("a response with no body and one checked header is always valid") } /// A route with its parameters folded into a query string. /// /// Encoded here rather than in the router, for the reason the router does not /// decode: the host has this code already and a second implementation is a /// second place for an escaping bug. Public because the renderers need the same /// answer the redirect does. A read that a renderer writes into an `href` and a /// redirect back to a filtered list are the same address, and two functions /// building it is how they stop being. /// /// A route with no parameters is returned as written, so nothing gains a /// trailing `?` it did not have. #[must_use] pub fn route_url(path: &str, params: &Params) -> String { if params.is_empty() { return path.to_owned(); } let query = form_urlencoded::Serializer::new(String::new()) .extend_pairs(params.iter()) .finish(); let joiner = if path.contains('?') { '&' } else { '?' }; format!("{path}{joiner}{query}") } /// Turn the adapter's own refusal into a response. /// /// No body, because there is nothing to say that the status does not already /// say and no description was ever reached. `Allow` on a 405 is what a client /// needs to correct itself rather than retry the same thing. #[must_use] pub fn refuse(refusal: Refusal) -> http::Response> { let mut builder = http::Response::builder().status(refusal.status()); if refusal == Refusal::Method { builder = builder.header(http::header::ALLOW, ALLOWED_METHODS); } builder .body(Vec::new()) .expect("a response with no body and a static header is always valid") } /// A rendered body, with the renderer's own content type. fn body( render: &R, status: u16, rendered: String, retarget: Option, ) -> http::Response> { let mut builder = http::Response::builder() .status(status) .header(http::header::CONTENT_TYPE, render.content_type()); if let Some(target) = retarget { builder = builder.header(htmx::RETARGET, target); } builder.body(rendered.into_bytes()).unwrap_or_else(|_| { // Only reachable if a renderer answered with a content type that is not // a legal header value, which is our bug and not the request's. http::Response::builder() .status(500) .body(Vec::new()) .expect("a response with no body and no headers is always valid") }) } /// The two verbs the description layer has, and nothing else. fn translate(method: &http::Method) -> Option { match *method { http::Method::GET => Some(Method::Get), http::Method::POST => Some(Method::Post), http::Method::DELETE => Some(Method::Delete), http::Method::PUT => Some(Method::Put), _ => None, } } /// Whether the body is a form these adapters read. /// /// `multipart/form-data` is deliberately not read. A file is a byte stream, a /// description has no word for one, and buffering an upload into [`Params`] /// would be the wrong shape at any size. Such a request still routes, with no /// parameters from its body. fn is_form(headers: &http::HeaderMap) -> bool { headers .get(http::header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) .is_some_and(|value| { value.split(';').next().is_some_and(|kind| { kind.trim() .eq_ignore_ascii_case("application/x-www-form-urlencoded") }) }) } /// Percent-decoded name and value pairs, repeats kept. /// /// Repeats are the point: a checkbox group submits one name several times, and /// a decoder that keeps the last is a bug that only shows on the screen with /// the multi-select on it. fn decode_pairs(encoded: &str) -> Params { form_urlencoded::parse(encoded.as_bytes()) .map(|(name, value)| (name.into_owned(), value.into_owned())) .collect() } #[cfg(test)] mod tests;