1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// 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 std::error::Error;

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

use crate::director::Director;

/// Results from an event.
#[derive(Debug)]
pub enum JobResult {
    /// The event was accepted and acted upon.
    Accept,
    /// The event was deferred until a later time for the given reason.
    Defer(String),
    /// The event was rejected for the given reason.
    Reject(String),
    /// The event failed with the given error.
    Fail(Box<dyn Error + Send + 'static>),
    /// The director should be restarted.
    Restart,
    /// The event was the last one which should be processed.
    Done,
}

impl JobResult {
    /// Create an accept result.
    pub fn accept() -> Self {
        Self::Accept
    }

    /// Create a deferral result.
    pub fn defer<M>(msg: M) -> Self
    where
        M: Into<String>,
    {
        Self::Defer(msg.into())
    }

    /// Create a rejecting result.
    pub fn reject<M>(msg: M) -> Self
    where
        M: Into<String>,
    {
        Self::Reject(msg.into())
    }

    /// Create a failure.
    pub fn fail<E>(err: E) -> Self
    where
        E: Into<Box<dyn Error + Send + Sync + 'static>>,
    {
        Self::Fail(err.into())
    }

    /// Create a restart result.
    pub fn restart() -> Self {
        Self::Restart
    }

    /// Create a completion result.
    pub fn done() -> Self {
        Self::Done
    }

    /// Combine two handler results into one.
    pub fn combine(self, other: Self) -> Self {
        match (self, other) {
            // Acceptance defers to the other.
            (Self::Accept, next) | (next, Self::Accept) => next,
            // Completion overrides any other status.
            (Self::Done, _) | (_, Self::Done) => Self::Done,
            // Once completion is handled, restart takes precedence.
            (Self::Restart, _) | (_, Self::Restart) => Self::Restart,
            // Deferring is next.
            (Self::Defer(left), Self::Defer(right)) => Self::Defer(format!("{}\n{}", left, right)),
            (defer @ Self::Defer(_), _) | (_, defer @ Self::Defer(_)) => defer,
            // Failures are handled next.
            (fail @ Self::Fail(_), _) | (_, fail @ Self::Fail(_)) => fail,
            // All we have left are rejections; combine their messages.
            (Self::Reject(left), Self::Reject(right)) => {
                Self::Reject(format!("{}\n{}", left, right))
            },
        }
    }
}

/// An error which can occur when handling a job.
pub type JobError = Box<dyn Error + Send + Sync>;

/// Interface for handling events.
pub trait HandlerCore {
    /// Adds the handler to a director.
    fn add_to_director<'a>(&'a self, director: &mut Director<'a>) -> Result<(), JobError>;
}

/// Interface for handling events asynchronously.
#[async_trait]
pub trait Handler: HandlerCore {
    /// The JSON object is passed in and acted upon.
    async fn handle(
        &self,
        kind: &str,
        object: &Value,
        retry_count: usize,
    ) -> Result<JobResult, JobError>;
}