163 lines
5.6 KiB
Rust
163 lines
5.6 KiB
Rust
//! Immutable, manifest-pinned assets acquired before native serving starts.
|
|
use std::{
|
|
fs::{self, File, OpenOptions},
|
|
io,
|
|
path::{Component, Path, PathBuf},
|
|
};
|
|
|
|
use serde::Deserialize;
|
|
|
|
use crate::model;
|
|
|
|
type Result<T> = std::result::Result<T, crate::BoxError>;
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct AssetBundle {
|
|
pub manifest: PathBuf,
|
|
pub directory: PathBuf,
|
|
}
|
|
|
|
pub fn validate(bundles: &[AssetBundle]) -> Result<()> {
|
|
if bundles.len() > 16 {
|
|
return Err("at most 16 asset bundles may be configured".into());
|
|
}
|
|
for (index, bundle) in bundles.iter().enumerate() {
|
|
for path in [&bundle.manifest, &bundle.directory] {
|
|
if !path.is_absolute()
|
|
|| path.file_name().is_none()
|
|
|| path
|
|
.components()
|
|
.any(|part| matches!(part, Component::ParentDir))
|
|
{
|
|
return Err("asset paths must be absolute, non-root paths without '..'".into());
|
|
}
|
|
}
|
|
if bundles[..index].iter().any(|other| {
|
|
other.directory.starts_with(&bundle.directory)
|
|
|| bundle.directory.starts_with(&other.directory)
|
|
}) {
|
|
return Err("asset bundle destinations must not overlap".into());
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Parse every manifest before mutation. Each destination is an immutable
|
|
/// versioned bundle: a mismatch is an error, never an implicit replacement.
|
|
pub async fn provision(bundles: &[AssetBundle]) -> Result<()> {
|
|
validate(bundles)?;
|
|
let mut manifests = Vec::with_capacity(bundles.len());
|
|
for bundle in bundles {
|
|
manifests.push(model::Manifest::load(&bundle.manifest).await?);
|
|
}
|
|
for (bundle, manifest) in bundles.iter().zip(manifests) {
|
|
ensure(bundle, &manifest).await?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
async fn ensure(bundle: &AssetBundle, manifest: &model::Manifest) -> Result<()> {
|
|
let parent = bundle
|
|
.directory
|
|
.parent()
|
|
.ok_or("asset directory has no parent")?;
|
|
fs::create_dir_all(parent)?;
|
|
let name = bundle
|
|
.directory
|
|
.file_name()
|
|
.ok_or("asset directory has no name")?;
|
|
let sibling = |suffix: &str| sibling_path(parent, name, suffix);
|
|
let _lock = lock_destination(&sibling(".strata-lock"))?;
|
|
if directory_exists(&bundle.directory)? {
|
|
return verify_bundle(manifest, &bundle.directory).await;
|
|
}
|
|
let stage = sibling(".strata-stage");
|
|
create_stage(&stage)?;
|
|
acquire_stage(manifest, &stage).await?;
|
|
publish_stage(&stage, &bundle.directory, parent)
|
|
}
|
|
|
|
async fn acquire_stage(manifest: &model::Manifest, stage: &Path) -> Result<()> {
|
|
// On failure the private stage remains for resumable acquisition. It is
|
|
// never used by the worker and never replaces an existing bundle.
|
|
model::fetch(manifest, stage).await?;
|
|
verify_bundle(manifest, stage).await?;
|
|
File::open(stage)?.sync_all()?;
|
|
Ok(())
|
|
}
|
|
|
|
fn sibling_path(parent: &Path, name: &std::ffi::OsStr, suffix: &str) -> PathBuf {
|
|
let mut value = std::ffi::OsString::from(".");
|
|
value.push(name);
|
|
value.push(suffix);
|
|
parent.join(value)
|
|
}
|
|
|
|
fn publish_stage(stage: &Path, destination: &Path, parent: &Path) -> Result<()> {
|
|
if fs::symlink_metadata(destination).is_ok() {
|
|
return Err("asset destination appeared during preparation; refusing to replace it".into());
|
|
}
|
|
crate::immutable_directory::publish(stage, destination)?;
|
|
File::open(parent)?.sync_all()?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Takes the exclusive lock file of one destination; the lock is held until the returned file is dropped.
|
|
fn lock_destination(path: &Path) -> Result<File> {
|
|
// Keep the lock inode after releasing it: unlinking could let two later
|
|
// preparers lock different inodes for the same destination. OS locks are
|
|
// released on process death, allowing interrupted downloads to resume.
|
|
let mut options = OpenOptions::new();
|
|
options.read(true).write(true).create(true).truncate(false);
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::OpenOptionsExt;
|
|
options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
|
|
}
|
|
let lock = options.open(path)?;
|
|
if !lock.metadata()?.is_file() {
|
|
return Err("asset lock must be a regular file".into());
|
|
}
|
|
lock.try_lock().map_err(
|
|
|_| "asset bundle is busy or cannot be locked; retry after preparation finishes",
|
|
)?;
|
|
Ok(lock)
|
|
}
|
|
|
|
fn create_stage(stage: &Path) -> Result<()> {
|
|
if !directory_exists(stage)? {
|
|
let mut builder = fs::DirBuilder::new();
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::DirBuilderExt;
|
|
builder.mode(0o700);
|
|
}
|
|
builder.create(stage)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn directory_exists(path: &Path) -> Result<bool> {
|
|
match fs::symlink_metadata(path) {
|
|
Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(true),
|
|
Ok(_) => Err("asset destination/stage must be a directory, not a symlink".into()),
|
|
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
|
|
Err(error) => Err(error.into()),
|
|
}
|
|
}
|
|
|
|
async fn verify_bundle(manifest: &model::Manifest, directory: &Path) -> Result<()> {
|
|
// Extra files could come from a different interrupted manifest. Do not
|
|
// silently publish a mixed bundle or trust a completion marker alone.
|
|
for entry in fs::read_dir(directory)? {
|
|
let name = entry?.file_name();
|
|
if !manifest.files.iter().any(|file| name == file.name.as_str()) {
|
|
return Err(
|
|
"asset bundle contains files absent from its manifest; use a new directory".into(),
|
|
);
|
|
}
|
|
}
|
|
model::verify(manifest, directory).await
|
|
}
|