Call action handler on action
This commit is contained in:
parent
2812a723ff
commit
2a0661b122
|
@ -1,28 +1,53 @@
|
||||||
//! Processor responsible for receiving events, filtering them, and scheduling actions in response.
|
//! Processor responsible for receiving events, filtering them, and scheduling actions in response.
|
||||||
|
|
||||||
use std::time::{Duration, Instant};
|
use std::{
|
||||||
|
fmt,
|
||||||
|
sync::Arc,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
use tokio::{sync::{mpsc, watch}, time::timeout};
|
use atomic_take::AtomicTake;
|
||||||
|
use tokio::{
|
||||||
|
sync::{mpsc, watch},
|
||||||
|
time::timeout,
|
||||||
|
};
|
||||||
|
use tracing::{debug, trace};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
error::{CriticalError, RuntimeError},
|
error::{CriticalError, RuntimeError},
|
||||||
event::Event,
|
event::Event,
|
||||||
|
handler::{rte, Handler},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub struct WorkingData {
|
pub struct WorkingData {
|
||||||
pub throttle: Duration,
|
pub throttle: Duration,
|
||||||
|
pub action_handler: Arc<AtomicTake<Box<dyn Handler<Action> + Send>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for WorkingData {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("WorkingData")
|
||||||
|
.field("throttle", &self.throttle)
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for WorkingData {
|
impl Default for WorkingData {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
throttle: Duration::from_millis(100),
|
throttle: Duration::from_millis(100),
|
||||||
|
action_handler: Arc::new(AtomicTake::new(Box::new(()) as _)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Action {
|
||||||
|
pub events: Vec<Event>,
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn worker(
|
pub async fn worker(
|
||||||
working: watch::Receiver<WorkingData>,
|
working: watch::Receiver<WorkingData>,
|
||||||
errors: mpsc::Sender<RuntimeError>,
|
errors: mpsc::Sender<RuntimeError>,
|
||||||
|
@ -30,11 +55,13 @@ pub async fn worker(
|
||||||
) -> Result<(), CriticalError> {
|
) -> Result<(), CriticalError> {
|
||||||
let mut last = Instant::now();
|
let mut last = Instant::now();
|
||||||
let mut set = Vec::new();
|
let mut set = Vec::new();
|
||||||
|
let mut handler =
|
||||||
|
{ working.borrow().action_handler.take() }.ok_or(CriticalError::MissingHandler)?;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let maxtime = working.borrow().throttle;
|
let maxtime = working.borrow().throttle;
|
||||||
match timeout(maxtime, events.recv()).await {
|
match timeout(maxtime, events.recv()).await {
|
||||||
Err(_timeout) => {},
|
Err(_timeout) => {}
|
||||||
Ok(None) => break,
|
Ok(None) => break,
|
||||||
Ok(Some(event)) => {
|
Ok(Some(event)) => {
|
||||||
set.push(event);
|
set.push(event);
|
||||||
|
@ -46,7 +73,21 @@ pub async fn worker(
|
||||||
}
|
}
|
||||||
|
|
||||||
last = Instant::now();
|
last = Instant::now();
|
||||||
set.drain(..); // TODO: do action with the set
|
|
||||||
|
let action = Action {
|
||||||
|
events: set.drain(..).collect(),
|
||||||
|
};
|
||||||
|
debug!(?action, "action constructed");
|
||||||
|
|
||||||
|
if let Some(h) = working.borrow().action_handler.take() {
|
||||||
|
trace!("action handler updated");
|
||||||
|
handler = h;
|
||||||
|
}
|
||||||
|
|
||||||
|
let err = handler.handle(action).map_err(|e| rte("action worker", e));
|
||||||
|
if let Err(err) = err {
|
||||||
|
errors.send(err).await?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,6 +33,13 @@ pub enum CriticalError {
|
||||||
#[error("main task join: {0}")]
|
#[error("main task join: {0}")]
|
||||||
#[diagnostic(code(watchexec::critical::main_task_join))]
|
#[diagnostic(code(watchexec::critical::main_task_join))]
|
||||||
MainTaskJoin(#[source] JoinError),
|
MainTaskJoin(#[source] JoinError),
|
||||||
|
|
||||||
|
/// Error received when a handler is missing on initialisation.
|
||||||
|
///
|
||||||
|
/// This is a critical bug and unlikely to be recoverable in any way.
|
||||||
|
#[error("internal: missing handler on init")]
|
||||||
|
#[diagnostic(code(watchexec::critical::internal::missing_handler))]
|
||||||
|
MissingHandler,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Errors which _may_ be recoverable, transient, or only affect a part of the operation, and should
|
/// Errors which _may_ be recoverable, transient, or only affect a part of the operation, and should
|
||||||
|
@ -112,15 +119,6 @@ pub enum RuntimeError {
|
||||||
Handler { ctx: &'static str, err: String },
|
Handler { ctx: &'static str, err: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RuntimeError {
|
|
||||||
pub(crate) fn from_handler(ctx: &'static str, err: impl std::error::Error) -> Self {
|
|
||||||
Self::Handler {
|
|
||||||
ctx,
|
|
||||||
err: err.to_string(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Errors occurring from reconfigs.
|
/// Errors occurring from reconfigs.
|
||||||
#[derive(Debug, Diagnostic, Error)]
|
#[derive(Debug, Diagnostic, Error)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
|
|
|
@ -88,12 +88,21 @@ use std::{error::Error, future::Future, io::Write, marker::PhantomData};
|
||||||
|
|
||||||
use tokio::runtime::Handle;
|
use tokio::runtime::Handle;
|
||||||
|
|
||||||
|
use crate::error::RuntimeError;
|
||||||
|
|
||||||
/// A callable that can be used to hook into watchexec.
|
/// A callable that can be used to hook into watchexec.
|
||||||
pub trait Handler<T> {
|
pub trait Handler<T> {
|
||||||
/// Call the handler with the given data.
|
/// Call the handler with the given data.
|
||||||
fn handle(&mut self, _data: T) -> Result<(), Box<dyn Error>>;
|
fn handle(&mut self, _data: T) -> Result<(), Box<dyn Error>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn rte(ctx: &'static str, err: Box<dyn Error>) -> RuntimeError {
|
||||||
|
RuntimeError::Handler {
|
||||||
|
ctx,
|
||||||
|
err: err.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Wrapper for [`Handler`]s that are non-future [`FnMut`]s.
|
/// Wrapper for [`Handler`]s that are non-future [`FnMut`]s.
|
||||||
///
|
///
|
||||||
/// Construct using [`Into::into`]:
|
/// Construct using [`Into::into`]:
|
||||||
|
|
|
@ -19,7 +19,7 @@ use crate::{
|
||||||
config::{InitConfig, RuntimeConfig},
|
config::{InitConfig, RuntimeConfig},
|
||||||
error::{CriticalError, ReconfigError, RuntimeError},
|
error::{CriticalError, ReconfigError, RuntimeError},
|
||||||
fs,
|
fs,
|
||||||
handler::Handler,
|
handler::{rte, Handler},
|
||||||
signal,
|
signal,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -130,10 +130,7 @@ async fn error_hook(
|
||||||
if let Err(err) = handler.handle(err) {
|
if let Err(err) = handler.handle(err) {
|
||||||
error!(%err, "error while handling error");
|
error!(%err, "error while handling error");
|
||||||
handler
|
handler
|
||||||
.handle(RuntimeError::Handler {
|
.handle(rte("error hook", err))
|
||||||
ctx: "error hook",
|
|
||||||
err: err.to_string(),
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|err| {
|
.unwrap_or_else(|err| {
|
||||||
error!(%err, "error while handling error of handling error");
|
error!(%err, "error while handling error of handling error");
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in New Issue