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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
use crate::{
    data::Data,
    model::{
        algorithms::global_plugins::GlobalPlugins,
        graph::{
            graph::GqlGraph, graphs::GqlGraphs, mutable_graph::GqlMutableGraph,
            vectorised_graph::GqlVectorisedGraph,
        },
    },
    url_encode::{url_decode_graph, url_encode_graph},
};
use async_graphql::Context;
use chrono::Utc;
use dynamic_graphql::{
    App, Enum, Mutation, MutationFields, MutationRoot, ResolvedObject, ResolvedObjectFields,
    Result, Upload,
};
use itertools::Itertools;
#[cfg(feature = "storage")]
use raphtory::db::api::{storage::graph::storage_ops::GraphStorage, view::internal::CoreGraphOps};
use raphtory::{
    core::{utils::errors::GraphError, Prop},
    db::api::view::MaterializedGraph,
    prelude::*,
};
use raphtory_api::core::storage::arc_str::ArcStr;
use std::{
    error::Error,
    fmt::{Display, Formatter},
    fs,
    fs::File,
    io::copy,
    path::Path,
    sync::Arc,
};

pub mod algorithms;
pub(crate) mod graph;
pub(crate) mod schema;

#[derive(Debug)]
pub struct MissingGraph;

impl Display for MissingGraph {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "Graph does not exist")
    }
}

impl Error for MissingGraph {}

#[derive(thiserror::Error, Debug)]
pub enum GqlGraphError {
    #[error("Disk Graph is immutable")]
    ImmutableDiskGraph,
    #[error("Graph does exists at path {0}")]
    GraphDoesNotExists(String),
    #[error("Failed to load graph")]
    FailedToLoadGraph,
    #[error("Invalid namespace: {0}")]
    InvalidNamespace(String),
    #[error("Failed to create dir {0}")]
    FailedToCreateDir(String),
}

#[derive(Enum)]
pub enum GqlGraphType {
    Persistent,
    Event,
}

#[derive(ResolvedObject)]
#[graphql(root)]
pub(crate) struct QueryRoot;

#[ResolvedObjectFields]
impl QueryRoot {
    async fn hello() -> &'static str {
        "Hello world from raphtory-graphql"
    }

    /// Returns a graph
    async fn graph<'a>(ctx: &Context<'a>, path: String) -> Result<GqlGraph> {
        let path = Path::new(&path);
        let data = ctx.data_unchecked::<Data>();
        Ok(data
            .get_graph(path)
            .map(|g| GqlGraph::new(path.to_path_buf(), g))?)
    }

    async fn update_graph<'a>(ctx: &Context<'a>, path: String) -> Result<GqlMutableGraph> {
        let data = ctx.data_unchecked::<Data>();
        let graph = data
            .get_graph(path.as_ref())
            .map(|g| GqlMutableGraph::new(path, g))?;
        Ok(graph)
    }

    async fn vectorised_graph<'a>(ctx: &Context<'a>, path: String) -> Option<GqlVectorisedGraph> {
        let data = ctx.data_unchecked::<Data>();
        let g = data
            .global_plugins
            .vectorised_graphs
            .read()
            .get(&path)
            .cloned()?;
        Some(g.into())
    }

    async fn graphs<'a>(ctx: &Context<'a>) -> Result<GqlGraphs> {
        let data = ctx.data_unchecked::<Data>();
        let paths = data.get_graph_names_paths()?;
        Ok(GqlGraphs::new(paths))
    }

    async fn plugins<'a>(ctx: &Context<'a>) -> GlobalPlugins {
        let data = ctx.data_unchecked::<Data>();
        data.global_plugins.clone()
    }

    async fn receive_graph<'a>(ctx: &Context<'a>, path: String) -> Result<String, Arc<GraphError>> {
        let path = path.as_ref();
        let data = ctx.data_unchecked::<Data>();
        let g = data.get_graph(path)?.graph.clone();
        let res = url_encode_graph(g)?;
        Ok(res)
    }
}

#[derive(MutationRoot)]
pub(crate) struct MutRoot;

#[derive(Mutation)]
pub(crate) struct Mut(MutRoot);

