use std::{
fmt,
sync::{Arc, Weak},
time::Duration,
};
use once_cell::sync::OnceCell;
use tokio::{
process::Command as TokioCommand,
sync::{Mutex, OwnedMutexGuard},
};
use crate::{command::Command, event::Event, filter::Filterer, handler::HandlerLock};
use super::Outcome;
#[derive(Clone)]
#[non_exhaustive]
pub struct WorkingData {
pub throttle: Duration,
pub action_handler: HandlerLock<Action>,
pub pre_spawn_handler: HandlerLock<PreSpawn>,
pub post_spawn_handler: HandlerLock<PostSpawn>,
pub commands: Vec<Command>,
pub grouped: bool,
pub filterer: Arc<dyn Filterer>,
}
impl fmt::Debug for WorkingData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WorkingData")
.field("throttle", &self.throttle)
.field("commands", &self.commands)
.field("grouped", &self.grouped)
.field("filterer", &self.filterer)
.finish_non_exhaustive()
}
}
impl Default for WorkingData {
fn default() -> Self {
Self {
throttle: Duration::from_millis(50),
action_handler: Default::default(),
pre_spawn_handler: Default::default(),
post_spawn_handler: Default::default(),
commands: Vec::new(),
grouped: true,
filterer: Arc::new(()),
}
}
}
#[derive(Debug)]
pub struct Action {
pub events: Arc<[Event]>,
pub(super) outcome: Arc<OnceCell<Outcome>>,
}
impl Action {
pub(super) fn new(events: Arc<[Event]>) -> Self {
Self {
events,
outcome: Default::default(),
}
}
pub fn outcome(self, outcome: Outcome) {
self.outcome.set(outcome).ok();
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct PreSpawn {
pub command: Command,
pub events: Arc<[Event]>,
to_spawn_w: Weak<Mutex<TokioCommand>>,
}
impl PreSpawn {
pub(crate) fn new(
command: Command,
to_spawn: TokioCommand,
events: Arc<[Event]>,
) -> (Self, Arc<Mutex<TokioCommand>>) {
let arc = Arc::new(Mutex::new(to_spawn));
(
Self {
command,
events,
to_spawn_w: Arc::downgrade(&arc),
},
arc.clone(),
)
}
pub async fn command(&self) -> Option<OwnedMutexGuard<TokioCommand>> {
if let Some(arc) = self.to_spawn_w.upgrade() {
Some(arc.lock_owned().await)
} else {
None
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct PostSpawn {
pub command: Command,
pub events: Arc<[Event]>,
pub id: u32,
pub grouped: bool,
}