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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use crate::decision::Decision;
use crate::handler::tree::GraphResponse;
use crate::loader::closure::ClosureLoader;
use crate::loader::noop::NoopLoader;
use crate::loader::{DecisionLoader, LoaderResponse, LoaderResult};
use crate::model::decision::DecisionContent;

use serde_json::Value;
use std::future::Future;

use std::sync::Arc;

pub struct DecisionEngine<T>
where
    T: DecisionLoader,
{
    loader: Arc<T>,
}

#[derive(Debug, Default)]
pub struct EvaluationOptions {
    pub trace: Option<bool>,
    pub max_depth: Option<u8>,
}

impl Default for DecisionEngine<NoopLoader> {
    fn default() -> Self {
        Self {
            loader: Arc::new(NoopLoader::default()),
        }
    }
}

impl<F, O> DecisionEngine<ClosureLoader<F>>
where
    F: Fn(&str) -> O + Sync + Send,
    O: Future<Output = LoaderResponse> + Send,
{
    pub fn async_loader(loader: F) -> Self {
        Self {
            loader: Arc::new(ClosureLoader::new(loader)),
        }
    }
}

impl<T: DecisionLoader> DecisionEngine<T> {
    pub fn new<L>(loader: L) -> Self
    where
        L: Into<Arc<T>>,
    {
        Self {
            loader: loader.into(),
        }
    }

    pub fn new_arc(loader: Arc<T>) -> Self {
        Self { loader }
    }

    pub async fn evaluate<K>(&self, key: K, context: &Value) -> Result<GraphResponse, anyhow::Error>
    where
        K: AsRef<str>,
    {
        self.evaluate_with_opts(key, context, Default::default())
            .await
    }

    pub async fn evaluate_with_opts<K>(
        &self,
        key: K,
        context: &Value,
        options: EvaluationOptions,
    ) -> Result<GraphResponse, anyhow::Error>
    where
        K: AsRef<str>,
    {
        let content = self.loader.load(key.as_ref()).await?;
        let decision = self.create_decision(content);
        decision.evaluate_with_opts(context, options).await
    }

    pub async fn simulate(
        &self,
        content: DecisionContent,
        context: &Value,
    ) -> Result<GraphResponse, anyhow::Error> {
        self.simulate_with_opts(content, context, Default::default())
            .await
    }

    pub async fn simulate_with_opts(
        &self,
        content: DecisionContent,
        context: &Value,
        options: EvaluationOptions,
    ) -> Result<GraphResponse, anyhow::Error> {
        let decision = self.create_decision(Arc::new(content));
        decision.evaluate_with_opts(context, options).await
    }

    pub fn create_decision(&self, content: Arc<DecisionContent>) -> Decision<T> {
        Decision::from(content).with_loader(self.loader.clone())
    }

    pub async fn get_decision(&self, key: &str) -> LoaderResult<Decision<T>> {
        let content = self.loader.load(key).await?;
        Ok(self.create_decision(content))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::loader::filesystem::{FilesystemLoader, FilesystemLoaderOptions};
    use crate::loader::memory::MemoryLoader;
    use crate::model::decision::DecisionContent;
    use serde_json::json;
    use std::path::Path;

    #[test]
    fn it_supports_memory_loader() {
        let mem_loader = MemoryLoader::default();

        mem_loader.add(
            "table",
            serde_json::from_str::<DecisionContent>(include_str!("../../../test-data/table.json"))
                .unwrap(),
        );

        mem_loader.add(
            "function",
            serde_json::from_str::<DecisionContent>(include_str!(
                "../../../test-data/function.json"
            ))
            .unwrap(),
        );

        let graph = DecisionEngine::new(mem_loader);
        let res1 = tokio_test::block_on(graph.evaluate("table", &json!({ "input": 12 })));
        let res2 = tokio_test::block_on(graph.evaluate("aaa", &json!({ "input": 12 })));

        assert_eq!(res1.unwrap().result, json!({"output": 10}));
        assert!(res2.is_err());
    }

    #[test]
    fn it_supports_filesystem_loader() {
        let cargo_root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let test_data_root = cargo_root.join("../../").join("test-data");
        let fs_loader = FilesystemLoader::new(FilesystemLoaderOptions {
            keep_in_memory: true,
            root: test_data_root.to_str().unwrap(),
        });

        let graph = DecisionEngine::new(fs_loader);
        let res1 = tokio_test::block_on(graph.evaluate("table.json", &json!({ "input": 12 })));
        let res2 = tokio_test::block_on(graph.evaluate("aaa", &json!({ "input": 12 })));

        assert_eq!(res1.unwrap().result, json!({"output": 10}));
        assert!(res2.is_err());
    }

    #[test]
    fn it_supports_closure_loader() {
        let graph = DecisionEngine::async_loader(|_| async {
            let content = serde_json::from_str::<DecisionContent>(include_str!(
                "../../../test-data/table.json"
            ))
            .unwrap();

            Ok(Arc::new(content))
        });

        let res1 = tokio_test::block_on(graph.evaluate("sample", &json!({ "input": 12 })));
        let res2 = tokio_test::block_on(graph.evaluate("1", &json!({ "input": 4 })));

        assert_eq!(res1.unwrap().result, json!({"output": 10}));
        assert_eq!(res2.unwrap().result, json!({"output": 0}))
    }
}