use std::{
collections::BTreeMap,
path::{Path, PathBuf},
sync::{Arc, RwLock},
time::{Duration, SystemTime},
};
use axum::{
body::Body,
extract::{Path as RequestPath, State},
http::{header, HeaderValue, Method, Request, Response, StatusCode},
routing::get,
Router,
};
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
use proa_assets::{
AssetCatalog, AssetError, LiveReader, IMMUTABLE_DIRECTORY, MANIFEST_FILE, MUTABLE_DIRECTORY,
OUTPUT_ENV, PUBLIC_ROUTE,
};
use proa_core::{BasePath, PublicAssetUrls};
use thiserror::Error;
use tower::ServiceExt;
use tower_http::services::ServeFile;
const PATH_ENCODING: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'/')
.remove(b'-')
.remove(b'_')
.remove(b'.')
.remove(b'~');
const RACY_MANIFEST_WINDOW: Duration = Duration::from_secs(2);
pub const ASSET_PREFIX_ENV: &str = "PROA_ASSET_PREFIX";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AssetPrefix {
value: Arc<str>,
origin: Option<Arc<str>>,
}
#[derive(Debug, Error, PartialEq, Eq)]
#[error("invalid asset prefix `{0}`: use an http(s) URL or a path from the origin root, with no query or fragment")]
pub struct InvalidAssetPrefix(pub(crate) String);
impl AssetPrefix {
pub fn new(value: &str) -> Result<Self, InvalidAssetPrefix> {
let invalid = || InvalidAssetPrefix(value.to_owned());
let trimmed = value.trim_end_matches('/');
if trimmed.is_empty()
|| trimmed
.chars()
.any(|c| c.is_whitespace() || c.is_control() || "\"'<>\\?#;,".contains(c))
{
return Err(invalid());
}
if trimmed.starts_with('/') {
if trimmed[1..]
.split('/')
.any(|segment| matches!(segment, "" | "." | ".."))
{
return Err(invalid());
}
return Ok(Self {
value: Arc::from(trimmed),
origin: None,
});
}
let lowered = trimmed.to_ascii_lowercase();
if !(lowered.starts_with("http://") || lowered.starts_with("https://")) {
return Err(invalid());
}
let url = url::Url::parse(trimmed).map_err(|_| invalid())?;
if !matches!(url.scheme(), "http" | "https")
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
{
return Err(invalid());
}
Ok(Self {
value: Arc::from(trimmed),
origin: Some(Arc::from(url.origin().ascii_serialization())),
})
}
pub fn from_env() -> Result<Option<Self>, InvalidAssetPrefix> {
match std::env::var(ASSET_PREFIX_ENV) {
Ok(value) if !value.trim().is_empty() => Self::new(value.trim()).map(Some),
Ok(_) | Err(std::env::VarError::NotPresent) => Ok(None),
Err(std::env::VarError::NotUnicode(value)) => {
Err(InvalidAssetPrefix(value.to_string_lossy().into_owned()))
}
}
}
pub fn as_str(&self) -> &str {
&self.value
}
pub(crate) fn shared(&self) -> Arc<str> {
self.value.clone()
}
pub fn origin(&self) -> Option<&str> {
self.origin.as_deref()
}
}
#[derive(Debug, Error)]
pub enum PublicAssetError {
#[error(transparent)]
AssetPrefix(#[from] InvalidAssetPrefix),
#[error(transparent)]
Catalog(#[from] AssetError),
#[error("could not prepare public asset `{path}`: {reason}")]
Preparation { path: String, reason: String },
}
#[derive(Clone)]
pub struct PublicAssets {
catalog: Arc<PreparedCatalog>,
live: Option<Arc<LiveCatalog>>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct ManifestStamp {
modified: SystemTime,
len: u64,
}
impl ManifestStamp {
fn read(manifest: &Path) -> Option<Self> {
let meta = std::fs::metadata(manifest).ok()?;
Some(Self {
modified: meta.modified().ok()?,
len: meta.len(),
})
}
fn settled(self) -> bool {
self.modified
.elapsed()
.is_ok_and(|age| age > RACY_MANIFEST_WINDOW)
}
}
struct LiveState {
catalog: Arc<PreparedCatalog>,
settled: Option<ManifestStamp>,
rejected: Option<String>,
}
struct LiveCatalog {
output: PathBuf,
manifest: PathBuf,
base_path: BasePath,
state: RwLock<LiveState>,
_registration: LiveReader,
}
impl LiveCatalog {
fn current(&self) -> Arc<PreparedCatalog> {
let stamp = ManifestStamp::read(&self.manifest);
{
let state = self.state.read().unwrap_or_else(|e| e.into_inner());
if stamp.is_some() && stamp == state.settled {
return state.catalog.clone();
}
}
let mut state = self.state.write().unwrap_or_else(|e| e.into_inner());
let stamp = ManifestStamp::read(&self.manifest).filter(|stamp| stamp.settled());
if stamp.is_some() && stamp == state.settled {
return state.catalog.clone();
}
let Ok(bytes) = std::fs::read(&self.manifest) else {
return state.catalog.clone();
};
let generation = proa_assets::sha256(&bytes);
if generation != state.catalog.catalog.generation()
&& state.rejected.as_deref() != Some(generation.as_str())
{
match AssetCatalog::load(&self.output)
.map_err(PublicAssetError::from)
.and_then(|catalog| PreparedCatalog::from_catalog(catalog, &self.base_path, None))
{
Ok(catalog) => {
tracing::debug!("public asset catalog reloaded in place");
state.catalog = Arc::new(catalog);
state.rejected = None;
}
Err(error) => {
tracing::warn!(
%error,
"could not reload the public asset catalog; serving the previous one"
);
state.rejected = Some(generation);
}
}
}
state.settled = stamp;
state.catalog.clone()
}
}
struct PreparedCatalog {
catalog: AssetCatalog,
base_path: BasePath,
asset_prefix: Option<AssetPrefix>,
urls: PublicAssetUrls,
routes: BTreeMap<String, PreparedFile>,
root: BTreeMap<String, PreparedFile>,
cache_key: String,
}
#[derive(Clone)]
struct PreparedFile {
service: ServeFile,
etag: HeaderValue,
content_type: HeaderValue,
cache_control: HeaderValue,
}
fn bundled_with_current_executable() -> Option<PathBuf> {
let executable = std::env::current_exe().ok()?;
let executable = executable.canonicalize().unwrap_or(executable);
bundled_catalog(&executable)
}
fn bundled_catalog(executable: &Path) -> Option<PathBuf> {
let output = proa_assets::bundled_output(executable)?;
proa_assets::is_output(&output).then_some(output)
}
impl PublicAssets {
pub fn load(output: impl AsRef<Path>, base_path: &BasePath) -> Result<Self, PublicAssetError> {
Self::load_hosted(output, base_path, None)
}
pub fn load_hosted(
output: impl AsRef<Path>,
base_path: &BasePath,
asset_prefix: Option<&AssetPrefix>,
) -> Result<Self, PublicAssetError> {
let prepared =
PreparedCatalog::from_catalog(AssetCatalog::load(output)?, base_path, asset_prefix)?;
Ok(Self {
catalog: Arc::new(prepared),
live: None,
})
}
pub fn load_live(
output: impl AsRef<Path>,
base_path: &BasePath,
) -> Result<Self, PublicAssetError> {
let output = output.as_ref();
let fixed = Self::load(output, base_path)?;
let Ok(registration) = LiveReader::register(output) else {
return Ok(fixed);
};
Ok(Self {
live: Some(Arc::new(LiveCatalog {
manifest: output.join(MANIFEST_FILE),
output: output.to_path_buf(),
base_path: base_path.clone(),
state: RwLock::new(LiveState {
catalog: fixed.catalog.clone(),
settled: None,
rejected: None,
}),
_registration: registration,
})),
catalog: fixed.catalog,
})
}
pub fn configured() -> bool {
std::env::var_os(OUTPUT_ENV).is_some() || bundled_with_current_executable().is_some()
}
pub fn from_env(base_path: &BasePath) -> Result<Option<Self>, PublicAssetError> {
let Some(path) = std::env::var_os(OUTPUT_ENV)
.map(PathBuf::from)
.or_else(bundled_with_current_executable)
else {
return Ok(None);
};
if crate::dev_reload::session_from_env() {
Self::load_live(path, base_path).map(Some)
} else {
Self::load_hosted(path, base_path, AssetPrefix::from_env()?.as_ref()).map(Some)
}
}
pub fn current(&self) -> Self {
match &self.live {
Some(live) => Self {
catalog: live.current(),
live: None,
},
None => self.clone(),
}
}
pub fn url(&self, logical: &str) -> Option<&str> {
self.catalog.urls.get(logical)
}
pub fn render_urls(&self) -> PublicAssetUrls {
match &self.live {
Some(live) => live.current().urls.clone(),
None => self.catalog.urls.clone(),
}
}
pub fn asset_prefix(&self) -> Option<&AssetPrefix> {
self.catalog.asset_prefix.as_ref()
}
pub(crate) fn catalog(&self) -> &AssetCatalog {
&self.catalog.catalog
}
pub(crate) fn base_path(&self) -> &BasePath {
&self.catalog.base_path
}
pub fn cache_key(&self) -> &str {
&self.catalog.cache_key
}
pub fn serve_root_files(&self, router: Router) -> Router {
if self.live.is_none() && self.catalog.root.is_empty() {
return router;
}
let assets = self.clone();
router.layer(axum::middleware::from_fn(
move |request: Request<Body>, next: axum::middleware::Next| {
let assets = assets.clone();
async move {
let assets = assets.current();
let wanted = matches!(*request.method(), Method::GET | Method::HEAD)
&& assets.catalog.root.contains_key(request.uri().path());
if !wanted {
return next.run(request).await;
}
let (parts, body) = request.into_parts();
let response = next.run(Request::from_parts(parts.clone(), body)).await;
if response.status() != StatusCode::NOT_FOUND {
return response;
}
let file = &assets.catalog.root[parts.uri.path()];
respond(file, Request::from_parts(parts, Body::empty())).await
}
},
))
}
pub fn router(&self) -> Router {
Router::new()
.route(
&format!("{PUBLIC_ROUTE}/{IMMUTABLE_DIRECTORY}/{{*path}}"),
get(serve_immutable),
)
.route(
&format!("{PUBLIC_ROUTE}/{MUTABLE_DIRECTORY}/{{*path}}"),
get(serve_mutable),
)
.with_state(self.clone())
}
}
impl PreparedCatalog {
fn from_catalog(
catalog: AssetCatalog,
base_path: &BasePath,
asset_prefix: Option<&AssetPrefix>,
) -> Result<Self, PublicAssetError> {
let prefix = asset_prefix.map_or(base_path.as_str(), AssetPrefix::as_str);
let mut urls = BTreeMap::new();
let mut routes = BTreeMap::new();
for (logical, entry) in &catalog.manifest().assets {
let fail = |reason: String| PublicAssetError::Preparation {
path: logical.clone(),
reason,
};
let mime: mime::Mime = entry
.content_type
.parse()
.map_err(|e: mime::FromStrError| fail(e.to_string()))?;
let path = catalog.object_path(logical).expect("manifest entry");
let file = PreparedFile {
service: ServeFile::new_with_mime(path, &mime),
etag: format!("\"{}\"", entry.sha256)
.parse()
.expect("SHA-256 header"),
content_type: entry
.content_type
.parse()
.map_err(|e: axum::http::header::InvalidHeaderValue| fail(e.to_string()))?,
cache_control: HeaderValue::from_static(entry.cache_policy.cache_control()),
};
let url_path = entry.url_path();
let encoded = utf8_percent_encode(&url_path, PATH_ENCODING);
urls.insert(
logical.clone(),
Arc::from(format!("{prefix}{PUBLIC_ROUTE}/{encoded}")),
);
routes.insert(url_path, file);
}
let mut root = BTreeMap::new();
for (path, logical) in &catalog.manifest().root {
let entry = &catalog.manifest().assets[logical];
let mut file = routes[&entry.url_path()].clone();
file.cache_control =
HeaderValue::from_static(proa_assets::CachePolicy::Revalidate.cache_control());
root.insert(format!("/{path}"), file);
}
let cache_key = proa_assets::sha256(
format!("{}\n{}\n{prefix}", catalog.generation(), base_path.as_str()).as_bytes(),
);
Ok(Self {
catalog,
base_path: base_path.clone(),
asset_prefix: asset_prefix.cloned(),
urls: PublicAssetUrls::new(urls),
routes,
root,
cache_key,
})
}
}
async fn serve_immutable(
assets: State<PublicAssets>,
RequestPath(path): RequestPath<String>,
request: Request<Body>,
) -> Response<Body> {
serve(assets, IMMUTABLE_DIRECTORY, &path, request).await
}
async fn serve_mutable(
assets: State<PublicAssets>,
RequestPath(path): RequestPath<String>,
request: Request<Body>,
) -> Response<Body> {
serve(assets, MUTABLE_DIRECTORY, &path, request).await
}
async fn serve(
State(assets): State<PublicAssets>,
directory: &str,
path: &str,
request: Request<Body>,
) -> Response<Body> {
let assets = assets.current();
match assets.catalog.routes.get(&format!("{directory}/{path}")) {
Some(file) => respond(file, request).await,
None => empty(StatusCode::NOT_FOUND),
}
}
async fn respond(file: &PreparedFile, mut request: Request<Body>) -> Response<Body> {
let matches = request
.headers()
.get_all(header::IF_NONE_MATCH)
.iter()
.any(|value| {
value.to_str().is_ok_and(|value| {
value.split(',').any(|tag| {
let tag = tag.trim();
tag == "*" || tag.strip_prefix("W/").unwrap_or(tag) == file.etag
})
})
});
let mut response = if matches {
empty(StatusCode::NOT_MODIFIED)
} else {
request.headers_mut().remove(header::IF_NONE_MATCH);
request.headers_mut().remove(header::IF_MODIFIED_SINCE);
if let Some(if_range) = request.headers_mut().remove(header::IF_RANGE) {
if if_range != file.etag {
request.headers_mut().remove(header::RANGE);
}
}
file.service
.clone()
.oneshot(request)
.await
.unwrap()
.map(Body::new)
};
if response.status().is_success() || response.status() == StatusCode::NOT_MODIFIED {
let headers = response.headers_mut();
headers.insert(header::ETAG, file.etag.clone());
headers.insert(header::CONTENT_TYPE, file.content_type.clone());
headers.insert(header::CACHE_CONTROL, file.cache_control.clone());
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
headers.remove(header::LAST_MODIFIED);
}
response
}
fn empty(status: StatusCode) -> Response<Body> {
let mut response = Response::new(Body::empty());
*response.status_mut() = status;
response
}
#[cfg(test)]
mod tests;