use std::collections::{HashMap, HashSet, VecDeque};
use std::io;
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use tracing_subscriber::fmt::MakeWriter;
use crate::clipboard::{Clipboard, ClipboardError, RgbaImage};
use crate::clock::Clock;
use crate::config::EnvProvider;
use crate::fs::{BoxRead, BoxWrite, DirEntry, FsError, Metadata, RemoteFs, RemotePath};
use crate::random::RandomSource;
#[derive(Debug, Clone, Copy)]
pub struct FixedClock(pub DateTime<Utc>);
impl FixedClock {
pub fn at(rfc3339: &str) -> Self {
let instant = DateTime::parse_from_rfc3339(rfc3339).expect("valid RFC 3339 timestamp");
Self(instant.with_timezone(&Utc))
}
}
impl Clock for FixedClock {
fn now(&self) -> DateTime<Utc> {
self.0
}
}
#[derive(Debug)]
pub struct ManualClock(Mutex<DateTime<Utc>>);
impl ManualClock {
pub fn at(rfc3339: &str) -> Self {
Self(Mutex::new(FixedClock::at(rfc3339).0))
}
pub fn advance(&self, secs: i64) {
*self.0.lock().expect("clock lock") += chrono::TimeDelta::seconds(secs);
}
}
impl Clock for ManualClock {
fn now(&self) -> DateTime<Utc> {
*self.0.lock().expect("clock lock")
}
}
#[derive(Debug, Clone)]
pub struct SeqRandom {
values: VecDeque<u64>,
}
impl SeqRandom {
pub fn new(values: impl IntoIterator<Item = u64>) -> Self {
Self {
values: values.into_iter().collect(),
}
}
}
impl RandomSource for SeqRandom {
fn next_u64(&mut self) -> u64 {
self.values.pop_front().expect("SeqRandom exhausted")
}
}
#[derive(Debug, Clone, Default)]
pub struct LogBuffer(Arc<Mutex<Vec<u8>>>);
impl LogBuffer {
pub fn contents(&self) -> String {
let bytes = self.0.lock().expect("log buffer lock").clone();
String::from_utf8(bytes).expect("log output is UTF-8")
}
}
impl io::Write for LogBuffer {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0
.lock()
.expect("log buffer lock")
.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl<'a> MakeWriter<'a> for LogBuffer {
type Writer = LogBuffer;
fn make_writer(&'a self) -> Self::Writer {
self.clone()
}
}
#[derive(Debug, Clone)]
pub struct MapEnv {
vars: HashMap<String, String>,
hostname: String,
}
impl Default for MapEnv {
fn default() -> Self {
Self {
vars: HashMap::new(),
hostname: "test-host".to_owned(),
}
}
}
impl MapEnv {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with(mut self, key: &str, value: &str) -> Self {
self.vars.insert(key.to_owned(), value.to_owned());
self
}
#[must_use]
pub fn with_hostname(mut self, hostname: &str) -> Self {
self.hostname = hostname.to_owned();
self
}
}
impl EnvProvider for MapEnv {
fn var(&self, key: &str) -> Option<String> {
self.vars.get(key).cloned()
}
fn hostname(&self) -> String {
self.hostname.clone()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FsOp {
CreateDirAll,
ReadDir,
OpenRead,
OpenWrite,
Rename,
RemoveDirAll,
Stat,
}
#[derive(Debug, Default)]
struct FaultState {
calls: HashMap<FsOp, usize>,
failing: HashSet<(FsOp, usize)>,
}
#[derive(Debug)]
pub struct FaultyFs<F> {
inner: F,
state: Mutex<FaultState>,
}
impl<F> FaultyFs<F> {
pub fn new(inner: F) -> Self {
Self {
inner,
state: Mutex::default(),
}
}
pub fn inner(&self) -> &F {
&self.inner
}
pub fn fail_nth(&self, op: FsOp, nth: usize) {
self.state
.lock()
.expect("fault state lock")
.failing
.insert((op, nth));
}
pub fn fail_next(&self, op: FsOp, times: usize) {
let mut state = self.state.lock().expect("fault state lock");
let done = state.calls.get(&op).copied().unwrap_or(0);
state.failing.extend((1..=times).map(|i| (op, done + i)));
}
pub fn calls(&self, op: FsOp) -> usize {
self.state
.lock()
.expect("fault state lock")
.calls
.get(&op)
.copied()
.unwrap_or(0)
}
fn check(&self, op: FsOp, path: &RemotePath) -> Result<(), FsError> {
let mut state = self.state.lock().expect("fault state lock");
let call = state.calls.entry(op).or_insert(0);
*call += 1;
let key = (op, *call);
if state.failing.remove(&key) {
return Err(FsError::Other {
path: path.to_string(),
message: format!("injected {op:?} failure"),
});
}
Ok(())
}
}
#[async_trait]
impl<F: RemoteFs> RemoteFs for FaultyFs<F> {
async fn create_dir_all(&self, path: &RemotePath) -> Result<(), FsError> {
self.check(FsOp::CreateDirAll, path)?;
self.inner.create_dir_all(path).await
}
async fn read_dir(&self, path: &RemotePath) -> Result<Vec<DirEntry>, FsError> {
self.check(FsOp::ReadDir, path)?;
self.inner.read_dir(path).await
}
async fn open_read(&self, path: &RemotePath) -> Result<BoxRead, FsError> {
self.check(FsOp::OpenRead, path)?;
self.inner.open_read(path).await
}
async fn open_write(&self, path: &RemotePath) -> Result<BoxWrite, FsError> {
self.check(FsOp::OpenWrite, path)?;
self.inner.open_write(path).await
}
async fn rename(&self, from: &RemotePath, to: &RemotePath) -> Result<(), FsError> {
self.check(FsOp::Rename, from)?;
self.inner.rename(from, to).await
}
async fn remove_dir_all(&self, path: &RemotePath) -> Result<(), FsError> {
self.check(FsOp::RemoveDirAll, path)?;
self.inner.remove_dir_all(path).await
}
async fn stat(&self, path: &RemotePath) -> Result<Option<Metadata>, FsError> {
self.check(FsOp::Stat, path)?;
self.inner.stat(path).await
}
}
#[derive(Debug, Default)]
struct MockClipboardState {
reads: VecDeque<Result<Option<String>, ClipboardError>>,
current: Option<String>,
writes: Vec<String>,
fail_writes: bool,
image_reads: VecDeque<Option<RgbaImage>>,
current_image: Option<RgbaImage>,
image_writes: Vec<RgbaImage>,
}
#[derive(Debug, Clone, Default)]
pub struct MockClipboard(Arc<Mutex<MockClipboardState>>);
impl MockClipboard {
pub fn new() -> Self {
Self::default()
}
pub fn with_text(text: &str) -> Self {
let mock = Self::new();
mock.lock().current = Some(text.to_owned());
mock
}
#[must_use]
pub fn with_reads<'a>(self, reads: impl IntoIterator<Item = Option<&'a str>>) -> Self {
self.lock()
.reads
.extend(reads.into_iter().map(|read| Ok(read.map(str::to_owned))));
self
}
pub fn with_image(image: RgbaImage) -> Self {
let mock = Self::new();
mock.lock().current_image = Some(image);
mock
}
#[must_use]
pub fn with_image_reads(self, reads: impl IntoIterator<Item = Option<RgbaImage>>) -> Self {
self.lock().image_reads.extend(reads);
self
}
pub fn image_writes(&self) -> Vec<RgbaImage> {
self.lock().image_writes.clone()
}
pub fn current_image(&self) -> Option<RgbaImage> {
self.lock().current_image.clone()
}
pub fn push_read_error(&self, err: ClipboardError) {
self.lock().reads.push_front(Err(err));
}
pub fn fail_writes(&self, fail: bool) {
self.lock().fail_writes = fail;
}
pub fn writes(&self) -> Vec<String> {
self.lock().writes.clone()
}
pub fn current(&self) -> Option<String> {
self.lock().current.clone()
}
fn lock(&self) -> std::sync::MutexGuard<'_, MockClipboardState> {
self.0.lock().expect("mock clipboard lock")
}
}
impl Clipboard for MockClipboard {
fn read_text(&mut self) -> Result<Option<String>, ClipboardError> {
let mut state = self.lock();
match state.reads.pop_front() {
Some(Ok(text)) => {
if text.is_some() {
state.current.clone_from(&text);
}
Ok(text)
}
Some(Err(err)) => Err(err),
None => Ok(state.current.clone()),
}
}
fn write_text(&mut self, text: &str) -> Result<(), ClipboardError> {
let mut state = self.lock();
if state.fail_writes {
return Err(ClipboardError::Other("injected write failure".to_owned()));
}
state.writes.push(text.to_owned());
state.current = Some(text.to_owned());
state.current_image = None;
Ok(())
}
fn read_image(&mut self) -> Result<Option<RgbaImage>, ClipboardError> {
let mut state = self.lock();
match state.image_reads.pop_front() {
Some(image) => {
if image.is_some() {
state.current_image.clone_from(&image);
}
Ok(image)
}
None => Ok(state.current_image.clone()),
}
}
fn write_image(&mut self, image: &RgbaImage) -> Result<(), ClipboardError> {
let mut state = self.lock();
if state.fail_writes {
return Err(ClipboardError::Other("injected write failure".to_owned()));
}
state.image_writes.push(image.clone());
state.current_image = Some(image.clone());
state.current = None;
Ok(())
}
}