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
use crate::model::algorithms::{
    algorithm::{Algorithm, Pagerank},
    algorithm_entry_point::AlgorithmEntryPoint,
    RegisterFunction,
};
use async_graphql::{dynamic::FieldValue, Context};
use dynamic_graphql::internal::{OutputTypeName, Register, Registry, ResolveOwned, TypeName};
use once_cell::sync::Lazy;
use raphtory::db::api::view::DynamicGraph;
use std::{
    borrow::Cow,
    collections::HashMap,
    sync::{Mutex, MutexGuard},
};

use super::algorithm::ShortestPath;

pub static GRAPH_ALGO_PLUGINS: Lazy<Mutex<HashMap<String, RegisterFunction>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

pub struct GraphAlgorithms {
    pub graph: DynamicGraph,
}

impl From<DynamicGraph> for GraphAlgorithms {
    fn from(graph: DynamicGraph) -> Self {
        Self { graph }
    }
}

impl<'a> AlgorithmEntryPoint<'a> for GraphAlgorithms {
    fn predefined_algos() -> HashMap<&'static str, RegisterFunction> {
        HashMap::from([
            (
                "pagerank",
                Box::new(Pagerank::register_algo) as RegisterFunction,
            ),
            (
                "shortest_path",
                Box::new(ShortestPath::register_algo) as RegisterFunction,
            ),
        ])
    }
    fn lock_plugins() -> MutexGuard<'static, HashMap<String, RegisterFunction>> {
        GRAPH_ALGO_PLUGINS.lock().unwrap()
    }
}

impl Register for GraphAlgorithms {
    fn register(registry: Registry) -> Registry {
        Self::register_algos(registry)
    }
}
impl TypeName for GraphAlgorithms {
    fn get_type_name() -> Cow<'static, str> {
        "GraphAlgorithms".into()
    }
}
impl OutputTypeName for GraphAlgorithms {}
impl<'a> ResolveOwned<'a> for GraphAlgorithms {
    fn resolve_owned(self, _ctx: &Context) -> dynamic_graphql::Result<Option<FieldValue<'a>>> {
        Ok(Some(FieldValue::owned_any(self)))
    }
}