Files
leleka/control-plane/src/service_switch.rs
T
Pavlo Ratushnyi 6b5fcd242e STRA-338 S12b: fns and impl blocks of 59 cold oversize modules move into child modules (model-format, gateway, desktop-core, leaf libraries)
scripts/dev/split_module.py (lexer-based, with 16 self-tests) moves the top-level fn and impl items of 59 oversize module files in control-plane, desktop-core, model-format, gateway-text, leleka-memory, experimental-ref, context, serving-policy, tokenizer, backend-api, quant-core, harmony, igpu, libc-shim, npu-service and runtime-client into foo/<name>.rs groups of about 250 lines; types, constants, macros, nested modules and tests stay, every path stays valid through pub use re-exports, restricted visibilities keep their scope one level down, include paths and super:: paths are shifted. Not touched: leleka-runtime, cuda-driver, native-cpu-expert, sampler-ref and cpu-* (hot path, next wave) and the files kar-off-ab edits.

The baseline drops from 311 to 263 oversize files and from 273,600 to about 233,000 lines; the path-include ratchet ignores dir/name.rs child declarations.
2026-11-05 15:29:39 +01:00

207 lines
7.7 KiB
Rust

//! Explicit transaction between installed native user services. Never replay an
//! interrupted lifecycle operation; retained phases require reconciliation.
use serde::Deserialize;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
time::Duration,
};
const USAGE: &str =
"usage: strata-next service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR";
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Catalog {
schema_version: u32,
profiles: BTreeMap<String, Profile>,
#[serde(default = "provision_budget")]
provision_timeout_s: u64,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Profile {
unit: String,
config: PathBuf,
working_dir: PathBuf,
url: String,
model: String,
key_file: Option<PathBuf>,
#[serde(default = "ready_budget")]
timeout_s: u64,
}
#[cfg(unix)]
mod storage {
use super::*;
use std::{
fs::{self, File, OpenOptions},
io::{Read, Write},
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
};
pub(super) fn read(path: &Path, private: bool, max: u64) -> Result<Vec<u8>, String> {
if !path.is_absolute() {
return Err("profile paths must be absolute".into());
}
let file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)
.map_err(|_| "cannot open profile file")?;
let meta = file.metadata().map_err(|_| "cannot inspect profile file")?;
if !meta.is_file()
|| meta.uid() != unsafe { libc::geteuid() }
|| meta.mode() & if private { 0o077 } else { 0o022 } != 0
|| meta.len() > max
{
return Err(
"profile file must be owned, regular, bounded and have safe permissions".into(),
);
}
let mut bytes = Vec::new();
file.take(max + 1)
.read_to_end(&mut bytes)
.map_err(|_| "cannot read profile file")?;
if bytes.len() as u64 > max {
return Err("profile file exceeds limit".into());
}
Ok(bytes)
}
pub(super) fn digest(path: &Path) -> Result<String, String> {
Ok(hex::encode(Sha256::digest(read(path, false, 1024 * 1024)?)))
}
pub(super) struct Journal {
dir: PathBuf,
directory: File,
_lock: File,
pub(super) value: Value,
}
impl Journal {
pub(super) fn open(path: &Path, value: Value) -> Result<Self, String> {
Self::open_inner(path, value, false)
}
pub(super) fn reconciliation(path: &Path) -> Result<Self, String> {
read(&path.join("transaction.json"), true, 65536)?;
Self::open_inner(path, json!({}), true)
}
fn open_inner(path: &Path, value: Value, reconciliation: bool) -> Result<Self, String> {
if !path.is_absolute() || path.file_name().is_none() {
return Err("state directory must be absolute and non-root".into());
}
match fs::DirBuilder::new().mode(0o700).create(path) {
Ok(()) => (),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => (),
Err(_) => {
return Err("cannot create private state directory; parent must exist".into());
}
}
let m = fs::symlink_metadata(path).map_err(|_| "cannot inspect state directory")?;
if !m.is_dir()
|| m.file_type().is_symlink()
|| m.uid() != unsafe { libc::geteuid() }
|| m.mode() & 0o777 != 0o700
{
return Err(
"state directory must be owned, private mode0700 and not a symlink".into(),
);
}
let dir = path
.canonicalize()
.map_err(|_| "cannot resolve state directory")?;
let lock = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(dir.join("switch.lock"))
.map_err(|_| "cannot open switch lock")?;
let m = lock.metadata().map_err(|_| "cannot inspect switch lock")?;
if !m.is_file() || m.uid() != unsafe { libc::geteuid() } || m.mode() & 0o077 != 0 {
return Err("unsafe switch lock".into());
}
lock.try_lock()
.map_err(|_| "another switch is running or lock is unavailable")?;
let previous = dir.join("transaction.json");
match fs::symlink_metadata(&previous) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
Err(_) => return Err("cannot inspect prior transaction".into()),
Ok(_) => {
let prior: Value = serde_json::from_slice(&read(&previous, true, 65536)?)
.map_err(|_| "invalid prior transaction; reconcile explicitly")?;
if !reconciliation
&& (prior["schema_version"] != 1
|| !matches!(
prior["phase"].as_str(),
Some(
"committed"
| "rolled_back"
| "preflight_failed"
| "cold_failed"
| "reused"
| "reconciled"
)
))
{
return Err("unfinished or unknown switch transaction; inspect services and archive journal only after explicit reconciliation".into());
}
}
}
let directory = File::open(&dir).map_err(|_| "cannot open state directory")?;
Ok(Self {
dir,
directory,
_lock: lock,
value,
})
}
pub(super) fn phase(&mut self, phase: &str) -> Result<(), String> {
self.value["phase"] = json!(phase);
let bytes =
serde_json::to_vec(&self.value).map_err(|_| "cannot encode switch journal")?;
let temp = self.dir.join(format!(
".transaction-{}-{}.tmp",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|_| "invalid clock")?
.as_nanos()
));
let write = (|| -> std::io::Result<()> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&temp)?;
file.write_all(&bytes)?;
file.sync_all()?;
fs::rename(&temp, self.dir.join("transaction.json"))?;
self.directory.sync_all()
})();
if write.is_err() {
let _ = fs::remove_file(&temp);
return Err(
"cannot durably record switch phase; no further action performed".into(),
);
}
Ok(())
}
}
}
#[cfg(test)]
mod tests;
mod provision_budget;
#[allow(unused_imports)]
pub use provision_budget::*;
mod run;
#[allow(unused_imports)]
pub use run::*;
mod reconcile;
#[allow(unused_imports)]
pub use reconcile::*;