use std::fmt; use std::path::Path; #[derive(Debug, Clone, PartialEq, Eq)] pub enum LazyFsCommand { ClearCache, CacheCheckpoint, DisplayCacheUsage, UnsyncedDataReport, Help, Crash(CrashCommand), TornOp(TornOpCommand), TornSeq(TornSeqCommand), } impl LazyFsCommand { pub fn render(&self) -> String { match self { Self::ClearCache => "lazyfs::clear-cache".to_string(), Self::CacheCheckpoint => "lazyfs::cache-checkpoint".to_string(), Self::DisplayCacheUsage => "lazyfs::display-cache-usage".to_string(), Self::UnsyncedDataReport => "lazyfs::unsynced-data-report".to_string(), Self::Help => "lazyfs::help".to_string(), Self::Crash(command) => command.render(), Self::TornOp(command) => command.render(), Self::TornSeq(command) => command.render(), } } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum LazyFsCommandError { MissingCrashPathRegex, EmptyPersistSet { command: &'static str, }, ZeroPersistIndex { command: &'static str, }, PersistIndexOutOfRange { command: &'static str, index: usize, max: usize, }, InvalidCommandArgument { command: &'static str, argument: &'static str, reason: &'static str, }, ZeroTornOpParts, EmptyTornOpPartBytes, ZeroTornOpPartBytes, } impl fmt::Display for LazyFsCommandError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::MissingCrashPathRegex => { f.write_str("multi-path crash commands need at least one path regex") } Self::EmptyPersistSet { command } => { write!(f, "{command} commands need at least one persist index") } Self::ZeroPersistIndex { command } => { write!( f, "{command} persist indexes are 1-based and cannot be zero" ) } Self::PersistIndexOutOfRange { command, index, max, } => write!( f, "{command} persist index {index} exceeds the maximum part index {max}" ), Self::InvalidCommandArgument { command, argument, reason, } => write!(f, "{command} argument {argument} is invalid: {reason}"), Self::ZeroTornOpParts => f.write_str("torn-op parts must be greater than zero"), Self::EmptyTornOpPartBytes => { f.write_str("torn-op parts_bytes must contain at least one part") } Self::ZeroTornOpPartBytes => { f.write_str("torn-op parts_bytes values must be greater than zero") } } } } impl std::error::Error for LazyFsCommandError {} fn validate_persist(command: &'static str, persist: &[usize]) -> Result<(), LazyFsCommandError> { if persist.is_empty() { return Err(LazyFsCommandError::EmptyPersistSet { command }); } if persist.contains(&0) { return Err(LazyFsCommandError::ZeroPersistIndex { command }); } Ok(()) } fn validate_command_argument( command: &'static str, argument: &'static str, value: &str, ) -> Result<(), LazyFsCommandError> { let reason = if value.is_empty() { Some("empty values are not accepted by LazyFS") } else if value == "none" { Some("'none' is reserved as LazyFS's missing-value sentinel") } else if value.contains("::") { Some("contains LazyFS command delimiter '::'") } else if value.contains('\0') { Some("contains NUL") } else if value.contains('\n') || value.contains('\r') { Some("contains a line break") } else { None }; if let Some(reason) = reason { return Err(LazyFsCommandError::InvalidCommandArgument { command, argument, reason, }); } Ok(()) } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Timing { Before, After, } impl fmt::Display for Timing { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Before => f.write_str("before"), Self::After => f.write_str("after"), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CrashOp { Unlink, Truncate, Fsync, Write, Create, Access, Open, Read, Rename, Link, Symlink, } impl CrashOp { fn is_multi_path(self) -> bool { matches!(self, Self::Rename | Self::Link | Self::Symlink) } } impl fmt::Display for CrashOp { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Unlink => f.write_str("unlink"), Self::Truncate => f.write_str("truncate"), Self::Fsync => f.write_str("fsync"), Self::Write => f.write_str("write"), Self::Create => f.write_str("create"), Self::Access => f.write_str("access"), Self::Open => f.write_str("open"), Self::Read => f.write_str("read"), Self::Rename => f.write_str("rename"), Self::Link => f.write_str("link"), Self::Symlink => f.write_str("symlink"), } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct CrashCommand { timing: Timing, op: CrashOp, from_rgx: Option, to_rgx: Option, } impl CrashCommand { pub fn single_path( timing: Timing, op: CrashOp, from_rgx: impl Into, ) -> Result { assert!(!op.is_multi_path(), "{op} is a multi-path LazyFS operation"); let from_rgx = from_rgx.into(); validate_command_argument("crash", "from_rgx", &from_rgx)?; Ok(Self { timing, op, from_rgx: Some(from_rgx), to_rgx: None, }) } pub fn multi_path( timing: Timing, op: CrashOp, from_rgx: Option>, to_rgx: Option>, ) -> Result { assert!( op.is_multi_path(), "{op} is not a multi-path LazyFS operation" ); let from_rgx = from_rgx.map(Into::into); let to_rgx = to_rgx.map(Into::into); if from_rgx.is_none() && to_rgx.is_none() { return Err(LazyFsCommandError::MissingCrashPathRegex); } if let Some(from_rgx) = &from_rgx { validate_command_argument("crash", "from_rgx", from_rgx)?; } if let Some(to_rgx) = &to_rgx { validate_command_argument("crash", "to_rgx", to_rgx)?; } Ok(Self { timing, op, from_rgx, to_rgx, }) } fn render(&self) -> String { let mut command = format!("lazyfs::crash::timing={}::op={}", self.timing, self.op); if let Some(from_rgx) = &self.from_rgx { command.push_str("::from_rgx="); command.push_str(from_rgx); } if let Some(to_rgx) = &self.to_rgx { command.push_str("::to_rgx="); command.push_str(to_rgx); } command } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum TornOpSplit { Parts(usize), PartsBytes(Vec), } #[derive(Debug, Clone, PartialEq, Eq)] enum TornOpTarget { File(String), FileRegex(String), } impl TornOpTarget { fn render(&self) -> String { match self { Self::File(file) => format!("file={file}"), Self::FileRegex(file_rgx) => format!("file_rgx={file_rgx}"), } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct TornOpCommand { target: TornOpTarget, split: TornOpSplit, persist: Vec, } impl TornOpCommand { pub fn new( file: impl AsRef, split: TornOpSplit, persist: Vec, ) -> Result { validate_torn_op(&split, &persist)?; let file = file.as_ref().to_string_lossy().into_owned(); validate_command_argument("torn-op", "file", &file)?; Ok(Self { target: TornOpTarget::File(file), split, persist, }) } pub fn new_file_regex( file_rgx: impl Into, split: TornOpSplit, persist: Vec, ) -> Result { let file_rgx = file_rgx.into(); validate_torn_op(&split, &persist)?; validate_command_argument("torn-op", "file_rgx", &file_rgx)?; Ok(Self { target: TornOpTarget::FileRegex(file_rgx), split, persist, }) } fn render(&self) -> String { let mut command = format!("lazyfs::torn-op::{}", self.target.render()); command.push_str("::persist="); command.push_str(&render_list(&self.persist)); match &self.split { TornOpSplit::Parts(parts) => { command.push_str("::parts="); command.push_str(&parts.to_string()); } TornOpSplit::PartsBytes(parts_bytes) => { command.push_str("::parts_bytes="); command.push_str(&render_list(parts_bytes)); } } command } } fn validate_torn_op(split: &TornOpSplit, persist: &[usize]) -> Result<(), LazyFsCommandError> { validate_persist("torn-op", persist)?; let max_part_index = match split { TornOpSplit::Parts(0) => return Err(LazyFsCommandError::ZeroTornOpParts), TornOpSplit::Parts(parts) => *parts, TornOpSplit::PartsBytes(parts_bytes) if parts_bytes.is_empty() => { return Err(LazyFsCommandError::EmptyTornOpPartBytes); } TornOpSplit::PartsBytes(parts_bytes) if parts_bytes.contains(&0) => { return Err(LazyFsCommandError::ZeroTornOpPartBytes); } TornOpSplit::PartsBytes(parts_bytes) => parts_bytes.len(), }; if let Some(index) = persist .iter() .copied() .find(|index| *index > max_part_index) { return Err(LazyFsCommandError::PersistIndexOutOfRange { command: "torn-op", index, max: max_part_index, }); } Ok(()) } #[derive(Debug, Clone, PartialEq, Eq)] pub struct TornSeqCommand { file: String, persist: Vec, } impl TornSeqCommand { pub fn write( file: impl AsRef, mut persist: Vec, ) -> Result { validate_persist("torn-seq", &persist)?; let file = file.as_ref().to_string_lossy().into_owned(); validate_command_argument("torn-seq", "file", &file)?; persist.sort_unstable(); Ok(Self { file, persist }) } fn render(&self) -> String { format!( "lazyfs::torn-seq::op=write::file={}::persist={}", self.file, render_list(&self.persist) ) } } fn render_list(values: &[usize]) -> String { values .iter() .map(usize::to_string) .collect::>() .join(",") }