mirror of
https://github.com/rm-dr/servable.git
synced 2025-11-28 05:19:33 -08:00
Version 0.0.1
This commit is contained in:
38
crates/servable/Cargo.toml
Normal file
38
crates/servable/Cargo.toml
Normal file
@@ -0,0 +1,38 @@
|
||||
[package]
|
||||
name = "servable"
|
||||
description = "A tiny web stack featuring htmx, Axum, Rust, and Maud."
|
||||
keywords = ["htmx", "web", "webui", "maud", "framework"]
|
||||
categories = ["web-programming", "web-programming::http-server"]
|
||||
rust-version = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
version = { workspace = true }
|
||||
license = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
readme = { workspace = true }
|
||||
authors = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
axum = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
maud = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_urlencoded = { workspace = true }
|
||||
tower = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
|
||||
tokio = { workspace = true, optional = true }
|
||||
image = { workspace = true, optional = true }
|
||||
strum = { workspace = true, optional = true }
|
||||
thiserror = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tower-http = { workspace = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
image = ["dep:image", "dep:strum", "dep:thiserror", "dep:tokio"]
|
||||
"htmx-2.0.8" = []
|
||||
1
crates/servable/htmx/htmx-2.0.8.min.js
vendored
Normal file
1
crates/servable/htmx/htmx-2.0.8.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
11
crates/servable/htmx/json-enc-1.9.12.js
Normal file
11
crates/servable/htmx/json-enc-1.9.12.js
Normal file
@@ -0,0 +1,11 @@
|
||||
htmx.defineExtension('json-enc', {
|
||||
onEvent: function (name, evt) {
|
||||
if (name === "htmx:configRequest") {
|
||||
evt.detail.headers['Content-Type'] = "application/json";
|
||||
}
|
||||
},
|
||||
encodeParameters: function (xhr, parameters, elt) {
|
||||
xhr.overrideMimeType('text/json');
|
||||
return (JSON.stringify(parameters));
|
||||
}
|
||||
});
|
||||
56
crates/servable/src/lib.rs
Normal file
56
crates/servable/src/lib.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
#![doc = include_str!("../README.md")]
|
||||
|
||||
pub mod mime;
|
||||
|
||||
mod types;
|
||||
|
||||
use rand::{Rng, distr::Alphanumeric};
|
||||
pub use types::*;
|
||||
|
||||
mod router;
|
||||
pub use router::*;
|
||||
|
||||
mod servable;
|
||||
pub use servable::*;
|
||||
|
||||
#[cfg(test)] // Used in doctests
|
||||
use tower_http as _;
|
||||
|
||||
//
|
||||
//
|
||||
//
|
||||
|
||||
#[cfg(feature = "image")]
|
||||
pub mod transform;
|
||||
|
||||
/// A unique string that can be used for cache-busting.
|
||||
///
|
||||
/// Note that this string changes every time this code is started,
|
||||
/// even if the data inside the program did not change.
|
||||
pub static CACHE_BUST_STR: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
|
||||
rand::rng()
|
||||
.sample_iter(&Alphanumeric)
|
||||
.take(10)
|
||||
.map(char::from)
|
||||
.collect()
|
||||
});
|
||||
|
||||
//
|
||||
//
|
||||
//
|
||||
|
||||
/// HTMX 2.0.8, minified
|
||||
#[cfg(feature = "htmx-2.0.8")]
|
||||
pub const HTMX_2_0_8: servable::StaticAsset = servable::StaticAsset {
|
||||
bytes: include_str!("../htmx/htmx-2.0.8.min.js").as_bytes(),
|
||||
mime: mime::MimeType::Javascript,
|
||||
};
|
||||
|
||||
/// HTMX json extension, 1.19.2.
|
||||
/// Compatible with:
|
||||
/// - [HTMX_2_0_8]
|
||||
#[cfg(feature = "htmx-2.0.8")]
|
||||
pub const EXT_JSON_1_19_12: servable::StaticAsset = servable::StaticAsset {
|
||||
bytes: include_str!("../htmx/json-enc-1.9.12.js").as_bytes(),
|
||||
mime: mime::MimeType::Javascript,
|
||||
};
|
||||
811
crates/servable/src/mime.rs
Normal file
811
crates/servable/src/mime.rs
Normal file
@@ -0,0 +1,811 @@
|
||||
//! Strongly-typed MIME types via [MimeType].
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::{fmt::Display, str::FromStr};
|
||||
use tracing::debug;
|
||||
|
||||
/// A media type, conveniently parsed
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
pub enum MimeType {
|
||||
/// A mimetype we didn't recognize
|
||||
Other(String),
|
||||
|
||||
/// An unstructured binary blob (application/octet-stream)
|
||||
Blob,
|
||||
|
||||
// MARK: Audio
|
||||
/// AAC audio file (audio/aac)
|
||||
Aac,
|
||||
/// FLAC audio file (audio/flac)
|
||||
Flac,
|
||||
/// MIDI audio file (audio/midi)
|
||||
Midi,
|
||||
/// MP3 audio file (audio/mpeg)
|
||||
Mp3,
|
||||
/// OGG audio file (audio/ogg)
|
||||
Oga,
|
||||
/// Opus audio file in Ogg container (audio/ogg)
|
||||
Opus,
|
||||
/// Waveform Audio Format (audio/wav)
|
||||
Wav,
|
||||
/// WEBM audio file (audio/webm)
|
||||
Weba,
|
||||
|
||||
// MARK: Video
|
||||
/// AVI: Audio Video Interleave (video/x-msvideo)
|
||||
Avi,
|
||||
/// MP4 video file (video/mp4)
|
||||
Mp4,
|
||||
/// MPEG video file (video/mpeg)
|
||||
Mpeg,
|
||||
/// OGG video file (video/ogg)
|
||||
Ogv,
|
||||
/// MPEG transport stream (video/mp2t)
|
||||
Ts,
|
||||
/// WEBM video file (video/webm)
|
||||
WebmVideo,
|
||||
/// 3GPP audio/video container (video/3gpp)
|
||||
ThreeGp,
|
||||
/// 3GPP2 audio/video container (video/3gpp2)
|
||||
ThreeG2,
|
||||
|
||||
// MARK: Images
|
||||
/// Animated Portable Network Graphics (image/apng)
|
||||
Apng,
|
||||
/// AVIF image (image/avif)
|
||||
Avif,
|
||||
/// Windows OS/2 Bitmap Graphics (image/bmp)
|
||||
Bmp,
|
||||
/// Graphics Interchange Format (image/gif)
|
||||
Gif,
|
||||
/// Icon format (image/vnd.microsoft.icon)
|
||||
Ico,
|
||||
/// JPEG image (image/jpeg)
|
||||
Jpg,
|
||||
/// Portable Network Graphics (image/png)
|
||||
Png,
|
||||
/// Quite ok Image Format
|
||||
Qoi,
|
||||
/// Scalable Vector Graphics (image/svg+xml)
|
||||
Svg,
|
||||
/// Tagged Image File Format (image/tiff)
|
||||
Tiff,
|
||||
/// WEBP image (image/webp)
|
||||
Webp,
|
||||
|
||||
// MARK: Text
|
||||
/// Plain text (text/plain)
|
||||
Text,
|
||||
/// Cascading Style Sheets (text/css)
|
||||
Css,
|
||||
/// Comma-separated values (text/csv)
|
||||
Csv,
|
||||
/// HyperText Markup Language (text/html)
|
||||
Html,
|
||||
/// JavaScript (text/javascript)
|
||||
Javascript,
|
||||
/// JSON format (application/json)
|
||||
Json,
|
||||
/// JSON-LD format (application/ld+json)
|
||||
JsonLd,
|
||||
/// XML (application/xml)
|
||||
Xml,
|
||||
|
||||
// MARK: Documents
|
||||
/// Adobe Portable Document Format (application/pdf)
|
||||
Pdf,
|
||||
/// Rich Text Format (application/rtf)
|
||||
Rtf,
|
||||
|
||||
// MARK: Archives
|
||||
/// Archive document, multiple files embedded (application/x-freearc)
|
||||
Arc,
|
||||
/// BZip archive (application/x-bzip)
|
||||
Bz,
|
||||
/// BZip2 archive (application/x-bzip2)
|
||||
Bz2,
|
||||
/// GZip Compressed Archive (application/gzip)
|
||||
Gz,
|
||||
/// Java Archive (application/java-archive)
|
||||
Jar,
|
||||
/// OGG (application/ogg)
|
||||
Ogg,
|
||||
/// RAR archive (application/vnd.rar)
|
||||
Rar,
|
||||
/// 7-zip archive (application/x-7z-compressed)
|
||||
SevenZ,
|
||||
/// Tape Archive (application/x-tar)
|
||||
Tar,
|
||||
/// ZIP archive (application/zip)
|
||||
Zip,
|
||||
|
||||
// MARK: Fonts
|
||||
/// MS Embedded OpenType fonts (application/vnd.ms-fontobject)
|
||||
Eot,
|
||||
/// OpenType font (font/otf)
|
||||
Otf,
|
||||
/// TrueType Font (font/ttf)
|
||||
Ttf,
|
||||
/// Web Open Font Format (font/woff)
|
||||
Woff,
|
||||
/// Web Open Font Format 2 (font/woff2)
|
||||
Woff2,
|
||||
|
||||
// MARK: Applications
|
||||
/// AbiWord document (application/x-abiword)
|
||||
Abiword,
|
||||
/// Amazon Kindle eBook format (application/vnd.amazon.ebook)
|
||||
Azw,
|
||||
/// CD audio (application/x-cdf)
|
||||
Cda,
|
||||
/// C-Shell script (application/x-csh)
|
||||
Csh,
|
||||
/// Microsoft Word (application/msword)
|
||||
Doc,
|
||||
/// Microsoft Word OpenXML (application/vnd.openxmlformats-officedocument.wordprocessingml.document)
|
||||
Docx,
|
||||
/// Electronic publication (application/epub+zip)
|
||||
Epub,
|
||||
/// iCalendar format (text/calendar)
|
||||
Ics,
|
||||
/// Apple Installer Package (application/vnd.apple.installer+xml)
|
||||
Mpkg,
|
||||
/// OpenDocument presentation (application/vnd.oasis.opendocument.presentation)
|
||||
Odp,
|
||||
/// OpenDocument spreadsheet (application/vnd.oasis.opendocument.spreadsheet)
|
||||
Ods,
|
||||
/// OpenDocument text document (application/vnd.oasis.opendocument.text)
|
||||
Odt,
|
||||
/// Hypertext Preprocessor (application/x-httpd-php)
|
||||
Php,
|
||||
/// Microsoft PowerPoint (application/vnd.ms-powerpoint)
|
||||
Ppt,
|
||||
/// Microsoft PowerPoint OpenXML (application/vnd.openxmlformats-officedocument.presentationml.presentation)
|
||||
Pptx,
|
||||
/// Bourne shell script (application/x-sh)
|
||||
Sh,
|
||||
/// Microsoft Visio (application/vnd.visio)
|
||||
Vsd,
|
||||
/// XHTML (application/xhtml+xml)
|
||||
Xhtml,
|
||||
/// Microsoft Excel (application/vnd.ms-excel)
|
||||
Xls,
|
||||
/// Microsoft Excel OpenXML (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)
|
||||
Xlsx,
|
||||
/// XUL (application/vnd.mozilla.xul+xml)
|
||||
Xul,
|
||||
}
|
||||
|
||||
// MARK: ser/de
|
||||
|
||||
/*
|
||||
impl utoipa::ToSchema for MimeType {
|
||||
fn name() -> std::borrow::Cow<'static, str> {
|
||||
std::borrow::Cow::Borrowed("MimeType")
|
||||
}
|
||||
}
|
||||
impl utoipa::PartialSchema for MimeType {
|
||||
fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
|
||||
utoipa::openapi::Schema::Object(
|
||||
utoipa::openapi::schema::ObjectBuilder::new()
|
||||
.schema_type(utoipa::openapi::schema::SchemaType::Type(Type::String))
|
||||
.description(Some(
|
||||
"A media type string (e.g., 'application/json', 'text/plain')",
|
||||
))
|
||||
.examples(Some("application/json"))
|
||||
.build(),
|
||||
)
|
||||
.into()
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
impl Serialize for MimeType {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(&self.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for MimeType {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Ok(MimeType::from_str(&s).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: misc
|
||||
//
|
||||
|
||||
impl Default for MimeType {
|
||||
fn default() -> Self {
|
||||
Self::Blob
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for MimeType {
|
||||
fn from(value: String) -> Self {
|
||||
Self::from_str(&value).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for MimeType {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::from_str(value).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&MimeType> for String {
|
||||
fn from(value: &MimeType) -> Self {
|
||||
value.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: fromstr
|
||||
//
|
||||
|
||||
impl MimeType {
|
||||
/// Parse a mimetype from a string that may contain
|
||||
/// whitespace or ";" parameters.
|
||||
///
|
||||
/// Parameters are discarded, write your own parser if you need them.
|
||||
pub fn from_header(s: &str) -> Result<Self, <Self as FromStr>::Err> {
|
||||
let s = s.trim();
|
||||
let semi = s.find(';').unwrap_or(s.len());
|
||||
let space = s.find(' ').unwrap_or(s.len());
|
||||
let limit = semi.min(space);
|
||||
let s = &s[0..limit];
|
||||
let s = s.trim();
|
||||
|
||||
return Self::from_str(s);
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for MimeType {
|
||||
type Err = std::convert::Infallible;
|
||||
|
||||
// Must match `display` below, but may provide other alternatives.
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Ok(match s {
|
||||
"application/octet-stream" => Self::Blob,
|
||||
|
||||
// Audio
|
||||
"audio/aac" => Self::Aac,
|
||||
"audio/flac" => Self::Flac,
|
||||
"audio/midi" | "audio/x-midi" => Self::Midi,
|
||||
"audio/mpeg" => Self::Mp3,
|
||||
"audio/ogg" => Self::Oga,
|
||||
"audio/wav" => Self::Wav,
|
||||
"audio/webm" => Self::Weba,
|
||||
|
||||
// Video
|
||||
"video/x-msvideo" => Self::Avi,
|
||||
"video/mp4" => Self::Mp4,
|
||||
"video/mpeg" => Self::Mpeg,
|
||||
"video/ogg" => Self::Ogv,
|
||||
"video/mp2t" => Self::Ts,
|
||||
"video/webm" => Self::WebmVideo,
|
||||
"video/3gpp" => Self::ThreeGp,
|
||||
"video/3gpp2" => Self::ThreeG2,
|
||||
|
||||
// Images
|
||||
"image/apng" => Self::Apng,
|
||||
"image/avif" => Self::Avif,
|
||||
"image/bmp" => Self::Bmp,
|
||||
"image/gif" => Self::Gif,
|
||||
"image/vnd.microsoft.icon" => Self::Ico,
|
||||
"image/jpeg" | "image/jpg" => Self::Jpg,
|
||||
"image/png" => Self::Png,
|
||||
"image/svg+xml" => Self::Svg,
|
||||
"image/tiff" => Self::Tiff,
|
||||
"image/webp" => Self::Webp,
|
||||
"image/qoi" => Self::Qoi,
|
||||
|
||||
// Text
|
||||
"text/plain" => Self::Text,
|
||||
"text/css" => Self::Css,
|
||||
"text/csv" => Self::Csv,
|
||||
"text/html" => Self::Html,
|
||||
"text/javascript" => Self::Javascript,
|
||||
"application/json" => Self::Json,
|
||||
"application/ld+json" => Self::JsonLd,
|
||||
"application/xml" | "text/xml" => Self::Xml,
|
||||
|
||||
// Documents
|
||||
"application/pdf" => Self::Pdf,
|
||||
"application/rtf" => Self::Rtf,
|
||||
|
||||
// Archives
|
||||
"application/x-freearc" => Self::Arc,
|
||||
"application/x-bzip" => Self::Bz,
|
||||
"application/x-bzip2" => Self::Bz2,
|
||||
"application/gzip" | "application/x-gzip" => Self::Gz,
|
||||
"application/java-archive" => Self::Jar,
|
||||
"application/ogg" => Self::Ogg,
|
||||
"application/vnd.rar" => Self::Rar,
|
||||
"application/x-7z-compressed" => Self::SevenZ,
|
||||
"application/x-tar" => Self::Tar,
|
||||
"application/zip" | "application/x-zip-compressed" => Self::Zip,
|
||||
|
||||
// Fonts
|
||||
"application/vnd.ms-fontobject" => Self::Eot,
|
||||
"font/otf" => Self::Otf,
|
||||
"font/ttf" => Self::Ttf,
|
||||
"font/woff" => Self::Woff,
|
||||
"font/woff2" => Self::Woff2,
|
||||
|
||||
// Applications
|
||||
"application/x-abiword" => Self::Abiword,
|
||||
"application/vnd.amazon.ebook" => Self::Azw,
|
||||
"application/x-cdf" => Self::Cda,
|
||||
"application/x-csh" => Self::Csh,
|
||||
"application/msword" => Self::Doc,
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" => Self::Docx,
|
||||
"application/epub+zip" => Self::Epub,
|
||||
"text/calendar" => Self::Ics,
|
||||
"application/vnd.apple.installer+xml" => Self::Mpkg,
|
||||
"application/vnd.oasis.opendocument.presentation" => Self::Odp,
|
||||
"application/vnd.oasis.opendocument.spreadsheet" => Self::Ods,
|
||||
"application/vnd.oasis.opendocument.text" => Self::Odt,
|
||||
"application/x-httpd-php" => Self::Php,
|
||||
"application/vnd.ms-powerpoint" => Self::Ppt,
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation" => {
|
||||
Self::Pptx
|
||||
}
|
||||
"application/x-sh" => Self::Sh,
|
||||
"application/vnd.visio" => Self::Vsd,
|
||||
"application/xhtml+xml" => Self::Xhtml,
|
||||
"application/vnd.ms-excel" => Self::Xls,
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => Self::Xlsx,
|
||||
"application/vnd.mozilla.xul+xml" => Self::Xul,
|
||||
|
||||
_ => {
|
||||
debug!(message = "Encountered unknown mimetype", mime_string = s);
|
||||
Self::Other(s.into())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: display
|
||||
//
|
||||
|
||||
impl Display for MimeType {
|
||||
/// Get a string representation of this mimetype.
|
||||
///
|
||||
/// The following always holds:
|
||||
/// ```rust
|
||||
/// # use servable::mime::MimeType;
|
||||
/// # let x = MimeType::Blob;
|
||||
/// assert_eq!(MimeType::from(x.to_string()), x);
|
||||
/// ```
|
||||
///
|
||||
/// The following might not hold:
|
||||
/// ```rust
|
||||
/// # use servable::mime::MimeType;
|
||||
/// # let y = "application/custom";
|
||||
/// // MimeType::from(y).to_string() may not equal y
|
||||
/// ```
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Blob => write!(f, "application/octet-stream"),
|
||||
|
||||
// Audio
|
||||
Self::Aac => write!(f, "audio/aac"),
|
||||
Self::Flac => write!(f, "audio/flac"),
|
||||
Self::Midi => write!(f, "audio/midi"),
|
||||
Self::Mp3 => write!(f, "audio/mpeg"),
|
||||
Self::Oga => write!(f, "audio/ogg"),
|
||||
Self::Opus => write!(f, "audio/ogg"),
|
||||
Self::Wav => write!(f, "audio/wav"),
|
||||
Self::Weba => write!(f, "audio/webm"),
|
||||
|
||||
// Video
|
||||
Self::Avi => write!(f, "video/x-msvideo"),
|
||||
Self::Mp4 => write!(f, "video/mp4"),
|
||||
Self::Mpeg => write!(f, "video/mpeg"),
|
||||
Self::Ogv => write!(f, "video/ogg"),
|
||||
Self::Ts => write!(f, "video/mp2t"),
|
||||
Self::WebmVideo => write!(f, "video/webm"),
|
||||
Self::ThreeGp => write!(f, "video/3gpp"),
|
||||
Self::ThreeG2 => write!(f, "video/3gpp2"),
|
||||
|
||||
// Images
|
||||
Self::Apng => write!(f, "image/apng"),
|
||||
Self::Avif => write!(f, "image/avif"),
|
||||
Self::Bmp => write!(f, "image/bmp"),
|
||||
Self::Gif => write!(f, "image/gif"),
|
||||
Self::Ico => write!(f, "image/vnd.microsoft.icon"),
|
||||
Self::Jpg => write!(f, "image/jpeg"),
|
||||
Self::Png => write!(f, "image/png"),
|
||||
Self::Svg => write!(f, "image/svg+xml"),
|
||||
Self::Tiff => write!(f, "image/tiff"),
|
||||
Self::Webp => write!(f, "image/webp"),
|
||||
Self::Qoi => write!(f, "image/qoi"),
|
||||
|
||||
// Text
|
||||
Self::Text => write!(f, "text/plain"),
|
||||
Self::Css => write!(f, "text/css"),
|
||||
Self::Csv => write!(f, "text/csv"),
|
||||
Self::Html => write!(f, "text/html"),
|
||||
Self::Javascript => write!(f, "text/javascript"),
|
||||
Self::Json => write!(f, "application/json"),
|
||||
Self::JsonLd => write!(f, "application/ld+json"),
|
||||
Self::Xml => write!(f, "application/xml"),
|
||||
|
||||
// Documents
|
||||
Self::Pdf => write!(f, "application/pdf"),
|
||||
Self::Rtf => write!(f, "application/rtf"),
|
||||
|
||||
// Archives
|
||||
Self::Arc => write!(f, "application/x-freearc"),
|
||||
Self::Bz => write!(f, "application/x-bzip"),
|
||||
Self::Bz2 => write!(f, "application/x-bzip2"),
|
||||
Self::Gz => write!(f, "application/gzip"),
|
||||
Self::Jar => write!(f, "application/java-archive"),
|
||||
Self::Ogg => write!(f, "application/ogg"),
|
||||
Self::Rar => write!(f, "application/vnd.rar"),
|
||||
Self::SevenZ => write!(f, "application/x-7z-compressed"),
|
||||
Self::Tar => write!(f, "application/x-tar"),
|
||||
Self::Zip => write!(f, "application/zip"),
|
||||
|
||||
// Fonts
|
||||
Self::Eot => write!(f, "application/vnd.ms-fontobject"),
|
||||
Self::Otf => write!(f, "font/otf"),
|
||||
Self::Ttf => write!(f, "font/ttf"),
|
||||
Self::Woff => write!(f, "font/woff"),
|
||||
Self::Woff2 => write!(f, "font/woff2"),
|
||||
|
||||
// Applications
|
||||
Self::Abiword => write!(f, "application/x-abiword"),
|
||||
Self::Azw => write!(f, "application/vnd.amazon.ebook"),
|
||||
Self::Cda => write!(f, "application/x-cdf"),
|
||||
Self::Csh => write!(f, "application/x-csh"),
|
||||
Self::Doc => write!(f, "application/msword"),
|
||||
Self::Docx => write!(
|
||||
f,
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
),
|
||||
Self::Epub => write!(f, "application/epub+zip"),
|
||||
Self::Ics => write!(f, "text/calendar"),
|
||||
Self::Mpkg => write!(f, "application/vnd.apple.installer+xml"),
|
||||
Self::Odp => write!(f, "application/vnd.oasis.opendocument.presentation"),
|
||||
Self::Ods => write!(f, "application/vnd.oasis.opendocument.spreadsheet"),
|
||||
Self::Odt => write!(f, "application/vnd.oasis.opendocument.text"),
|
||||
Self::Php => write!(f, "application/x-httpd-php"),
|
||||
Self::Ppt => write!(f, "application/vnd.ms-powerpoint"),
|
||||
Self::Pptx => write!(
|
||||
f,
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
||||
),
|
||||
Self::Sh => write!(f, "application/x-sh"),
|
||||
Self::Vsd => write!(f, "application/vnd.visio"),
|
||||
Self::Xhtml => write!(f, "application/xhtml+xml"),
|
||||
Self::Xls => write!(f, "application/vnd.ms-excel"),
|
||||
Self::Xlsx => write!(
|
||||
f,
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
),
|
||||
Self::Xul => write!(f, "application/vnd.mozilla.xul+xml"),
|
||||
|
||||
Self::Other(x) => write!(f, "{x}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MimeType {
|
||||
//
|
||||
// MARK: from extension
|
||||
//
|
||||
|
||||
/// Try to guess a file's mime type from its extension.
|
||||
/// `ext` should NOT start with a dot.
|
||||
pub fn from_extension(ext: &str) -> Option<Self> {
|
||||
Some(match ext {
|
||||
// Audio
|
||||
"aac" => Self::Aac,
|
||||
"flac" => Self::Flac,
|
||||
"mid" | "midi" => Self::Midi,
|
||||
"mp3" => Self::Mp3,
|
||||
"oga" => Self::Oga,
|
||||
"opus" => Self::Opus,
|
||||
"wav" => Self::Wav,
|
||||
"weba" => Self::Weba,
|
||||
|
||||
// Video
|
||||
"avi" => Self::Avi,
|
||||
"mp4" => Self::Mp4,
|
||||
"mpeg" => Self::Mpeg,
|
||||
"ogv" => Self::Ogv,
|
||||
"ts" => Self::Ts,
|
||||
"webm" => Self::WebmVideo,
|
||||
"3gp" => Self::ThreeGp,
|
||||
"3g2" => Self::ThreeG2,
|
||||
|
||||
// Images
|
||||
"apng" => Self::Apng,
|
||||
"avif" => Self::Avif,
|
||||
"bmp" => Self::Bmp,
|
||||
"gif" => Self::Gif,
|
||||
"ico" => Self::Ico,
|
||||
"jpg" | "jpeg" => Self::Jpg,
|
||||
"png" => Self::Png,
|
||||
"svg" => Self::Svg,
|
||||
"tif" | "tiff" => Self::Tiff,
|
||||
"webp" => Self::Webp,
|
||||
"qoi" => Self::Qoi,
|
||||
|
||||
// Text
|
||||
"txt" => Self::Text,
|
||||
"css" => Self::Css,
|
||||
"csv" => Self::Csv,
|
||||
"htm" | "html" => Self::Html,
|
||||
"js" | "mjs" => Self::Javascript,
|
||||
"json" => Self::Json,
|
||||
"jsonld" => Self::JsonLd,
|
||||
"xml" => Self::Xml,
|
||||
|
||||
// Documents
|
||||
"pdf" => Self::Pdf,
|
||||
"rtf" => Self::Rtf,
|
||||
|
||||
// Archives
|
||||
"arc" => Self::Arc,
|
||||
"bz" => Self::Bz,
|
||||
"bz2" => Self::Bz2,
|
||||
"gz" => Self::Gz,
|
||||
"jar" => Self::Jar,
|
||||
"ogx" => Self::Ogg,
|
||||
"rar" => Self::Rar,
|
||||
"7z" => Self::SevenZ,
|
||||
"tar" => Self::Tar,
|
||||
"zip" => Self::Zip,
|
||||
|
||||
// Fonts
|
||||
"eot" => Self::Eot,
|
||||
"otf" => Self::Otf,
|
||||
"ttf" => Self::Ttf,
|
||||
"woff" => Self::Woff,
|
||||
"woff2" => Self::Woff2,
|
||||
|
||||
// Applications
|
||||
"abw" => Self::Abiword,
|
||||
"azw" => Self::Azw,
|
||||
"cda" => Self::Cda,
|
||||
"csh" => Self::Csh,
|
||||
"doc" => Self::Doc,
|
||||
"docx" => Self::Docx,
|
||||
"epub" => Self::Epub,
|
||||
"ics" => Self::Ics,
|
||||
"mpkg" => Self::Mpkg,
|
||||
"odp" => Self::Odp,
|
||||
"ods" => Self::Ods,
|
||||
"odt" => Self::Odt,
|
||||
"php" => Self::Php,
|
||||
"ppt" => Self::Ppt,
|
||||
"pptx" => Self::Pptx,
|
||||
"sh" => Self::Sh,
|
||||
"vsd" => Self::Vsd,
|
||||
"xhtml" => Self::Xhtml,
|
||||
"xls" => Self::Xls,
|
||||
"xlsx" => Self::Xlsx,
|
||||
"xul" => Self::Xul,
|
||||
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: to extension
|
||||
//
|
||||
|
||||
/// Get the extension we use for files with this type.
|
||||
/// Never includes a dot.
|
||||
pub fn extension(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::Blob => None,
|
||||
Self::Other(_) => None,
|
||||
|
||||
// Audio
|
||||
Self::Aac => Some("aac"),
|
||||
Self::Flac => Some("flac"),
|
||||
Self::Midi => Some("midi"),
|
||||
Self::Mp3 => Some("mp3"),
|
||||
Self::Oga => Some("oga"),
|
||||
Self::Opus => Some("opus"),
|
||||
Self::Wav => Some("wav"),
|
||||
Self::Weba => Some("weba"),
|
||||
|
||||
// Video
|
||||
Self::Avi => Some("avi"),
|
||||
Self::Mp4 => Some("mp4"),
|
||||
Self::Mpeg => Some("mpeg"),
|
||||
Self::Ogv => Some("ogv"),
|
||||
Self::Ts => Some("ts"),
|
||||
Self::WebmVideo => Some("webm"),
|
||||
Self::ThreeGp => Some("3gp"),
|
||||
Self::ThreeG2 => Some("3g2"),
|
||||
|
||||
// Images
|
||||
Self::Apng => Some("apng"),
|
||||
Self::Avif => Some("avif"),
|
||||
Self::Bmp => Some("bmp"),
|
||||
Self::Gif => Some("gif"),
|
||||
Self::Ico => Some("ico"),
|
||||
Self::Jpg => Some("jpg"),
|
||||
Self::Png => Some("png"),
|
||||
Self::Svg => Some("svg"),
|
||||
Self::Tiff => Some("tiff"),
|
||||
Self::Webp => Some("webp"),
|
||||
Self::Qoi => Some("qoi"),
|
||||
|
||||
// Text
|
||||
Self::Text => Some("txt"),
|
||||
Self::Css => Some("css"),
|
||||
Self::Csv => Some("csv"),
|
||||
Self::Html => Some("html"),
|
||||
Self::Javascript => Some("js"),
|
||||
Self::Json => Some("json"),
|
||||
Self::JsonLd => Some("jsonld"),
|
||||
Self::Xml => Some("xml"),
|
||||
|
||||
// Documents
|
||||
Self::Pdf => Some("pdf"),
|
||||
Self::Rtf => Some("rtf"),
|
||||
|
||||
// Archives
|
||||
Self::Arc => Some("arc"),
|
||||
Self::Bz => Some("bz"),
|
||||
Self::Bz2 => Some("bz2"),
|
||||
Self::Gz => Some("gz"),
|
||||
Self::Jar => Some("jar"),
|
||||
Self::Ogg => Some("ogx"),
|
||||
Self::Rar => Some("rar"),
|
||||
Self::SevenZ => Some("7z"),
|
||||
Self::Tar => Some("tar"),
|
||||
Self::Zip => Some("zip"),
|
||||
|
||||
// Fonts
|
||||
Self::Eot => Some("eot"),
|
||||
Self::Otf => Some("otf"),
|
||||
Self::Ttf => Some("ttf"),
|
||||
Self::Woff => Some("woff"),
|
||||
Self::Woff2 => Some("woff2"),
|
||||
|
||||
// Applications
|
||||
Self::Abiword => Some("abw"),
|
||||
Self::Azw => Some("azw"),
|
||||
Self::Cda => Some("cda"),
|
||||
Self::Csh => Some("csh"),
|
||||
Self::Doc => Some("doc"),
|
||||
Self::Docx => Some("docx"),
|
||||
Self::Epub => Some("epub"),
|
||||
Self::Ics => Some("ics"),
|
||||
Self::Mpkg => Some("mpkg"),
|
||||
Self::Odp => Some("odp"),
|
||||
Self::Ods => Some("ods"),
|
||||
Self::Odt => Some("odt"),
|
||||
Self::Php => Some("php"),
|
||||
Self::Ppt => Some("ppt"),
|
||||
Self::Pptx => Some("pptx"),
|
||||
Self::Sh => Some("sh"),
|
||||
Self::Vsd => Some("vsd"),
|
||||
Self::Xhtml => Some("xhtml"),
|
||||
Self::Xls => Some("xls"),
|
||||
Self::Xlsx => Some("xlsx"),
|
||||
Self::Xul => Some("xul"),
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: is_text
|
||||
//
|
||||
|
||||
/// Returns true if this MIME type is always plain text.
|
||||
pub fn is_text(&self) -> bool {
|
||||
match self {
|
||||
// Text types
|
||||
Self::Text => true,
|
||||
Self::Css => true,
|
||||
Self::Csv => true,
|
||||
Self::Html => true,
|
||||
Self::Javascript => true,
|
||||
Self::Json => true,
|
||||
Self::JsonLd => true,
|
||||
Self::Xml => true,
|
||||
Self::Svg => true,
|
||||
Self::Ics => true,
|
||||
Self::Xhtml => true,
|
||||
|
||||
// Script types
|
||||
Self::Csh => true,
|
||||
Self::Php => true,
|
||||
Self::Sh => true,
|
||||
|
||||
// All other types are not plain text
|
||||
Self::Other(_) => false,
|
||||
Self::Blob => false,
|
||||
|
||||
// Audio
|
||||
Self::Aac => false,
|
||||
Self::Flac => false,
|
||||
Self::Midi => false,
|
||||
Self::Mp3 => false,
|
||||
Self::Oga => false,
|
||||
Self::Opus => false,
|
||||
Self::Wav => false,
|
||||
Self::Weba => false,
|
||||
|
||||
// Video
|
||||
Self::Avi => false,
|
||||
Self::Mp4 => false,
|
||||
Self::Mpeg => false,
|
||||
Self::Ogv => false,
|
||||
Self::Ts => false,
|
||||
Self::WebmVideo => false,
|
||||
Self::ThreeGp => false,
|
||||
Self::ThreeG2 => false,
|
||||
|
||||
// Images
|
||||
Self::Apng => false,
|
||||
Self::Avif => false,
|
||||
Self::Bmp => false,
|
||||
Self::Gif => false,
|
||||
Self::Ico => false,
|
||||
Self::Jpg => false,
|
||||
Self::Png => false,
|
||||
Self::Qoi => false,
|
||||
Self::Tiff => false,
|
||||
Self::Webp => false,
|
||||
|
||||
// Documents
|
||||
Self::Pdf => false,
|
||||
Self::Rtf => false,
|
||||
|
||||
// Archives
|
||||
Self::Arc => false,
|
||||
Self::Bz => false,
|
||||
Self::Bz2 => false,
|
||||
Self::Gz => false,
|
||||
Self::Jar => false,
|
||||
Self::Ogg => false,
|
||||
Self::Rar => false,
|
||||
Self::SevenZ => false,
|
||||
Self::Tar => false,
|
||||
Self::Zip => false,
|
||||
|
||||
// Fonts
|
||||
Self::Eot => false,
|
||||
Self::Otf => false,
|
||||
Self::Ttf => false,
|
||||
Self::Woff => false,
|
||||
Self::Woff2 => false,
|
||||
|
||||
// Applications
|
||||
Self::Abiword => false,
|
||||
Self::Azw => false,
|
||||
Self::Cda => false,
|
||||
Self::Doc => false,
|
||||
Self::Docx => false,
|
||||
Self::Epub => false,
|
||||
Self::Mpkg => false,
|
||||
Self::Odp => false,
|
||||
Self::Ods => false,
|
||||
Self::Odt => false,
|
||||
Self::Ppt => false,
|
||||
Self::Pptx => false,
|
||||
Self::Vsd => false,
|
||||
Self::Xls => false,
|
||||
Self::Xlsx => false,
|
||||
Self::Xul => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
296
crates/servable/src/router.rs
Normal file
296
crates/servable/src/router.rs
Normal file
@@ -0,0 +1,296 @@
|
||||
use axum::{
|
||||
Router,
|
||||
body::Body,
|
||||
http::{HeaderMap, HeaderValue, Method, Request, StatusCode, header},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use chrono::TimeDelta;
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
convert::Infallible,
|
||||
net::SocketAddr,
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
time::Instant,
|
||||
};
|
||||
use tower::Service;
|
||||
use tracing::trace;
|
||||
|
||||
use crate::{
|
||||
ClientInfo, RenderContext, Rendered, RenderedBody,
|
||||
mime::MimeType,
|
||||
servable::{Servable, ServableWithRoute},
|
||||
};
|
||||
|
||||
struct Default404 {}
|
||||
|
||||
impl Servable for Default404 {
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
_ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<()>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
return Rendered {
|
||||
code: StatusCode::NOT_FOUND,
|
||||
body: (),
|
||||
ttl: Some(TimeDelta::days(1)),
|
||||
immutable: true,
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(MimeType::Html),
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<RenderedBody>> + 'a + Send + Sync>> {
|
||||
Box::pin(async { self.head(ctx).await.with_body(RenderedBody::Empty) })
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of related [Servable]s under one route.
|
||||
///
|
||||
/// Use as follows:
|
||||
/// ```rust
|
||||
/// use servable::{ServableRouter, StaticAsset, mime::MimeType};
|
||||
/// use axum::Router;
|
||||
/// use tower_http::compression::{CompressionLayer, predicate::DefaultPredicate};
|
||||
///
|
||||
/// // Add compression, for example.
|
||||
/// // Also consider CORS and timeout.
|
||||
/// let compression: CompressionLayer = CompressionLayer::new()
|
||||
/// .br(true)
|
||||
/// .deflate(true)
|
||||
/// .gzip(true)
|
||||
/// .zstd(true)
|
||||
/// .compress_when(DefaultPredicate::new());
|
||||
///
|
||||
/// let route = ServableRouter::new()
|
||||
/// .add_page(
|
||||
/// "/page",
|
||||
/// StaticAsset {
|
||||
/// bytes: "I am a page".as_bytes(),
|
||||
/// mime: MimeType::Text,
|
||||
/// },
|
||||
/// );
|
||||
///
|
||||
/// let router: Router<()> = route
|
||||
/// .into_router()
|
||||
/// .layer(compression.clone());
|
||||
/// ```
|
||||
#[derive(Clone)]
|
||||
pub struct ServableRouter {
|
||||
pages: Arc<HashMap<String, Arc<dyn Servable>>>,
|
||||
notfound: Arc<dyn Servable>,
|
||||
}
|
||||
|
||||
impl ServableRouter {
|
||||
/// Create a new, empty [ServableRouter]
|
||||
#[inline(always)]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
pages: Arc::new(HashMap::new()),
|
||||
notfound: Arc::new(Default404 {}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set this server's "not found" page
|
||||
#[inline(always)]
|
||||
pub fn with_404<S: Servable + 'static>(mut self, page: S) -> Self {
|
||||
self.notfound = Arc::new(page);
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a [Servable] to this server at the given route.
|
||||
/// - panics if route does not start with a `/`, ends with a `/`, or contains `//`.
|
||||
/// - urls are normalized, routes that violate this condition will never be served.
|
||||
/// - `/` is an exception, it is valid.
|
||||
/// - panics if called after this service is started
|
||||
/// - overwrites existing pages
|
||||
#[inline(always)]
|
||||
pub fn add_page<S: Servable + 'static>(mut self, route: impl Into<String>, page: S) -> Self {
|
||||
let route = route.into();
|
||||
|
||||
if !route.starts_with("/") {
|
||||
panic!("route must start with /")
|
||||
};
|
||||
|
||||
if route.ends_with("/") && route != "/" {
|
||||
panic!("route must not end with /")
|
||||
};
|
||||
|
||||
if route.contains("//") {
|
||||
panic!("route must not contain //")
|
||||
};
|
||||
|
||||
#[expect(clippy::expect_used)]
|
||||
Arc::get_mut(&mut self.pages)
|
||||
.expect("add_pages called after service was started")
|
||||
.insert(route, Arc::new(page));
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a [ServableWithRoute] to this server.
|
||||
/// Behaves exactly like [Self::add_page].
|
||||
#[inline(always)]
|
||||
pub fn add_page_with_route<S: Servable + 'static>(
|
||||
self,
|
||||
servable_with_route: &'static ServableWithRoute<S>,
|
||||
) -> Self {
|
||||
self.add_page(servable_with_route.route(), servable_with_route)
|
||||
}
|
||||
|
||||
/// Convenience method.
|
||||
/// Turns this service into a router.
|
||||
///
|
||||
/// Equivalent to:
|
||||
/// ```ignore
|
||||
/// Router::new().fallback_service(self)
|
||||
/// ```
|
||||
#[inline(always)]
|
||||
pub fn into_router<T: Clone + Send + Sync + 'static>(self) -> Router<T> {
|
||||
Router::new().fallback_service(self)
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: impl Service
|
||||
//
|
||||
|
||||
impl Service<Request<Body>> for ServableRouter {
|
||||
type Response = Response;
|
||||
type Error = Infallible;
|
||||
type Future =
|
||||
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
|
||||
|
||||
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request<Body>) -> Self::Future {
|
||||
if req.method() != Method::GET && req.method() != Method::HEAD {
|
||||
let mut headers = HeaderMap::with_capacity(1);
|
||||
headers.insert(header::ACCEPT, HeaderValue::from_static("GET,HEAD"));
|
||||
return Box::pin(async {
|
||||
Ok((StatusCode::METHOD_NOT_ALLOWED, headers).into_response())
|
||||
});
|
||||
}
|
||||
|
||||
let pages = self.pages.clone();
|
||||
let notfound = self.notfound.clone();
|
||||
Box::pin(async move {
|
||||
let addr = req.extensions().get::<SocketAddr>().copied();
|
||||
let route = req.uri().path().to_owned();
|
||||
let headers = req.headers().clone();
|
||||
let query: BTreeMap<String, String> =
|
||||
serde_urlencoded::from_str(req.uri().query().unwrap_or("")).unwrap_or_default();
|
||||
|
||||
let start = Instant::now();
|
||||
let client_info = ClientInfo::from_headers(&headers);
|
||||
let ua = headers
|
||||
.get("user-agent")
|
||||
.and_then(|x| x.to_str().ok())
|
||||
.unwrap_or("");
|
||||
|
||||
trace!(
|
||||
message = "Serving route",
|
||||
route,
|
||||
addr = ?addr,
|
||||
user_agent = ua,
|
||||
device_type = ?client_info.device_type
|
||||
);
|
||||
|
||||
// Normalize url with redirect
|
||||
if (route.ends_with('/') && route != "/") || route.contains("//") {
|
||||
let mut new_route = route.clone();
|
||||
while new_route.contains("//") {
|
||||
new_route = new_route.replace("//", "/");
|
||||
}
|
||||
let new_route = new_route.trim_matches('/');
|
||||
|
||||
trace!(
|
||||
message = "Redirecting",
|
||||
route,
|
||||
new_route,
|
||||
addr = ?addr,
|
||||
user_agent = ua,
|
||||
device_type = ?client_info.device_type
|
||||
);
|
||||
|
||||
let mut headers = HeaderMap::with_capacity(1);
|
||||
match HeaderValue::from_str(&format!("/{new_route}")) {
|
||||
Ok(x) => headers.append(header::LOCATION, x),
|
||||
Err(_) => return Ok(StatusCode::BAD_REQUEST.into_response()),
|
||||
};
|
||||
return Ok((StatusCode::PERMANENT_REDIRECT, headers).into_response());
|
||||
}
|
||||
|
||||
let ctx = RenderContext {
|
||||
client_info,
|
||||
route,
|
||||
query,
|
||||
};
|
||||
|
||||
let page = pages.get(&ctx.route).unwrap_or(¬found);
|
||||
let mut rend = match req.method() == Method::HEAD {
|
||||
true => page.head(&ctx).await.with_body(RenderedBody::Empty),
|
||||
false => page.render(&ctx).await,
|
||||
};
|
||||
|
||||
// Tweak headers
|
||||
{
|
||||
if !rend.headers.contains_key(header::CACHE_CONTROL) {
|
||||
let max_age = rend.ttl.map(|x| x.num_seconds()).unwrap_or(1).max(1);
|
||||
|
||||
let mut value = String::new();
|
||||
if rend.immutable {
|
||||
value.push_str("immutable, ");
|
||||
}
|
||||
|
||||
value.push_str("public, ");
|
||||
value.push_str(&format!("max-age={}, ", max_age));
|
||||
|
||||
#[expect(clippy::unwrap_used)]
|
||||
rend.headers.insert(
|
||||
header::CACHE_CONTROL,
|
||||
HeaderValue::from_str(value.trim().trim_end_matches(',')).unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
if !rend.headers.contains_key("Accept-CH") {
|
||||
rend.headers
|
||||
.insert("Accept-CH", HeaderValue::from_static("Sec-CH-UA-Mobile"));
|
||||
}
|
||||
|
||||
if !rend.headers.contains_key(header::CONTENT_TYPE)
|
||||
&& let Some(mime) = &rend.mime
|
||||
{
|
||||
#[expect(clippy::unwrap_used)]
|
||||
rend.headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_str(&mime.to_string()).unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
trace!(
|
||||
message = "Served route",
|
||||
route = ctx.route,
|
||||
addr = ?addr,
|
||||
user_agent = ua,
|
||||
device_type = ?client_info.device_type,
|
||||
time_ns = start.elapsed().as_nanos()
|
||||
);
|
||||
|
||||
Ok(match rend.body {
|
||||
RenderedBody::Static(d) => (rend.code, rend.headers, d).into_response(),
|
||||
RenderedBody::Bytes(d) => (rend.code, rend.headers, d).into_response(),
|
||||
RenderedBody::String(s) => (rend.code, rend.headers, s).into_response(),
|
||||
RenderedBody::Empty => (rend.code, rend.headers).into_response(),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
213
crates/servable/src/servable/asset.rs
Normal file
213
crates/servable/src/servable/asset.rs
Normal file
@@ -0,0 +1,213 @@
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use chrono::TimeDelta;
|
||||
use std::pin::Pin;
|
||||
|
||||
use crate::{RenderContext, Rendered, RenderedBody, mime::MimeType, servable::Servable};
|
||||
|
||||
const TTL: Option<TimeDelta> = Some(TimeDelta::days(1));
|
||||
|
||||
/// A static blob of bytes
|
||||
pub struct StaticAsset {
|
||||
/// The data to return
|
||||
pub bytes: &'static [u8],
|
||||
|
||||
/// The type of `bytes`
|
||||
pub mime: MimeType,
|
||||
}
|
||||
|
||||
#[cfg(feature = "image")]
|
||||
impl Servable for StaticAsset {
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<()>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
use crate::transform::TransformerChain;
|
||||
use std::str::FromStr;
|
||||
|
||||
let is_image = TransformerChain::mime_is_image(&self.mime);
|
||||
|
||||
let transform = match (is_image, ctx.query.get("t")) {
|
||||
(false, _) | (_, None) => None,
|
||||
|
||||
(true, Some(x)) => match TransformerChain::from_str(x) {
|
||||
Ok(x) => Some(x),
|
||||
Err(_err) => {
|
||||
return Rendered {
|
||||
code: StatusCode::BAD_REQUEST,
|
||||
body: (),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
match transform {
|
||||
Some(transform) => {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: (),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(
|
||||
transform
|
||||
.output_mime(&self.mime)
|
||||
.unwrap_or(self.mime.clone()),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
None => {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: (),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(self.mime.clone()),
|
||||
};
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<RenderedBody>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
use crate::transform::TransformerChain;
|
||||
use std::str::FromStr;
|
||||
use tracing::{error, trace};
|
||||
|
||||
// Automatically provide transformation if this is an image
|
||||
let is_image = TransformerChain::mime_is_image(&self.mime);
|
||||
|
||||
let transform = match (is_image, ctx.query.get("t")) {
|
||||
(false, _) | (_, None) => None,
|
||||
|
||||
(true, Some(x)) => match TransformerChain::from_str(x) {
|
||||
Ok(x) => Some(x),
|
||||
Err(err) => {
|
||||
return Rendered {
|
||||
code: StatusCode::BAD_REQUEST,
|
||||
body: RenderedBody::String(err),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
match transform {
|
||||
Some(transform) => {
|
||||
trace!(message = "Transforming image", ?transform);
|
||||
|
||||
let task = {
|
||||
let mime = Some(self.mime.clone());
|
||||
let bytes = self.bytes;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
transform.transform_bytes(bytes, mime.as_ref())
|
||||
})
|
||||
};
|
||||
|
||||
let res = match task.await {
|
||||
Ok(x) => x,
|
||||
Err(error) => {
|
||||
error!(message = "Error while transforming image", ?error);
|
||||
return Rendered {
|
||||
code: StatusCode::INTERNAL_SERVER_ERROR,
|
||||
body: RenderedBody::String(format!(
|
||||
"Error while transforming image: {error:?}"
|
||||
)),
|
||||
ttl: None,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
match res {
|
||||
Ok((mime, bytes)) => {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: RenderedBody::Bytes(bytes),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(mime),
|
||||
};
|
||||
}
|
||||
|
||||
Err(err) => {
|
||||
return Rendered {
|
||||
code: StatusCode::INTERNAL_SERVER_ERROR,
|
||||
body: RenderedBody::String(format!("{err}")),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None => {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: RenderedBody::Static(self.bytes),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(self.mime.clone()),
|
||||
};
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "image"))]
|
||||
impl Servable for StaticAsset {
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
_ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<()>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: (),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(self.mime.clone()),
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<RenderedBody>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
self.head(ctx)
|
||||
.await
|
||||
.with_body(RenderedBody::Static(self.bytes))
|
||||
})
|
||||
}
|
||||
}
|
||||
302
crates/servable/src/servable/html.rs
Normal file
302
crates/servable/src/servable/html.rs
Normal file
@@ -0,0 +1,302 @@
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use chrono::TimeDelta;
|
||||
use maud::{DOCTYPE, Markup, PreEscaped, html};
|
||||
use serde::Deserialize;
|
||||
use std::{hash::Hash, pin::Pin, sync::Arc};
|
||||
|
||||
use crate::{RenderContext, Rendered, RenderedBody, mime::MimeType, servable::Servable};
|
||||
|
||||
#[expect(missing_docs)]
|
||||
#[derive(Debug, Clone, Hash, PartialEq, Eq, Deserialize)]
|
||||
pub struct PageMetadata {
|
||||
/// The title of this page.
|
||||
/// Browsers display this on the page's tab.
|
||||
pub title: String,
|
||||
|
||||
/// The page author (metadata only)
|
||||
pub author: Option<String>,
|
||||
|
||||
/// The page description (metadata only)
|
||||
pub description: Option<String>,
|
||||
|
||||
/// The page image.
|
||||
/// Browsers display this on the page's tab.
|
||||
pub image: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for PageMetadata {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
title: "Untitled page".into(),
|
||||
author: None,
|
||||
description: None,
|
||||
image: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(missing_docs)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum ScriptSource<S> {
|
||||
/// Raw script data
|
||||
Inline(S),
|
||||
|
||||
/// Load script from a url
|
||||
Linked(S),
|
||||
}
|
||||
|
||||
/// A complete, dynamically-rendered blob of HTML.
|
||||
#[derive(Clone)]
|
||||
pub struct HtmlPage {
|
||||
/// This page's metadata
|
||||
pub meta: PageMetadata,
|
||||
|
||||
/// If true, the contents of this page never change
|
||||
pub immutable: bool,
|
||||
|
||||
/// How long this page's html may be cached.
|
||||
/// This controls the maximum age of a page shown to the user.
|
||||
///
|
||||
/// If `None`, this page is never cached.
|
||||
pub ttl: Option<TimeDelta>,
|
||||
|
||||
/// A function that generates this page's html.
|
||||
///
|
||||
/// This should return the contents of this page's <body> tag,
|
||||
/// or the contents of a wrapper element (defined in the page server struct).
|
||||
///
|
||||
/// This closure must never return `<html>` or `<head>`.
|
||||
pub render: Arc<
|
||||
dyn Send
|
||||
+ Sync
|
||||
+ 'static
|
||||
+ for<'a> Fn(
|
||||
&'a HtmlPage,
|
||||
&'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Markup> + Send + Sync + 'a>>,
|
||||
>,
|
||||
|
||||
/// The response code that should accompany this html
|
||||
pub response_code: StatusCode,
|
||||
|
||||
/// Scripts to include in this page. Order is preserved.
|
||||
pub scripts: Vec<ScriptSource<String>>,
|
||||
|
||||
/// Styles to include in this page. Order is preserved.
|
||||
pub styles: Vec<ScriptSource<String>>,
|
||||
|
||||
/// `name`, `content` for extra `<meta>` tags
|
||||
pub extra_meta: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Default for HtmlPage {
|
||||
fn default() -> Self {
|
||||
HtmlPage {
|
||||
// No cache by default
|
||||
ttl: None,
|
||||
immutable: false,
|
||||
|
||||
meta: Default::default(),
|
||||
render: Arc::new(|_, _| Box::pin(async { html!() })),
|
||||
response_code: StatusCode::OK,
|
||||
scripts: Vec::new(),
|
||||
styles: Vec::new(),
|
||||
extra_meta: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HtmlPage {
|
||||
/// Set `self.meta`
|
||||
#[inline(always)]
|
||||
pub fn with_meta(mut self, meta: PageMetadata) -> Self {
|
||||
self.meta = meta;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set `self.generate`
|
||||
#[inline(always)]
|
||||
pub fn with_render<
|
||||
R: Send
|
||||
+ Sync
|
||||
+ 'static
|
||||
+ for<'a> Fn(
|
||||
&'a HtmlPage,
|
||||
&'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Markup> + Send + Sync + 'a>>,
|
||||
>(
|
||||
mut self,
|
||||
render: R,
|
||||
) -> Self {
|
||||
self.render = Arc::new(render);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set `self.immutable`
|
||||
#[inline(always)]
|
||||
pub fn with_immutable(mut self, immutable: bool) -> Self {
|
||||
self.immutable = immutable;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set `self.html_ttl`
|
||||
#[inline(always)]
|
||||
pub fn with_ttl(mut self, ttl: Option<TimeDelta>) -> Self {
|
||||
self.ttl = ttl;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set `self.response_code`
|
||||
#[inline(always)]
|
||||
pub fn with_code(mut self, response_code: StatusCode) -> Self {
|
||||
self.response_code = response_code;
|
||||
self
|
||||
}
|
||||
|
||||
/// Add an inline script to this page (after existing scripts)
|
||||
#[inline(always)]
|
||||
pub fn with_script_inline(mut self, script: impl Into<String>) -> Self {
|
||||
self.scripts.push(ScriptSource::Inline(script.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a linked script to this page (after existing scripts)
|
||||
#[inline(always)]
|
||||
pub fn with_script_linked(mut self, url: impl Into<String>) -> Self {
|
||||
self.scripts.push(ScriptSource::Linked(url.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a script to this page (after existing scripts)
|
||||
#[inline(always)]
|
||||
pub fn with_script(mut self, script: ScriptSource<impl Into<String>>) -> Self {
|
||||
let script = match script {
|
||||
ScriptSource::Inline(x) => ScriptSource::Inline(x.into()),
|
||||
ScriptSource::Linked(x) => ScriptSource::Linked(x.into()),
|
||||
};
|
||||
|
||||
self.scripts.push(script);
|
||||
self
|
||||
}
|
||||
|
||||
/// Add an inline script to this page (after existing styles)
|
||||
#[inline(always)]
|
||||
pub fn with_style_inline(mut self, style: impl Into<String>) -> Self {
|
||||
self.styles.push(ScriptSource::Inline(style.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a linked style to this page (after existing styles)
|
||||
#[inline(always)]
|
||||
pub fn with_style_linked(mut self, url: impl Into<String>) -> Self {
|
||||
self.styles.push(ScriptSource::Linked(url.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a style to this page (after existing scripts)
|
||||
#[inline(always)]
|
||||
pub fn with_style(mut self, style: ScriptSource<impl Into<String>>) -> Self {
|
||||
let style = match style {
|
||||
ScriptSource::Inline(x) => ScriptSource::Inline(x.into()),
|
||||
ScriptSource::Linked(x) => ScriptSource::Linked(x.into()),
|
||||
};
|
||||
|
||||
self.scripts.push(style);
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a `<meta>` to this page (after existing `<meta>s`)
|
||||
#[inline(always)]
|
||||
pub fn with_extra_meta(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
self.extra_meta.push((key.into(), value.into()));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Servable for HtmlPage {
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
_ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<()>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
return Rendered {
|
||||
code: self.response_code,
|
||||
body: (),
|
||||
ttl: self.ttl,
|
||||
immutable: self.immutable,
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(MimeType::Html),
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<RenderedBody>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
let inner_html = (self.render)(self, ctx).await;
|
||||
|
||||
let html = html! {
|
||||
(DOCTYPE)
|
||||
html {
|
||||
head {
|
||||
meta charset="UTF-8";
|
||||
meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no";
|
||||
meta content="text/html; charset=UTF-8" http-equiv="content-type";
|
||||
meta property="og:type" content="website";
|
||||
@for (name, content) in &self.extra_meta {
|
||||
meta name=(name) content=(content);
|
||||
}
|
||||
|
||||
//
|
||||
// Metadata
|
||||
//
|
||||
title { (PreEscaped(self.meta.title.clone())) }
|
||||
meta property="og:site_name" content=(self.meta.title);
|
||||
meta name="title" content=(self.meta.title);
|
||||
meta property="og:title" content=(self.meta.title);
|
||||
meta property="twitter:title" content=(self.meta.title);
|
||||
|
||||
@if let Some(author) = &self.meta.author {
|
||||
meta name="author" content=(author);
|
||||
}
|
||||
|
||||
@if let Some(desc) = &self.meta.description {
|
||||
meta name="description" content=(desc);
|
||||
meta property="og:description" content=(desc);
|
||||
meta property="twitter:description" content=(desc);
|
||||
}
|
||||
|
||||
@if let Some(image) = &self.meta.image {
|
||||
meta content=(image) property="og:image";
|
||||
link rel="shortcut icon" href=(image) type="image/x-icon";
|
||||
}
|
||||
|
||||
//
|
||||
// Scripts & styles
|
||||
//
|
||||
|
||||
@for style in &self.styles {
|
||||
@match style {
|
||||
ScriptSource::Linked(x) => link rel="stylesheet" type="text/css" href=(x);,
|
||||
ScriptSource::Inline(x) => style { (PreEscaped(x)) }
|
||||
}
|
||||
}
|
||||
|
||||
@for script in &self.scripts {
|
||||
@match script {
|
||||
ScriptSource::Linked(x) => script src=(x) {},
|
||||
ScriptSource::Inline(x) => script { (PreEscaped(x)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
body { main { (inner_html) } }
|
||||
}
|
||||
};
|
||||
|
||||
return self.head(ctx).await.with_body(RenderedBody::String(html.0));
|
||||
})
|
||||
}
|
||||
}
|
||||
123
crates/servable/src/servable/mod.rs
Normal file
123
crates/servable/src/servable/mod.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
//! This module provides the [Servable] trait,
|
||||
//! as well as a few helper structs that implement it.
|
||||
|
||||
mod asset;
|
||||
|
||||
pub use asset::*;
|
||||
|
||||
mod html;
|
||||
pub use html::*;
|
||||
|
||||
mod redirect;
|
||||
pub use redirect::*;
|
||||
|
||||
/// Something that may be served over http. If implementing this trait,
|
||||
/// refer to sample implementations in [redirect::Redirect], [asset::StaticAsset] and [html::HtmlPage].
|
||||
pub trait Servable: Send + Sync {
|
||||
/// Return the same response as [Servable::render], but with an empty body.
|
||||
///
|
||||
/// This method is used to respond to `HEAD` requests.
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
ctx: &'a crate::RenderContext,
|
||||
) -> std::pin::Pin<Box<dyn Future<Output = crate::Rendered<()>> + 'a + Send + Sync>>;
|
||||
|
||||
/// Render this page. Must return the same metadata as [Servable::head].
|
||||
/// Consider using [crate::Rendered::with_body] and [Servable::head] to implement this fn.
|
||||
///
|
||||
/// This method is used to respond to `GET` requests.
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a crate::RenderContext,
|
||||
) -> std::pin::Pin<
|
||||
Box<dyn Future<Output = crate::Rendered<crate::RenderedBody>> + 'a + Send + Sync>,
|
||||
>;
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: ServableWithRoute
|
||||
//
|
||||
|
||||
/// A [Servable] and the route it is available at
|
||||
pub struct ServableWithRoute<S: Servable> {
|
||||
/// The resource
|
||||
servable: S,
|
||||
|
||||
/// The route this resource is available at
|
||||
route: std::sync::LazyLock<String>,
|
||||
}
|
||||
|
||||
impl<S: Servable> ServableWithRoute<S> {
|
||||
/// Create a new [ServableWithRoute]
|
||||
pub const fn new(route_init: fn() -> std::string::String, servable: S) -> Self {
|
||||
Self {
|
||||
servable,
|
||||
route: std::sync::LazyLock::new(route_init),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the route associated with this resource
|
||||
pub fn route(&self) -> &str {
|
||||
&self.route
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Servable> Servable for ServableWithRoute<S> {
|
||||
#[inline(always)]
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
ctx: &'a crate::RenderContext,
|
||||
) -> std::pin::Pin<Box<dyn Future<Output = crate::Rendered<()>> + 'a + Send + Sync>> {
|
||||
self.servable.head(ctx)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a crate::RenderContext,
|
||||
) -> std::pin::Pin<
|
||||
Box<dyn Future<Output = crate::Rendered<crate::RenderedBody>> + 'a + Send + Sync>,
|
||||
> {
|
||||
self.servable.render(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Servable> Servable for &'static S {
|
||||
#[inline(always)]
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
ctx: &'a crate::RenderContext,
|
||||
) -> std::pin::Pin<Box<dyn Future<Output = crate::Rendered<()>> + 'a + Send + Sync>> {
|
||||
(*self).head(ctx)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a crate::RenderContext,
|
||||
) -> std::pin::Pin<
|
||||
Box<dyn Future<Output = crate::Rendered<crate::RenderedBody>> + 'a + Send + Sync>,
|
||||
> {
|
||||
(*self).render(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Servable> Servable for std::sync::LazyLock<S> {
|
||||
#[inline(always)]
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
ctx: &'a crate::RenderContext,
|
||||
) -> std::pin::Pin<Box<dyn Future<Output = crate::Rendered<()>> + 'a + Send + Sync>> {
|
||||
(**self).head(ctx)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a crate::RenderContext,
|
||||
) -> std::pin::Pin<
|
||||
Box<dyn Future<Output = crate::Rendered<crate::RenderedBody>> + 'a + Send + Sync>,
|
||||
> {
|
||||
(**self).render(ctx)
|
||||
}
|
||||
}
|
||||
75
crates/servable/src/servable/redirect.rs
Normal file
75
crates/servable/src/servable/redirect.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use axum::http::{
|
||||
HeaderMap, HeaderValue, StatusCode,
|
||||
header::{self, InvalidHeaderValue},
|
||||
};
|
||||
|
||||
use crate::{RenderContext, Rendered, RenderedBody, servable::Servable};
|
||||
|
||||
#[expect(missing_docs)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RedirectCode {
|
||||
/// Reply with an http 307 (temporary redirect)
|
||||
Http307,
|
||||
|
||||
/// Reply with an http 308 (permanent redirect)
|
||||
Http308,
|
||||
}
|
||||
|
||||
/// A simple http edirect
|
||||
pub struct Redirect {
|
||||
to: HeaderValue,
|
||||
code: RedirectCode,
|
||||
}
|
||||
|
||||
impl Redirect {
|
||||
/// Create a new [Redirect] to the given route.
|
||||
/// Returns an http 308 (permanent redirect)
|
||||
pub fn new(to: impl Into<String>) -> Result<Self, InvalidHeaderValue> {
|
||||
Ok(Self {
|
||||
to: HeaderValue::from_str(&to.into())?,
|
||||
code: RedirectCode::Http308,
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a new [Redirect] to the given route.
|
||||
/// Returns an http 307 (temporary redirect)
|
||||
pub fn new_307(to: impl Into<String>) -> Result<Self, InvalidHeaderValue> {
|
||||
Ok(Self {
|
||||
to: HeaderValue::from_str(&to.into())?,
|
||||
code: RedirectCode::Http307,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Servable for Redirect {
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
_ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<()>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
let mut headers = HeaderMap::with_capacity(1);
|
||||
headers.append(header::LOCATION, self.to.clone());
|
||||
|
||||
return Rendered {
|
||||
code: match self.code {
|
||||
RedirectCode::Http307 => StatusCode::TEMPORARY_REDIRECT,
|
||||
RedirectCode::Http308 => StatusCode::PERMANENT_REDIRECT,
|
||||
},
|
||||
headers,
|
||||
body: (),
|
||||
ttl: None,
|
||||
immutable: true,
|
||||
mime: None,
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<RenderedBody>> + 'a + Send + Sync>> {
|
||||
Box::pin(async { self.head(ctx).await.with_body(RenderedBody::Empty) })
|
||||
}
|
||||
}
|
||||
176
crates/servable/src/transform/chain.rs
Normal file
176
crates/servable/src/transform/chain.rs
Normal file
@@ -0,0 +1,176 @@
|
||||
use image::{DynamicImage, ImageFormat};
|
||||
use serde::{Deserialize, Deserializer, de};
|
||||
use std::{fmt::Display, hash::Hash, io::Cursor, str::FromStr};
|
||||
use thiserror::Error;
|
||||
|
||||
use super::transformers::{ImageTransformer, TransformerEnum};
|
||||
use crate::mime::MimeType;
|
||||
|
||||
#[expect(missing_docs)]
|
||||
#[derive(Debug, Error)]
|
||||
pub enum TransformBytesError {
|
||||
/// We tried to transform non-image data
|
||||
#[error("{0} is not a valid image type")]
|
||||
NotAnImage(String),
|
||||
|
||||
/// We encountered an error while processing
|
||||
/// an image.
|
||||
#[error("error while processing image")]
|
||||
ImageError(#[from] image::ImageError),
|
||||
}
|
||||
|
||||
/// A sequence of transformations to apply to an image
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TransformerChain {
|
||||
steps: Vec<TransformerEnum>,
|
||||
}
|
||||
|
||||
impl TransformerChain {
|
||||
/// Returns `true` if `mime` is a type that can be transformed
|
||||
#[inline(always)]
|
||||
pub fn mime_is_image(mime: &MimeType) -> bool {
|
||||
ImageFormat::from_mime_type(mime.to_string()).is_some()
|
||||
}
|
||||
|
||||
/// Transform the given image using this chain
|
||||
#[inline(always)]
|
||||
pub fn transform_image(&self, mut image: DynamicImage) -> DynamicImage {
|
||||
for step in &self.steps {
|
||||
match step {
|
||||
TransformerEnum::Format { .. } => {}
|
||||
TransformerEnum::MaxDim(t) => t.transform(&mut image),
|
||||
TransformerEnum::Crop(t) => t.transform(&mut image),
|
||||
}
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
/// Return the mime this chain will produce when given an image
|
||||
/// with type `input_mime`. If this returns `None`, the input mime
|
||||
/// cannot be transformed.
|
||||
#[inline(always)]
|
||||
pub fn output_mime(&self, input_mime: &MimeType) -> Option<MimeType> {
|
||||
let mime = self
|
||||
.steps
|
||||
.last()
|
||||
.and_then(|x| match x {
|
||||
TransformerEnum::Format { format } => Some(MimeType::from(format.to_mime_type())),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(input_mime.clone());
|
||||
|
||||
let fmt = ImageFormat::from_mime_type(mime.to_string());
|
||||
fmt.map(|_| mime)
|
||||
}
|
||||
|
||||
/// Transform `image_bytes` using this chain.
|
||||
/// Returns `(output_type, output_bytes)`.
|
||||
///
|
||||
/// `image_format` tells us the type of `image_bytes`.
|
||||
/// If it is `None`, we try to infer it.
|
||||
pub fn transform_bytes(
|
||||
&self,
|
||||
image_bytes: &[u8],
|
||||
image_format: Option<&MimeType>,
|
||||
) -> Result<(MimeType, Vec<u8>), TransformBytesError> {
|
||||
let format: ImageFormat = match image_format {
|
||||
Some(x) => ImageFormat::from_mime_type(x.to_string())
|
||||
.ok_or(TransformBytesError::NotAnImage(x.to_string()))?,
|
||||
None => image::guess_format(image_bytes)?,
|
||||
};
|
||||
|
||||
let out_format = self
|
||||
.steps
|
||||
.last()
|
||||
.and_then(|x| match x {
|
||||
TransformerEnum::Format { format } => Some(format),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(&format);
|
||||
|
||||
let img = image::load_from_memory_with_format(image_bytes, format)?;
|
||||
let img = self.transform_image(img);
|
||||
|
||||
let out_mime = MimeType::from(out_format.to_mime_type());
|
||||
let mut out_bytes = Cursor::new(Vec::new());
|
||||
img.write_to(&mut out_bytes, *out_format)?;
|
||||
|
||||
return Ok((out_mime, out_bytes.into_inner()));
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for TransformerChain {
|
||||
type Err = String;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let steps_str = s.split(";");
|
||||
|
||||
let mut steps = Vec::new();
|
||||
for s in steps_str {
|
||||
let s = s.trim();
|
||||
if s.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let step = s.parse();
|
||||
match step {
|
||||
Ok(x) => steps.push(x),
|
||||
Err(msg) => return Err(format!("invalid step `{s}`: {msg}")),
|
||||
}
|
||||
}
|
||||
|
||||
let n_format = steps
|
||||
.iter()
|
||||
.filter(|x| matches!(x, TransformerEnum::Format { .. }))
|
||||
.count();
|
||||
if n_format > 2 {
|
||||
return Err("provide at most one format()".to_owned());
|
||||
}
|
||||
|
||||
if n_format == 1 && !matches!(steps.last(), Some(TransformerEnum::Format { .. })) {
|
||||
return Err("format() must be last".to_owned());
|
||||
}
|
||||
|
||||
return Ok(Self { steps });
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for TransformerChain {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Self::from_str(&s).map_err(de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for TransformerChain {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let mut first = true;
|
||||
for step in &self.steps {
|
||||
if first {
|
||||
write!(f, "{step}")?;
|
||||
first = false
|
||||
} else {
|
||||
write!(f, ";{step}")?;
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for TransformerChain {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.to_string() == other.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for TransformerChain {}
|
||||
|
||||
impl Hash for TransformerChain {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.to_string().hash(state);
|
||||
}
|
||||
}
|
||||
9
crates/servable/src/transform/mod.rs
Normal file
9
crates/servable/src/transform/mod.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
//! Provides simple server-side image optimization
|
||||
//! using query parameters.
|
||||
|
||||
mod pixeldim;
|
||||
|
||||
pub mod transformers;
|
||||
|
||||
mod chain;
|
||||
pub use chain::*;
|
||||
68
crates/servable/src/transform/pixeldim.rs
Normal file
68
crates/servable/src/transform/pixeldim.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
// TODO: parse -, + (100vw - 10px)
|
||||
// TODO: parse 100vw [min] 10
|
||||
// TODO: parse 100vw [max] 10
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum PixelDim {
|
||||
Pixels(u32),
|
||||
WidthPercent(f32),
|
||||
HeightPercent(f32),
|
||||
}
|
||||
|
||||
impl FromStr for PixelDim {
|
||||
type Err = String;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let numeric_end = s.find(|c: char| !c.is_ascii_digit() && c != '.');
|
||||
|
||||
let (quantity, unit) = numeric_end.map(|x| s.split_at(x)).unwrap_or((s, "px"));
|
||||
let quantity = quantity.trim();
|
||||
let unit = unit.trim();
|
||||
|
||||
match unit {
|
||||
"vw" => Ok(PixelDim::WidthPercent(
|
||||
quantity
|
||||
.parse()
|
||||
.map_err(|_err| format!("invalid quantity {quantity}"))?,
|
||||
)),
|
||||
|
||||
"vh" => Ok(PixelDim::HeightPercent(
|
||||
quantity
|
||||
.parse()
|
||||
.map_err(|_err| format!("invalid quantity {quantity}"))?,
|
||||
)),
|
||||
|
||||
"px" => Ok(PixelDim::Pixels(
|
||||
quantity
|
||||
.parse()
|
||||
.map_err(|_err| format!("invalid quantity {quantity}"))?,
|
||||
)),
|
||||
|
||||
_ => Err(format!("invalid unit {unit}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for PixelDim {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
FromStr::from_str(&s).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for PixelDim {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
PixelDim::Pixels(px) => write!(f, "{px}"),
|
||||
PixelDim::WidthPercent(p) => write!(f, "{p:.2}vw"),
|
||||
PixelDim::HeightPercent(p) => write!(f, "{p:.2}vh"),
|
||||
}
|
||||
}
|
||||
}
|
||||
188
crates/servable/src/transform/transformers/crop.rs
Normal file
188
crates/servable/src/transform/transformers/crop.rs
Normal file
@@ -0,0 +1,188 @@
|
||||
use image::DynamicImage;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{fmt::Display, str::FromStr};
|
||||
use strum::{Display, EnumString};
|
||||
|
||||
use super::super::{pixeldim::PixelDim, transformers::ImageTransformer};
|
||||
|
||||
#[expect(missing_docs)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString, Serialize, Deserialize, Display)]
|
||||
pub enum Direction {
|
||||
#[serde(rename = "n")]
|
||||
#[strum(to_string = "n")]
|
||||
#[strum(serialize = "north")]
|
||||
North,
|
||||
|
||||
#[serde(rename = "e")]
|
||||
#[strum(serialize = "e")]
|
||||
#[strum(serialize = "east")]
|
||||
East,
|
||||
|
||||
#[serde(rename = "s")]
|
||||
#[strum(serialize = "s")]
|
||||
#[strum(serialize = "south")]
|
||||
South,
|
||||
|
||||
#[serde(rename = "w")]
|
||||
#[strum(to_string = "w")]
|
||||
#[strum(serialize = "west")]
|
||||
West,
|
||||
|
||||
#[serde(rename = "c")]
|
||||
#[strum(serialize = "c")]
|
||||
#[strum(serialize = "center")]
|
||||
Center,
|
||||
|
||||
#[serde(rename = "ne")]
|
||||
#[strum(serialize = "ne")]
|
||||
#[strum(serialize = "northeast")]
|
||||
NorthEast,
|
||||
|
||||
#[serde(rename = "se")]
|
||||
#[strum(serialize = "se")]
|
||||
#[strum(serialize = "southeast")]
|
||||
SouthEast,
|
||||
|
||||
#[serde(rename = "nw")]
|
||||
#[strum(serialize = "nw")]
|
||||
#[strum(serialize = "northwest")]
|
||||
NorthWest,
|
||||
|
||||
#[serde(rename = "sw")]
|
||||
#[strum(serialize = "sw")]
|
||||
#[strum(serialize = "southwest")]
|
||||
SouthWest,
|
||||
}
|
||||
|
||||
/// Crop an image to (at most) the given size.
|
||||
/// See [Self::new] for details.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CropTransformer {
|
||||
w: PixelDim,
|
||||
h: PixelDim,
|
||||
float: Direction,
|
||||
}
|
||||
|
||||
impl CropTransformer {
|
||||
/// Create a new [CropTransformer] with the given parameters.
|
||||
///
|
||||
/// A [CropTransformer] creates an image of size `w x h`, but...
|
||||
/// - does not reduce width if `w` is greater than image width
|
||||
/// - does not reduce height if `h` is greater than image height
|
||||
/// - does nothing if `w` or `h` is less than or equal to zero.
|
||||
pub fn new(w: PixelDim, h: PixelDim, float: Direction) -> Self {
|
||||
Self { w, h, float }
|
||||
}
|
||||
|
||||
fn crop_dim(&self, img_width: u32, img_height: u32) -> (u32, u32) {
|
||||
let crop_width = match self.w {
|
||||
PixelDim::Pixels(w) => w,
|
||||
PixelDim::WidthPercent(pct) => ((img_width as f32) * pct / 100.0) as u32,
|
||||
PixelDim::HeightPercent(pct) => ((img_height as f32) * pct / 100.0) as u32,
|
||||
};
|
||||
|
||||
let crop_height = match self.h {
|
||||
PixelDim::Pixels(h) => h,
|
||||
PixelDim::WidthPercent(pct) => ((img_width as f32) * pct / 100.0) as u32,
|
||||
PixelDim::HeightPercent(pct) => ((img_height as f32) * pct / 100.0) as u32,
|
||||
};
|
||||
|
||||
(crop_width, crop_height)
|
||||
}
|
||||
|
||||
#[expect(clippy::integer_division)]
|
||||
fn crop_pos(
|
||||
&self,
|
||||
img_width: u32,
|
||||
img_height: u32,
|
||||
crop_width: u32,
|
||||
crop_height: u32,
|
||||
) -> (u32, u32) {
|
||||
match self.float {
|
||||
Direction::North => {
|
||||
let x = (img_width - crop_width) / 2;
|
||||
let y = 0;
|
||||
(x, y)
|
||||
}
|
||||
Direction::East => {
|
||||
let x = img_width - crop_width;
|
||||
let y = (img_height - crop_height) / 2;
|
||||
(x, y)
|
||||
}
|
||||
Direction::South => {
|
||||
let x = (img_width - crop_width) / 2;
|
||||
let y = img_height - crop_height;
|
||||
(x, y)
|
||||
}
|
||||
Direction::West => {
|
||||
let x = 0;
|
||||
let y = (img_height - crop_height) / 2;
|
||||
(x, y)
|
||||
}
|
||||
Direction::Center => {
|
||||
let x = (img_width - crop_width) / 2;
|
||||
let y = (img_height - crop_height) / 2;
|
||||
(x, y)
|
||||
}
|
||||
Direction::NorthEast => {
|
||||
let x = img_width - crop_width;
|
||||
let y = 0;
|
||||
(x, y)
|
||||
}
|
||||
Direction::SouthEast => {
|
||||
let x = img_width - crop_width;
|
||||
let y = img_height - crop_height;
|
||||
(x, y)
|
||||
}
|
||||
Direction::NorthWest => {
|
||||
let x = 0;
|
||||
let y = 0;
|
||||
(x, y)
|
||||
}
|
||||
Direction::SouthWest => {
|
||||
let x = 0;
|
||||
let y = img_height - crop_height;
|
||||
(x, y)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for CropTransformer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "crop({},{},{})", self.w, self.h, self.float)
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageTransformer for CropTransformer {
|
||||
fn parse_args(args: &str) -> Result<Self, String> {
|
||||
let args: Vec<&str> = args.split(",").collect();
|
||||
if args.len() != 3 {
|
||||
return Err(format!("expected 3 args, got {}", args.len()));
|
||||
}
|
||||
|
||||
let w = args[0].trim().parse::<PixelDim>()?;
|
||||
let h = args[1].trim().parse::<PixelDim>()?;
|
||||
|
||||
let direction = args[2].trim();
|
||||
let direction = Direction::from_str(direction)
|
||||
.map_err(|_err| format!("invalid direction {direction}"))?;
|
||||
|
||||
Ok(Self {
|
||||
w,
|
||||
h,
|
||||
float: direction,
|
||||
})
|
||||
}
|
||||
|
||||
fn transform(&self, input: &mut DynamicImage) {
|
||||
let (img_width, img_height) = (input.width(), input.height());
|
||||
let (crop_width, crop_height) = self.crop_dim(img_width, img_height);
|
||||
|
||||
if (crop_width < img_width || crop_height < img_height) && crop_width > 0 && crop_height > 0
|
||||
{
|
||||
let (x, y) = self.crop_pos(img_width, img_height, crop_width, crop_height);
|
||||
*input = input.crop(x, y, crop_width, crop_height);
|
||||
}
|
||||
}
|
||||
}
|
||||
86
crates/servable/src/transform/transformers/maxdim.rs
Normal file
86
crates/servable/src/transform/transformers/maxdim.rs
Normal file
@@ -0,0 +1,86 @@
|
||||
use image::{DynamicImage, imageops::FilterType};
|
||||
use std::fmt::Display;
|
||||
|
||||
use super::super::{pixeldim::PixelDim, transformers::ImageTransformer};
|
||||
|
||||
/// Scale an image until it fits in a configured bounding box.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct MaxDimTransformer {
|
||||
w: PixelDim,
|
||||
h: PixelDim,
|
||||
}
|
||||
|
||||
impl MaxDimTransformer {
|
||||
/// Create a new [MaxDimTransformer] that scales an image down
|
||||
/// until it fits in a box of dimension `w x h`.
|
||||
///
|
||||
/// Images are never scaled up.
|
||||
pub fn new(w: PixelDim, h: PixelDim) -> Self {
|
||||
Self { w, h }
|
||||
}
|
||||
|
||||
fn target_dim(&self, img_width: u32, img_height: u32) -> (u32, u32) {
|
||||
let max_width = match self.w {
|
||||
PixelDim::Pixels(w) => Some(w),
|
||||
PixelDim::WidthPercent(pct) => Some(((img_width as f32) * pct / 100.0) as u32),
|
||||
PixelDim::HeightPercent(_) => None,
|
||||
};
|
||||
|
||||
let max_height = match self.h {
|
||||
PixelDim::Pixels(h) => Some(h),
|
||||
PixelDim::HeightPercent(pct) => Some(((img_height as f32) * pct / 100.0) as u32),
|
||||
PixelDim::WidthPercent(_) => None,
|
||||
};
|
||||
|
||||
if max_width.map(|x| img_width <= x).unwrap_or(true)
|
||||
&& max_height.map(|x| img_height <= x).unwrap_or(true)
|
||||
{
|
||||
return (img_width, img_height);
|
||||
}
|
||||
|
||||
let width_ratio = max_width
|
||||
.map(|x| x as f32 / img_width as f32)
|
||||
.unwrap_or(1.0);
|
||||
|
||||
let height_ratio = max_height
|
||||
.map(|x| x as f32 / img_height as f32)
|
||||
.unwrap_or(1.0);
|
||||
|
||||
let ratio = width_ratio.min(height_ratio);
|
||||
|
||||
(
|
||||
(img_width as f32 * ratio) as u32,
|
||||
(img_height as f32 * ratio) as u32,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for MaxDimTransformer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "maxdim({},{})", self.w, self.h)
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageTransformer for MaxDimTransformer {
|
||||
fn parse_args(args: &str) -> Result<Self, String> {
|
||||
let args: Vec<&str> = args.split(",").collect();
|
||||
if args.len() != 2 {
|
||||
return Err(format!("expected 2 args, got {}", args.len()));
|
||||
}
|
||||
|
||||
let w = args[0].parse::<PixelDim>()?;
|
||||
let h = args[1].parse::<PixelDim>()?;
|
||||
|
||||
Ok(Self { w, h })
|
||||
}
|
||||
|
||||
fn transform(&self, input: &mut DynamicImage) {
|
||||
let (img_width, img_height) = (input.width(), input.height());
|
||||
let (target_width, target_height) = self.target_dim(img_width, img_height);
|
||||
|
||||
// Only resize if needed
|
||||
if target_width != img_width || target_height != img_height {
|
||||
*input = input.resize(target_width, target_height, FilterType::Lanczos3);
|
||||
}
|
||||
}
|
||||
}
|
||||
171
crates/servable/src/transform/transformers/mod.rs
Normal file
171
crates/servable/src/transform/transformers/mod.rs
Normal file
@@ -0,0 +1,171 @@
|
||||
//! Defines all transformation steps we can apply to an image
|
||||
|
||||
use image::{DynamicImage, ImageFormat};
|
||||
use std::fmt;
|
||||
use std::fmt::{Debug, Display};
|
||||
use std::str::FromStr;
|
||||
|
||||
mod crop;
|
||||
pub use crop::*;
|
||||
|
||||
mod maxdim;
|
||||
pub use maxdim::*;
|
||||
|
||||
/// A single transformation that may be applied to an image.
|
||||
pub trait ImageTransformer
|
||||
where
|
||||
Self: PartialEq,
|
||||
Self: Sized + Clone,
|
||||
Self: Display + Debug,
|
||||
{
|
||||
/// Transform the given image in place
|
||||
fn transform(&self, input: &mut DynamicImage);
|
||||
|
||||
/// Parse an arg string.
|
||||
///
|
||||
/// `name({arg_string})`
|
||||
fn parse_args(args: &str) -> Result<Self, String>;
|
||||
}
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
/// An enum of all [`ImageTransformer`]s
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum TransformerEnum {
|
||||
/// Usage: `maxdim(w, h)`
|
||||
///
|
||||
/// Scale the image so its width is smaller than `w`
|
||||
/// and its height is smaller than `h`. Aspect ratio is preserved.
|
||||
///
|
||||
/// To only limit the size of one dimension, use `vw` or `vh`.
|
||||
/// For example, `maxdim(50,100vh)` will not limit width.
|
||||
MaxDim(MaxDimTransformer),
|
||||
|
||||
/// Usage: `crop(w, h, float)`
|
||||
///
|
||||
/// Crop the image to at most `w` by `h` pixels,
|
||||
/// floating the crop area in the specified direction.
|
||||
///
|
||||
/// Directions are one of:
|
||||
/// - Cardinal: n,e,s,w
|
||||
/// - Diagonal: ne,nw,se,sw,
|
||||
/// - Centered: c
|
||||
///
|
||||
/// Examples:
|
||||
/// - `crop(100vw, 50)` gets the top 50 pixels of the image \
|
||||
/// (or fewer, if the image's height is smaller than 50)
|
||||
///
|
||||
/// To only limit the size of one dimension, use `vw` or `vh`.
|
||||
/// For example, `maxdim(50,100vh)` will not limit width.
|
||||
Crop(CropTransformer),
|
||||
|
||||
/// Usage: `format(format)`
|
||||
///
|
||||
/// Transcode the image to the given format.
|
||||
/// This step must be last, and cannot be provided
|
||||
/// more than once.
|
||||
///
|
||||
/// Valid formats:
|
||||
/// - bmp
|
||||
/// - gif
|
||||
/// - ico
|
||||
/// - jpeg or jpg
|
||||
/// - png
|
||||
/// - qoi
|
||||
/// - webp
|
||||
///
|
||||
/// Example:
|
||||
/// - `format(png)`
|
||||
///
|
||||
/// When transcoding an animated gif, the first frame is taken
|
||||
/// and all others are thrown away. This happens even if we
|
||||
/// transcode from a gif to a gif.
|
||||
Format {
|
||||
/// The format to produce
|
||||
format: ImageFormat,
|
||||
},
|
||||
}
|
||||
|
||||
impl FromStr for TransformerEnum {
|
||||
type Err = String;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let s = s.trim();
|
||||
|
||||
let (name, args) = {
|
||||
let name_len = match s.find('(') {
|
||||
Some(x) => x + 1,
|
||||
None => {
|
||||
return Err(format!(
|
||||
"invalid transformation {s}. Must look like name(args)."
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let mut balance = 1;
|
||||
let mut end = name_len;
|
||||
for i in s[name_len..].bytes() {
|
||||
match i {
|
||||
b')' => balance -= 1,
|
||||
b'(' => balance += 1,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if balance == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
end += 1;
|
||||
}
|
||||
|
||||
if balance != 0 {
|
||||
return Err(format!("mismatched parenthesis in {s}"));
|
||||
}
|
||||
|
||||
let name = s[0..name_len - 1].trim();
|
||||
let args = s[name_len..end].trim();
|
||||
let trail = s[end + 1..].trim();
|
||||
if !trail.is_empty() {
|
||||
return Err(format!(
|
||||
"invalid transformation {s}. Must look like name(args)."
|
||||
));
|
||||
}
|
||||
|
||||
(name, args)
|
||||
};
|
||||
|
||||
match name {
|
||||
"maxdim" => Ok(Self::MaxDim(MaxDimTransformer::parse_args(args)?)),
|
||||
"crop" => Ok(Self::Crop(CropTransformer::parse_args(args)?)),
|
||||
|
||||
"format" => Ok(TransformerEnum::Format {
|
||||
format: ImageFormat::from_extension(args)
|
||||
.ok_or(format!("invalid image format {args}"))?,
|
||||
}),
|
||||
|
||||
_ => Err(format!("unknown transformation {name}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for TransformerEnum {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
s.parse().map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for TransformerEnum {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
TransformerEnum::MaxDim(x) => Display::fmt(x, f),
|
||||
TransformerEnum::Crop(x) => Display::fmt(x, f),
|
||||
TransformerEnum::Format { format } => {
|
||||
write!(f, "format({})", format.extensions_str()[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
148
crates/servable/src/types.rs
Normal file
148
crates/servable/src/types.rs
Normal file
@@ -0,0 +1,148 @@
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use chrono::TimeDelta;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::mime::MimeType;
|
||||
|
||||
//
|
||||
// MARK: rendered
|
||||
//
|
||||
|
||||
/// The contents of a response
|
||||
/// produced by a [crate::servable::Servable]
|
||||
#[derive(Clone)]
|
||||
pub enum RenderedBody {
|
||||
/// Static raw bytes
|
||||
Static(&'static [u8]),
|
||||
|
||||
/// Dynamic raw bytes
|
||||
Bytes(Vec<u8>),
|
||||
|
||||
/// A UTF-8 string
|
||||
String(String),
|
||||
|
||||
/// No body. Equivalent to `Self::Static(&[])`.
|
||||
Empty,
|
||||
}
|
||||
|
||||
trait RenderedBodyTypeSealed {}
|
||||
impl RenderedBodyTypeSealed for () {}
|
||||
impl RenderedBodyTypeSealed for RenderedBody {}
|
||||
|
||||
/// A utility trait, used to control the
|
||||
/// kind of body [Rendered] contains.
|
||||
///
|
||||
/// This trait is only implemented by two types:
|
||||
/// - `()`, when a request must return an empty body (i.e, HEAD)
|
||||
/// - [RenderedBody], when a request should return a full response (i.e, GET)
|
||||
#[expect(private_bounds)]
|
||||
pub trait RenderedBodyType: RenderedBodyTypeSealed {}
|
||||
impl<T: RenderedBodyTypeSealed> RenderedBodyType for T {}
|
||||
|
||||
/// An asset to return from an http route
|
||||
#[derive(Clone)]
|
||||
pub struct Rendered<T: RenderedBodyType> {
|
||||
/// The code to return
|
||||
pub code: StatusCode,
|
||||
|
||||
/// The headers to return
|
||||
pub headers: HeaderMap,
|
||||
|
||||
/// The content to return
|
||||
pub body: T,
|
||||
|
||||
/// The type of `self.body`
|
||||
pub mime: Option<MimeType>,
|
||||
|
||||
/// How long to cache this response.
|
||||
/// If none, don't cache.
|
||||
pub ttl: Option<TimeDelta>,
|
||||
|
||||
/// If true, the data at this route will never change.
|
||||
pub immutable: bool,
|
||||
}
|
||||
|
||||
impl Rendered<()> {
|
||||
/// Turn this [Rendered] into a [Rendered] with a body.
|
||||
pub fn with_body(self, body: RenderedBody) -> Rendered<RenderedBody> {
|
||||
Rendered {
|
||||
code: self.code,
|
||||
headers: self.headers,
|
||||
body,
|
||||
mime: self.mime,
|
||||
ttl: self.ttl,
|
||||
immutable: self.immutable,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional context available to [crate::servable::Servable]s
|
||||
/// when generating their content
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct RenderContext {
|
||||
/// Information about the request
|
||||
pub client_info: ClientInfo,
|
||||
|
||||
/// The route that was requested.
|
||||
/// Starts with a /.
|
||||
pub route: String,
|
||||
|
||||
/// This request's query parameters
|
||||
pub query: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// The type of device that requested a page
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum DeviceType {
|
||||
/// This is a mobile device, like a phone.
|
||||
Mobile,
|
||||
|
||||
/// This is a device with a large screen
|
||||
/// and a mouse, like a laptop.
|
||||
Desktop,
|
||||
}
|
||||
|
||||
impl Default for DeviceType {
|
||||
fn default() -> Self {
|
||||
Self::Desktop
|
||||
}
|
||||
}
|
||||
|
||||
/// Inferred information about the client
|
||||
/// that requested a certain route.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct ClientInfo {
|
||||
/// The type of device that is viewing this page.
|
||||
///
|
||||
/// We do our best to detect this value automatically,
|
||||
/// but we may be wrong.
|
||||
pub device_type: DeviceType,
|
||||
}
|
||||
|
||||
impl ClientInfo {
|
||||
pub(crate) fn from_headers(headers: &HeaderMap) -> Self {
|
||||
let ua = headers
|
||||
.get("user-agent")
|
||||
.and_then(|x| x.to_str().ok())
|
||||
.unwrap_or("");
|
||||
|
||||
let ch_mobile = headers
|
||||
.get("Sec-CH-UA-Mobile")
|
||||
.and_then(|x| x.to_str().ok())
|
||||
.unwrap_or("");
|
||||
|
||||
let mut device_type = None;
|
||||
|
||||
if device_type.is_none() && ch_mobile.contains("1") {
|
||||
device_type = Some(DeviceType::Mobile);
|
||||
}
|
||||
|
||||
if device_type.is_none() && ua.contains("Mobile") {
|
||||
device_type = Some(DeviceType::Mobile);
|
||||
}
|
||||
|
||||
Self {
|
||||
device_type: device_type.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user