json-job-dispatch 3.1.0

Dispatch jobs described by JSON files and sort them according to their status.
Documentation
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use async_trait::async_trait;
use serde_json::Value;

use crate::director::Director;
use crate::handler::{Handler, HandlerCore, JobError, JobResult};

/// A watchdog for the director.
///
/// This handles `watchdog:restart` and `watchdog:exit` job kinds to make restarting and exiting
/// the director easier.
#[derive(Debug, Clone, Copy, Default)]
pub struct DirectorWatchdog;

impl HandlerCore for DirectorWatchdog {
    fn add_to_director<'a>(&'a self, director: &mut Director<'a>) -> Result<(), JobError> {
        director.add_handler("watchdog:restart", self)?;
        director.add_handler("watchdog:exit", self)?;

        Ok(())
    }
}

#[async_trait]
impl Handler for DirectorWatchdog {
    async fn handle(&self, kind: &str, _: &Value, _: usize) -> Result<JobResult, JobError> {
        Ok(match kind {
            "watchdog:restart" => JobResult::Restart,
            "watchdog:exit" => JobResult::Done,
            _ => JobResult::Reject(format!("watchdog received an unhandled {} job", kind)),
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::test;
    use crate::{Director, DirectorWatchdog, HandlerCore};

    #[test]
    fn test_add_watchdog() {
        let tempdir = test::test_workspace_dir();
        let mut director = Director::new(tempdir.path()).unwrap();
        let watchdog = DirectorWatchdog;
        watchdog.add_to_director(&mut director).unwrap();

        assert_eq!(format!("{:?}", director), format!("Director {{ accept: \"{path}/accept\", reject: \"{path}/reject\", fail: \"{path}/fail\", handlers: [\"watchdog:exit\", \"watchdog:restart\"] }}", path=tempdir.path().display()));
    }
}