Files
leleka/control-plane/src/asset_bundle.rs
T
Pavlo Ratushnyi 35bf3a03d3 STRA-338 S16: gateway ports (EngineClient, ResponseStore, Clock, ToolHub, VisionEncoder) with adapters and fakes
AppState now holds ports instead of concrete types: `engine: Option<SharedEngine>` replaces the
mpsc::Sender<GenerationCommand>, `responses: SharedResponseStore` replaces Arc<RwLock<ResponseHistory>>,
`clock: SharedClock` serves queue deadlines, uptime and response timestamps, `mcp` is a ToolHub and `vision` a
VisionEncoder. The channel (adapters::ChannelEngine), the history with its disk snapshot
(responses::HistoryResponseStore), the system clock, mcp::Hub and vision::Vision are the adapters; main.rs serve()
composes them. No behaviour change: the HTTP handlers make the same calls in the same order, the queue claim race is
unchanged, only the deadline now reads the injected clock.

Ports are called per request, never per token or stream event (docs/architecture/gateway-ports.md).
ports/fakes has an in-memory adapter per port; control-plane/tests/ports_fakes.rs (12 tests), queue.rs and
adapters/channel_engine.rs add tests that drive the real handlers through them.

Architecture gate: dyn-trait:strata-control fell 35 -> 21 (a BoxError alias replaces 20 `Box<dyn Error>` spellings,
which pays for the 6 new port aliases); main.rs 1156 -> 1155 lines. Also adds scripts/dev/test-outcomes.py (per-test
outcome comparison of two cargo test logs) and scripts/dev/wsl-cargo.sh.
2026-11-05 20:06:28 +01:00

141 lines
5.0 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| {
let mut value = std::ffi::OsString::from(".");
value.push(name);
value.push(suffix);
parent.join(value)
};
// 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(sibling(".strata-lock"))?;
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",
)?;
if directory_exists(&bundle.directory)? {
return verify_bundle(manifest, &bundle.directory).await;
}
let stage = sibling(".strata-stage");
if !directory_exists(&stage)? {
let mut builder = fs::DirBuilder::new();
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder.create(&stage)?;
}
// 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()?;
if fs::symlink_metadata(&bundle.directory).is_ok() {
return Err("asset destination appeared during preparation; refusing to replace it".into());
}
crate::immutable_directory::publish(&stage, &bundle.directory)?;
File::open(parent)?.sync_all()?;
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
}