//! 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::{ Accepted, Action, Address, Destination, Method, Node, Outcome, Params, Request, Response, RouteError, Sought, safe_file_name, }; 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, /// Whether htmx made this request rather than the browser navigating. /// /// Read off [`htmx::REQUEST`], which htmx sets on every call it makes. The /// one fact about the envelope that changes what an answer may be: an /// ordinary navigation can be handed any bytes at all, and an XHR cannot /// (see [`respond`]'s file arm). /// /// Never given to a handler. A route describes what it answers, not who /// asked for it; this is the adapter's own and stops here. pub htmx: bool, } /// 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, /// [`Incoming::htmx`], kept for the same reason the other two are: the /// answer is placed after the router has consumed the request. pub htmx: bool, } 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), htmx: incoming.htmx, } } } 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 /// /// 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()), htmx: headers.contains_key(htmx::REQUEST), }) } /// 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, notice.undo.as_ref()) }); 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}"))) } // The work is running somewhere else and the region says so. // Aimed at that region, the same as a fragment, because it is // the same swap: what differs is that the contents are a wait. // // `Readiness` is the axis everywhere else, and on this host it // cannot be the whole answer. `aria-busy` sits on the region // element, and an innerHTML swap replaces what is inside that // element rather than the element itself — so the saying-so has // to be a node. `Node::pending` is that node, and // makeover-webview draws it `role="status" aria-live="polite"`, // which is the announcement a swapped-in wait owes a reader who // cannot see it. // // Deliberately not an `HX-Reswap` to `outerHTML` to get the // attribute back. `htmx::RESWAP` says why: how a response is put // in place travels with the element. // // Nothing here re-asks. The region already carries its own // `hx-trigger` from the render that put it up — that is // `Slot::live` — and a header telling it to poll would be this // crate deciding a cadence the description declined to name. Outcome::Started { region, message } => body( render, 200, render.fragment(&Node::pending(message)), 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. // Aimed at the list the field owns, which the renderer names // from the field's own name. A renderer with no such container // answers `None` and the fragment lands where it was aimed, // which is the same bargain an overlay strikes. Outcome::Suggestions { field, options } => { let target = render.suggestions_target(&field).map(|id| format!("#{id}")); body(render, 200, render.suggestions(&field, &options), target) } Outcome::Over(screen) => { let target = render.overlay_target().map(|id| format!("#{id}")); body(render, 200, render.overlay(&screen), target) } // Over what is already there, at a point in it. The container // belongs to the anchored thing rather than to the app, which // is the whole difference from the arm above: the retarget is // derived from the anchor and the one overlay container is left // alone. // // The swap style is not touched. `htmx::RESWAP` says why: how a // response is put in place travels with the element, so the // container this aims at is one whose ordinary innerHTML swap is // already right, rather than a header overriding a decision the // renderer made. Outcome::Anchored { screen, anchor } => { let target = render.anchored_target(&anchor).map(|id| format!("#{id}")); body(render, 200, render.anchored(&screen), target) } // A file, at whatever destination the browser is configured to // put downloads. `67881a88`: the route answers with the file // and the host puts it somewhere, and on this host the header // is the whole of the saying-so. // // Nothing is rendered, so `Serves` is not consulted: bytes are // not markup and there is no renderer question to ask. That is // why this member cost the `Serves` trait nothing when it // arrived, unlike every other outcome. // // Unless htmx asked, and the bytes are not text. `3bdf1a75`: // htmx leaves `responseType` unset, so the browser decodes the // body as UTF-8 before `DOWNLOAD_JS` can see it and every byte // sequence that is not valid UTF-8 has already become U+FFFD. // A `.zip` answered this way downloads and is corrupt, and it // looks exactly like one that worked. Outcome::File { name, kind, bytes: _, } if asked.htmx && !is_text(&kind) => { refused(render, &binary_download(&name, &kind)) } Outcome::File { name, kind, bytes } => attach(&name, &kind, bytes), // A place, on a host with no picker to open. `ec92f9cb` says a // host that cannot perform this refuses explicitly, and this is // the explicit refusal: 501, and a notice down the same path // every other failure takes. // // Deliberately not degraded into an upload field. A browser can // offer a file input and cannot hand back a folder the server // may write into afterwards, so anything drawn here would be a // control that looks like it worked. The `Locate` sites are // audiofiles' and audiofiles is not on this host; a described // screen that has to work in a browser asks for a file with // `FieldKind::File`, which is the described upload and is a // different sentence. // // Which dialog was wanted is named rather than the whole class // refused, because "cannot choose a place" tells a reader // nothing about what they pressed. The match is exhaustive so // that a shape added to `Sought` stops compiling here rather // than arriving at a wildcard that calls it something it is // not. Outcome::Locate(asking) => { let wanted = match &asking.sought { Sought::Folder => "choose a folder", Sought::File { .. } => "choose a file", Sought::Files { .. } => "choose files", // `7fda7ae3`. The one shape this host has something // adjacent to, and adjacent is not the same. A browser // saves bytes that exist now, through the download it // is already given `Outcome::File` for; this asks for // somewhere to write into later, and there is no way to // hand a page one. A description that has to work here // answers with the file instead. Sought::Save { .. } => "choose where to save", }; refused( render, &format!("this host cannot {wanted}: {}", asking.prompt), ) } }; 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(), // A `RouteError` carries no way back, so neither does this. act: None, }; let mut response = body( render, error.class.http_status(), render.fragment(&node), None, ); // A 405 without `Allow` is a refusal with no way to learn what // would have worked, which RFC 9110 makes a MUST for exactly that // reason. Empty for every other class, so nothing is added to the // answers that were already right. if let Some(allow) = error.allow_header() && let Ok(value) = http::HeaderValue::from_str(&allow) { response.headers_mut().insert(http::header::ALLOW, value); } response } } } /// 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. /// /// A [`Destination::Local`] is nowhere to go, and a `Goto` carrying one is a /// description bug: locality marks an interaction that asks nothing, and /// "navigate, asking nothing" names no place. It answers 200 with no header, so /// the page stays where it is. Refusing to answer at all was the other reading /// and is [`Screen::replace`]'s question rather than this one — a bad /// description is worth being able to see, and is not worth a 500. /// /// [`Destination::Back`] is the same answer for a different reason, and the /// reason is worth writing down because "go back after this write" is a /// coherent thing to want. A redirect is a header, and no header says "back": /// the browser's history is walked by script, and a response header cannot run /// one. The retained-screen hosts drop it here too — their `Goto` arms read /// `Destination::route` and get `None` — so the three agree, which is the /// property that matters more than any one of them doing something clever. /// **What a description says instead is an action on a control** /// ([`Action::back`](quasi_router::Action::back)), which every host answers. /// /// [`Screen::replace`]: quasi_router::Screen::replace fn redirect(action: &Action) -> http::Response> { let Some((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) => Some((htmx::LOCATION, route_url(path, &action.carried))), // Both ways out of the app are one redirect here. A response header // sends the browser somewhere and has no say in what window it lands // in, so the distinction the two variants draw is a link's and not a // redirect's: a page that has already navigated has nothing to keep // aside. Destination::External(address) | Destination::Leaving(address) => { Some((htmx::REDIRECT, address.clone())) } Destination::Local | Destination::Back => None, }) else { return http::Response::builder() .status(200) .body(Vec::new()) .expect("a response with no body and no headers is always valid"); }; 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. /// Hand the bytes over as a download. /// /// 200 and the file, with the name in `Content-Disposition`. Not a 303 to a /// second route that serves it: the payload is already in hand, and inventing a /// second address would mean holding it somewhere between the two requests. /// /// # The name is rewritten twice, on purpose /// /// [`safe_file_name`] first, because the name reaches here from a description /// and is regularly built from something a user typed. Then RFC 6266's two /// forms: a quoted ASCII `filename` every agent has understood for twenty /// years, and a `filename*` carrying the real characters for the ones that /// read it. A name that is already ASCII gets both and they agree, which is /// cheaper to read than a branch. /// /// # What htmx does with this, and what it does not /// /// A control that reaches this route through `hx-post` gets the bytes into an /// XHR and the browser downloads nothing, because a download is a navigation. /// `quasi-webview` closes that with [`DOWNLOAD_JS`], which cancels the swap and /// hands the body to the browser as a blob. A host serving plain links — /// anything not driving this from htmx — needs none of it and works off this /// header alone. /// /// [`DOWNLOAD_JS`]: https://makenot.work/git/max/quasi fn attach(name: &str, kind: &Accepted, bytes: Vec) -> http::Response> { let name = safe_file_name(name); http::Response::builder() .status(200) .header(http::header::CONTENT_TYPE, media_type(kind)) .header(http::header::CONTENT_DISPOSITION, disposition(&name)) .body(bytes) .unwrap_or_else(|_| { // Unreachable: both header values are built from a name this // function just sanitised and from a media type below, and neither // can carry a control character. http::Response::builder() .status(500) .body(Vec::new()) .expect("a response with no body and no headers is always valid") }) } /// Whether an answer's bytes can survive being read back off an XHR as text. /// /// The question is not "is this a sensible download" but "has the browser /// already destroyed it": htmx reads a response as a UTF-8 string, so anything /// that is not valid UTF-8 arrives at [`DOWNLOAD_JS`] with U+FFFD where its /// bytes were. Text survives that round trip exactly. /// /// Only [`Accepted::Type`] can answer, and it is the same reason /// [`media_type`] gives: a [`Family`](Accepted::Family) spells `image/*`, which /// is a filter, and a [`Suffix`](Accepted::Suffix) is a name. Guessing text-ness /// from `.csv` would be this crate keeping the suffix table the description /// layer deliberately does not have, and a wrong guess here is a corrupt file /// rather than a wrong header. Both answer "cannot say", which this reads as /// "not safe" -- a loud refusal is recoverable and a silently mangled download /// is not. /// /// The types that count are `text/*` and the structured formats that are text /// wearing an `application/` prefix for historical reasons. `+json` and `+xml` /// are RFC 6839 structured suffixes and are text by construction, so they are /// matched by shape rather than listed. /// /// [`DOWNLOAD_JS`]: https://makenot.work/git/max/quasi fn is_text(kind: &Accepted) -> bool { let Accepted::Type(media_type) = kind else { return false; }; let media_type = media_type .split(';') .next() .unwrap_or_default() .trim() .to_ascii_lowercase(); media_type.starts_with("text/") || media_type.ends_with("+json") || media_type.ends_with("+xml") || matches!( media_type.as_str(), "application/json" | "application/xml" | "application/javascript" ) } /// What a refused answer says, as a fragment down the path every failure takes. /// /// Decision 9 at the boundary: a host that cannot perform something says so as /// a notice rather than by answering something that looks like it worked. 501, /// because the description is fine and this host is what cannot do it. fn refused(render: &R, text: &str) -> http::Response> { let node = Node::Notice { kind: quasi_router::layout::Notice::Banner, tone: quasi_router::layout::Tone::Danger, text: text.to_owned(), // A refusal, with no route that would undo it. act: None, }; body(render, 501, render.fragment(&node), None) } /// What the refusal above says about a file htmx cannot be handed. /// /// Names the two ways out, because "cannot" with no next step is a dead end and /// both of these are one line at the call site: say a text media type if the /// bytes are text, or reach the route with a plain link, which never becomes an /// XHR and is always correct. fn binary_download(name: &str, kind: &Accepted) -> String { // `Accepted` is `#[non_exhaustive]`, so a member added upstream lands with // the two that already say "cannot say". That is the right default here: // this refuses what it cannot show to be text. let said = match kind { Accepted::Type(media_type) => media_type.clone(), _ => "no media type".to_owned(), }; format!( "this host cannot download `{name}` over htmx: {said} is not known to be \ text, and htmx reads a response as text. Answer with a text media type, \ or offer the route as a plain link." ) } /// The media type to send a described file kind as. /// /// Only [`Accepted::Type`] is one. A [`Family`](Accepted::Family) spells /// `image/*`, which is a filter and not a type, and a /// [`Suffix`](Accepted::Suffix) is a name rather than a type at all — guessing /// one from `.json` would be this crate keeping a suffix table that the /// description layer deliberately does not have. Both fall back to the type /// that means "bytes", which is what a download is. fn media_type(kind: &Accepted) -> &str { match kind { Accepted::Type(media_type) if !media_type.is_empty() => media_type, _ => "application/octet-stream", } } /// `attachment`, with the name said both ways RFC 6266 allows. /// /// The unquoted `filename*` is percent-encoded over everything outside the /// attr-char set, which is the RFC's own rule and is why this does not reach /// for a general URL encoder: the sets are not the same. fn disposition(name: &str) -> String { const HEX: [char; 16] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', ]; let mut ascii = String::with_capacity(name.len()); let mut encoded = String::with_capacity(name.len()); for ch in name.chars() { if ch.is_ascii() && !ch.is_ascii_control() && ch != '"' && ch != '\\' { ascii.push(ch); } else { ascii.push('_'); } if ch.is_ascii_alphanumeric() || "!#$&+-.^_`|~".contains(ch) { encoded.push(ch); } else { let mut buffer = [0u8; 4]; for byte in ch.encode_utf8(&mut buffer).as_bytes() { encoded.push('%'); encoded.push(HEX[usize::from(byte >> 4)]); encoded.push(HEX[usize::from(byte & 0x0f)]); } } } format!("attachment; filename=\"{ascii}\"; filename*=UTF-8''{encoded}") } 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;