#[MutationFields]
impl Mut {
    // If namespace is not provided, it will be set to the current working directory.
    async fn delete_graph<'a>(ctx: &Context<'a>, path: String) -> Result<bool> {
        let path = Path::new(&path);
        let data = ctx.data_unchecked::<Data>();

        let full_path = data.construct_graph_full_path(path)?;
        if !full_path.exists() {
            return Err(GraphError::GraphNotFound(path.to_path_buf()).into());
        }

        delete_graph(&full_path)?;
        data.graphs.remove(&path.to_path_buf());
        Ok(true)
    }

    async fn new_graph<'a>(
        ctx: &Context<'a>,
        path: String,
        graph_type: GqlGraphType,
    ) -> Result<bool> {
        let data = ctx.data_unchecked::<Data>();
        data.new_graph(path.as_ref(), graph_type)?;
        Ok(true)
    }

    // If namespace is not provided, it will be set to the current working directory.
    // This applies to both the graph namespace and new graph namespace.
    async fn move_graph<'a>(ctx: &Context<'a>, path: String, new_path: String) -> Result<bool> {
        let path = Path::new(&path);
        let new_path = Path::new(&new_path);
        let data = ctx.data_unchecked::<Data>();

        let full_path = data.construct_graph_full_path(path)?;
        if !full_path.exists() {
            return Err(GraphError::GraphNotFound(path.to_path_buf()).into());
        }
        let new_full_path = data.construct_graph_full_path(new_path)?;
        if new_full_path.exists() {
            return Err(GraphError::GraphNameAlreadyExists(new_path.to_path_buf()).into());
        }

        let graph = data.get_graph(&path)?;

        #[cfg(feature = "storage")]
        if let GraphStorage::Disk(_) = graph.core_graph() {
            return Err(GqlGraphError::ImmutableDiskGraph.into());
        }

        if new_full_path.ne(&full_path) {
            let timestamp: i64 = Utc::now().timestamp();

            graph.update_constant_properties([("lastUpdated", Prop::I64(timestamp * 1000))])?;
            graph.update_constant_properties([("lastOpened", Prop::I64(timestamp * 1000))])?;
            create_dirs_if_not_present(&new_full_path)?;
            graph.graph.encode(&new_full_path)?;

            delete_graph(&full_path)?;
            data.graphs.remove(&path.to_path_buf());
        }

        Ok(true)
    }

    // If namespace is not provided, it will be set to the current working directory.
    // This applies to both the graph namespace and new graph namespace.
    async fn copy_graph<'a>(ctx: &Context<'a>, path: String, new_path: String) -> Result<bool> {
        let path = Path::new(&path);
        let new_path = Path::new(&new_path);
        let data = ctx.data_unchecked::<Data>();

        let full_path = data.construct_graph_full_path(path)?;
        if !full_path.exists() {
            return Err(GraphError::GraphNotFound(path.to_path_buf()).into());
        }
        let new_full_path = data.construct_graph_full_path(new_path)?;
        if new_full_path.exists() {
            return Err(GraphError::GraphNameAlreadyExists(new_path.to_path_buf()).into());
        }

        let graph = data.get_graph(path)?;

        #[cfg(feature = "storage")]
        if let GraphStorage::Disk(_) = graph.core_graph() {
            return Err(GqlGraphError::ImmutableDiskGraph.into());
        }

        if new_full_path.ne(&full_path) {
            let timestamp: i64 = Utc::now().timestamp();
            let new_graph = graph.materialize()?;
            new_graph.update_constant_properties([("lastOpened", Prop::I64(timestamp * 1000))])?;
            create_dirs_if_not_present(&new_full_path)?;
            new_graph.encode(&new_full_path)?;
        }

        Ok(true)
    }

    async fn update_graph_last_opened<'a>(ctx: &Context<'a>, path: String) -> Result<bool> {
        let path = Path::new(&path);
        let data = ctx.data_unchecked::<Data>();
        let graph = data.get_graph(path)?;

        if graph.graph.storage().is_immutable() {
            return Err(GqlGraphError::ImmutableDiskGraph.into());
        }

        let dt = Utc::now();
        let timestamp: i64 = dt.timestamp();

        graph.update_constant_properties([("lastOpened", Prop::I64(timestamp * 1000))])?;

        graph.write_updates()?;

        Ok(true)
    }

    async fn create_graph<'a>(
        ctx: &Context<'a>,
        parent_graph_path: String,
        new_graph_path: String,
        props: String,
        is_archive: u8,
        graph_nodes: Vec<String>,
    ) -> Result<bool> {
        let parent_graph_path = Path::new(&parent_graph_path);
        let new_graph_path = Path::new(&new_graph_path);
        let data = ctx.data_unchecked::<Data>();

        let parent_graph_full_path = data.construct_graph_full_path(parent_graph_path)?;
        if !parent_graph_full_path.exists() {
            return Err(GraphError::GraphNotFound(parent_graph_path.to_path_buf()).into());
        }
        let new_graph_full_path = data.construct_graph_full_path(new_graph_path)?;
        if new_graph_full_path.exists() {
            return Err(GraphError::GraphNameAlreadyExists(new_graph_path.to_path_buf()).into());
        }

        let timestamp: i64 = Utc::now().timestamp();
        let node_ids = graph_nodes.iter().map(|key| key.as_str()).collect_vec();

        // Creating a new graph (owner is user) from UI
        // Graph is created from the parent graph. This means the new graph retains the character of the parent graph i.e.,
        // the new graph is an event or persistent graph depending on if the parent graph is event or persistent graph, respectively.
        let parent_graph = data.get_graph(&parent_graph_path.to_path_buf())?;
        let new_subgraph = parent_graph.subgraph(node_ids.clone()).materialize()?;

        new_subgraph.update_constant_properties([("creationTime", Prop::I64(timestamp * 1000))])?;
        new_subgraph.update_constant_properties([("lastUpdated", Prop::I64(timestamp * 1000))])?;
        new_subgraph.update_constant_properties([("lastOpened", Prop::I64(timestamp * 1000))])?;
        new_subgraph.update_constant_properties([("uiProps", Prop::Str(props.into()))])?;
        new_subgraph.update_constant_properties([("isArchive", Prop::U8(is_archive))])?;

        create_dirs_if_not_present(&new_graph_full_path)?;
        new_subgraph.cache(new_graph_full_path)?;

        data.graphs
            .insert(new_graph_path.to_path_buf(), new_subgraph.into());

        Ok(true)
    }

    async fn update_graph<'a>(
        ctx: &Context<'a>,
        parent_graph_path: String,
        graph_path: String,
        new_graph_path: String,
        props: String,
        is_archive: u8,
        graph_nodes: Vec<String>,
    ) -> Result<bool> {
        let parent_graph_path = Path::new(&parent_graph_path);
        let graph_path = Path::new(&graph_path);
        let new_graph_path = Path::new(&new_graph_path);
        let data = ctx.data_unchecked::<Data>();

        let parent_graph_full_path = data.construct_graph_full_path(parent_graph_path)?;
        if !parent_graph_full_path.exists() {
            return Err(GraphError::GraphNotFound(parent_graph_path.to_path_buf()).into());
        }

        // Saving an existing graph
        let graph_full_path = data.construct_graph_full_path(graph_path)?;
        if !graph_full_path.exists() {
            return Err(GraphError::GraphNotFound(graph_path.to_path_buf()).into());
        }

        let new_graph_full_path = data.construct_graph_full_path(new_graph_path)?;
        if graph_path != new_graph_path {
            // Save as
            if new_graph_full_path.exists() {
                return Err(
                    GraphError::GraphNameAlreadyExists(new_graph_path.to_path_buf()).into(),
                );
            }
        }

        let current_graph = data.get_graph(graph_path)?;
        #[cfg(feature = "storage")]
        if current_graph.graph.storage().is_immutable() {
            return Err(GqlGraphError::ImmutableDiskGraph.into());
        }

        let timestamp: i64 = Utc::now().timestamp();
        let node_ids = graph_nodes.iter().map(|key| key.as_str()).collect_vec();

        // Creating a new graph from the current graph instead of the parent graph preserves the character of the new graph
        // i.e., the new graph is an event or persistent graph depending on if the current graph is event or persistent graph, respectively.
        let new_subgraph = current_graph.subgraph(node_ids.clone()).materialize()?;

        let parent_graph = data.get_graph(parent_graph_path)?;
        let new_node_ids = node_ids
            .iter()
            .filter(|x| current_graph.graph.node(x).is_none())
            .collect_vec();
        let parent_subgraph = parent_graph.subgraph(new_node_ids);

        let nodes = parent_subgraph.nodes();
        new_subgraph.import_nodes(nodes, true)?;
        let edges = parent_subgraph.edges();
        new_subgraph.import_edges(edges, true)?;

        if graph_path == new_graph_path {
            // Save
            let static_props: Vec<(ArcStr, Prop)> = current_graph
                .properties()
                .into_iter()
                .filter(|(a, _)| a != "name" && a != "lastUpdated" && a != "uiProps")
                .collect_vec();
            new_subgraph.update_constant_properties(static_props)?;
        } else {
            // Save as
            let static_props: Vec<(ArcStr, Prop)> = current_graph
                .properties()
                .into_iter()
                .filter(|(a, _)| a != "name" && a != "creationTime" && a != "uiProps")
                .collect_vec();
            new_subgraph.update_constant_properties(static_props)?;
            new_subgraph
                .update_constant_properties([("creationTime", Prop::I64(timestamp * 1000))])?;
        }

        new_subgraph.update_constant_properties([("lastUpdated", Prop::I64(timestamp * 1000))])?;
        new_subgraph.update_constant_properties([("lastOpened", Prop::I64(timestamp * 1000))])?;
        new_subgraph.update_constant_properties([("uiProps", Prop::Str(props.into()))])?;
        new_subgraph.update_constant_properties([("isArchive", Prop::U8(is_archive))])?;

        new_subgraph.cache(new_graph_full_path)?;

        data.graphs.remove(&graph_path.to_path_buf());
        data.graphs
            .insert(new_graph_path.to_path_buf(), new_subgraph.into());

        Ok(true)
    }

    // /// Load graph from path
    // ///
    // /// Returns::
    // ///   list of names for newly added graphs
    // async fn load_graph_from_path<'a>(
    //     ctx: &Context<'a>,
    //     path_on_server: String,
    //     namespace: &Option<String>,
    //     overwrite: bool,
    // ) -> Result<String> {
    //     let path_on_server = Path::new(&path_on_server);
    //     let data = ctx.data_unchecked::<Data>();
    //     let new_path = load_graph_from_path(&data.work_dir, path_on_server, namespace, overwrite)?;
    //     data.graphs.remove(&new_path.to_path_buf());
    //     Ok(new_path.display().to_string())
    // }

    /// Use GQL multipart upload to send new graphs to server
    ///
    /// Returns::
    ///    name of the new graph
    async fn upload_graph<'a>(
        ctx: &Context<'a>,
        path: String,
        graph: Upload,
        overwrite: bool,
    ) -> Result<String> {
        let path = Path::new(&path);
        let data = ctx.data_unchecked::<Data>();

        let full_path = data.construct_graph_full_path(path)?;
        if full_path.exists() && !overwrite {
            return Err(GraphError::GraphNameAlreadyExists(path.to_path_buf()).into());
        }

        let mut in_file = graph.value(ctx)?.content;
        create_dirs_if_not_present(&full_path)?;
        let mut out_file = File::create(&full_path)?;
        copy(&mut in_file, &mut out_file)?;
        let g = MaterializedGraph::load_cached(&full_path)?;
        data.graphs.insert(path.to_path_buf(), g.into());
        Ok(path.display().to_string())
    }

    /// Send graph bincode as base64 encoded string
    ///
    /// Returns::
    ///    path of the new graph
    async fn send_graph<'a>(
        ctx: &Context<'a>,
        path: String,
        graph: String,
        overwrite: bool,
    ) -> Result<String> {
        let path = Path::new(&path);
        let data = ctx.data_unchecked::<Data>();
        let full_path = data.construct_graph_full_path(path)?;
        if full_path.exists() && !overwrite {
            return Err(GraphError::GraphNameAlreadyExists(path.to_path_buf()).into());
        }
        let g: MaterializedGraph = url_decode_graph(graph)?;
        create_dirs_if_not_present(&full_path)?;
        g.cache(&full_path)?;
        data.graphs.insert(path.to_path_buf(), g.into());
        Ok(path.display().to_string())
    }

    async fn archive_graph<'a>(ctx: &Context<'a>, path: String, is_archive: u8) -> Result<bool> {
        let path = Path::new(&path);
        let data = ctx.data_unchecked::<Data>();
        let graph = data.get_graph(path)?;

        if graph.graph.storage().is_immutable() {
            return Err(GqlGraphError::ImmutableDiskGraph.into());
        }

        graph.update_constant_properties([("isArchive", Prop::U8(is_archive))])?;
        graph.write_updates()?;
        Ok(true)
    }
}

pub(crate) fn create_dirs_if_not_present(path: &Path) -> Result<(), GraphError> {
    if let Some(parent) = path.parent() {
        if !parent.exists() {
            fs::create_dir_all(parent)?;
        }
    }
    Ok(())
}

#[derive(App)]
pub struct App(QueryRoot, MutRoot, Mut);

fn delete_graph(path: &Path) -> Result<()> {
    if path.is_file() {
        fs::remove_file(path)?;
    } else if path.is_dir() {
        fs::remove_dir_all(path)?;
    } else {
        return Err(GqlGraphError::GraphDoesNotExists(path.display().to_string()).into());
    }
    Ok(())
}