raphtory-graphql 0.17.0

Raphtory GraphQL server
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
use minijinja::{Environment, Value};
use pyo3::{exceptions::PyValueError, prelude::*, pyclass, pymethods};
use raphtory::errors::GraphError;
use raphtory_api::{
    core::{
        entities::{properties::prop::Prop, GID},
        storage::timeindex::EventTime,
        utils::time::IntoTime,
    },
    python::timeindex::PyEventTime,
};
use serde::{ser::SerializeStruct, Serialize, Serializer};
use serde_json::json;
use std::collections::HashMap;

pub mod raphtory_client;
pub mod remote_edge;
pub mod remote_graph;
pub mod remote_node;

/// A temporal update
///
/// Arguments:
///     time (TimeInput): the timestamp for the update
///     properties (PropInput, optional): the properties for the update
#[derive(Clone)]
#[pyclass(name = "RemoteUpdate", module = "raphtory.graphql")]
pub struct PyUpdate {
    time: PyEventTime,
    properties: Option<HashMap<String, Prop>>,
}

impl Serialize for PyUpdate {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut count = 1;
        if self.properties.is_some() {
            count += 1;
        }
        let mut state = serializer.serialize_struct("PyUpdate", count)?;

        let time = &self.time;
        let time = time.clone().into_time();
        state.serialize_field("time", &time)?;
        if let Some(ref properties) = self.properties {
            let properties_list: Vec<serde_json::Value> = properties
                .iter()
                .map(|(key, value)| {
                    json!({
                        "key": key,
                        "value": inner_collection(value),
                    })
                })
                .collect();
            state.serialize_field("properties", &properties_list)?;
        }

        state.end()
    }
}

#[pymethods]
impl PyUpdate {
    #[new]
    #[pyo3(signature = (time, properties=None))]
    pub(crate) fn new(time: EventTime, properties: Option<HashMap<String, Prop>>) -> Self {
        Self {
            time: PyEventTime::new(time),
            properties,
        }
    }
}

/// Node addition update
///
/// Arguments:
///     name (GID): the id of the node
///     node_type (str, optional): the node type
///     metadata (PropInput, optional): the metadata
///     updates (list[RemoteUpdate], optional): the temporal updates
#[derive(Clone)]
#[pyclass(name = "RemoteNodeAddition", module = "raphtory.graphql")]
pub struct PyNodeAddition {
    name: GID,
    node_type: Option<String>,
    metadata: Option<HashMap<String, Prop>>,
    updates: Option<Vec<PyUpdate>>,
}

impl Serialize for PyNodeAddition {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut count = 1;
        if self.node_type.is_some() {
            count += 1;
        }
        if self.metadata.is_some() {
            count += 1;
        }
        if self.updates.is_some() {
            count += 1;
        }
        let mut state = serializer.serialize_struct("PyNodeAddition", count)?;

        state.serialize_field("name", &self.name.to_string())?;

        if let Some(node_type) = &self.node_type {
            state.serialize_field("node_type", node_type)?;
        }

        if let Some(ref metadata) = self.metadata {
            let properties_list: Vec<serde_json::Value> = metadata
                .iter()
                .map(|(key, value)| {
                    json!({
                        "key": key,
                        "value": inner_collection(value),
                    })
                })
                .collect();
            state.serialize_field("metadata", &properties_list)?;
        }
        if let Some(updates) = &self.updates {
            state.serialize_field("updates", updates)?;
        }
        state.end()
    }
}

#[pymethods]
impl PyNodeAddition {
    #[new]
    #[pyo3(signature = (name, node_type=None, metadata=None, updates=None))]
    pub(crate) fn new(
        name: GID,
        node_type: Option<String>,
        metadata: Option<HashMap<String, Prop>>,
        updates: Option<Vec<PyUpdate>>,
    ) -> Self {
        Self {
            name,
            node_type,
            metadata,
            updates,
        }
    }
}

/// An edge update
///
/// Arguments:
///     src (GID): the id of the source node
///     dst (GID): the id of the destination node
///     layer (str, optional): the layer for the update
///     metadata (PropInput, optional): the metadata for the edge
///     updates (list[RemoteUpdate], optional): the temporal updates for the edge
#[derive(Clone)]
#[pyclass(name = "RemoteEdgeAddition", module = "raphtory.graphql")]
pub struct PyEdgeAddition {
    src: GID,
    dst: GID,
    layer: Option<String>,
    metadata: Option<HashMap<String, Prop>>,
    updates: Option<Vec<PyUpdate>>,
}

impl Serialize for PyEdgeAddition {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut count = 2;
        if self.layer.is_some() {
            count += 1;
        }
        if self.metadata.is_some() {
            count += 1;
        }
        if self.updates.is_some() {
            count += 1;
        }
        let mut state = serializer.serialize_struct("PyEdgeAddition", count)?;

        state.serialize_field("src", &self.src.to_string())?;
        state.serialize_field("dst", &self.dst.to_string())?;

        if let Some(layer) = &self.layer {
            state.serialize_field("layer", layer)?;
        }

        if let Some(ref metadata) = self.metadata {
            let properties_list: Vec<serde_json::Value> = metadata
                .iter()
                .map(|(key, value)| {
                    json!({
                        "key": key,
                        "value": inner_collection(value),
                    })
                })
                .collect();
            state.serialize_field("metadata", &properties_list)?;
        }
        if let Some(updates) = &self.updates {
            state.serialize_field("updates", updates)?;
        }
        state.end()
    }
}

#[pymethods]
impl PyEdgeAddition {
    #[new]
    #[pyo3(signature = (src, dst, layer=None, metadata=None, updates=None))]
    pub(crate) fn new(
        src: GID,
        dst: GID,
        layer: Option<String>,
        metadata: Option<HashMap<String, Prop>>,
        updates: Option<Vec<PyUpdate>>,
    ) -> Self {
        Self {
            src,
            dst,
            layer,
            metadata,
            updates,
        }
    }
}

fn inner_collection(value: &Prop) -> String {
    match value {
        Prop::Str(value) => format!("{{ str: \"{}\" }}", value),
        Prop::U8(value) => format!("{{ u64: {} }}", value),
        Prop::U16(value) => format!("{{ u64: {} }}", value),
        Prop::I32(value) => format!("{{ i64: {} }}", value),
        Prop::I64(value) => format!("{{ i64: {} }}", value),
        Prop::U32(value) => format!("{{ u64: {} }}", value),
        Prop::U64(value) => format!("{{ u64: {} }}", value),
        Prop::F32(value) => format!("{{ f64: {} }}", value),
        Prop::F64(value) => format!("{{ f64: {} }}", value),
        Prop::Bool(value) => format!("{{ bool: {} }}", value),
        Prop::List(value) => {
            let vec: Vec<String> = value.iter().map(inner_collection).collect();
            format!("{{ list: [{}] }}", vec.join(", "))
        }
        Prop::Array(value) => {
            let vec: Vec<String> = value.iter_prop().map(|v| inner_collection(&v)).collect();
            format!("{{ list: [{}] }}", vec.join(", "))
        }
        Prop::Map(value) => {
            let properties_array: Vec<String> = value
                .iter()
                .map(|(k, v)| format!("{{ key: \"{}\", value: {} }}", k, inner_collection(v)))
                .collect();
            format!("{{ object: [{}] }}", properties_array.join(", "))
        }
        Prop::DTime(value) => format!("{{ str: \"{}\" }}", value),
        Prop::NDTime(value) => format!("{{ str: \"{}\" }}", value),
        Prop::Decimal(value) => format!("{{ decimal: {} }}", value),
    }
}

fn to_graphql_valid(key: &String, value: &Prop) -> String {
    match value {
        Prop::Str(value) => format!("{{ key: \"{}\", value: {{ str: \"{}\" }} }}", key, value),
        Prop::U8(value) => format!("{{ key: \"{}\", value: {{ u64: {} }} }}", key, value),
        Prop::U16(value) => format!("{{ key: \"{}\", value: {{ u64: {} }} }}", key, value),
        Prop::I32(value) => format!("{{ key: \"{}\", value: {{ i64: {} }} }}", key, value),
        Prop::I64(value) => format!("{{ key: \"{}\", value: {{ i64: {} }} }}", key, value),
        Prop::U32(value) => format!("{{ key: \"{}\", value: {{ u64: {} }} }}", key, value),
        Prop::U64(value) => format!("{{ key: \"{}\", value: {{ u64: {} }} }}", key, value),
        Prop::F32(value) => format!("{{ key: \"{}\", value: {{ f64: {} }} }}", key, value),
        Prop::F64(value) => format!("{{ key: \"{}\", value: {{ f64: {} }} }}", key, value),
        Prop::Bool(value) => format!("{{ key: \"{}\", value: {{ bool: {} }} }}", key, value),
        Prop::List(value) => {
            let vec: Vec<String> = value.iter().map(inner_collection).collect();
            format!(
                "{{ key: \"{}\", value: {{ list: [{}] }} }}",
                key,
                vec.join(", ")
            )
        }
        Prop::Array(value) => {
            let vec: Vec<String> = value.iter_prop().map(|v| inner_collection(&v)).collect();
            format!(
                "{{ key: \"{}\", value: {{ list: [{}] }} }}",
                key,
                vec.join(", ")
            )
        }
        Prop::Map(value) => {
            let properties_array: Vec<String> = value
                .iter()
                .map(|(k, v)| format!("{{ key: \"{}\", value: {} }}", k, inner_collection(v)))
                .collect();
            format!(
                "{{ key: \"{}\", value: {{ object: [{}] }} }}",
                key,
                properties_array.join(", ")
            )
        }
        Prop::DTime(value) => format!("{{ key: \"{}\", value: {{ str: \"{}\" }} }}", key, value),
        Prop::NDTime(value) => format!("{{ key: \"{}\", value: {{ str: \"{}\" }} }}", key, value),
        Prop::Decimal(value) => format!(
            "{{ key: \"{}\", value: {{ decimal: \"{}\" }} }}",
            key, value
        ),
    }
}

pub(crate) fn build_property_string(properties: HashMap<String, Prop>) -> String {
    let properties_array: Vec<String> = properties
        .iter()
        .map(|(k, v)| to_graphql_valid(k, v))
        .collect();

    format!("[{}]", properties_array.join(", "))
}

pub(crate) fn build_query(template: &str, context: Value) -> Result<String, GraphError> {
    let mut env = Environment::new();
    env.add_template("template", template)
        .map_err(|e| GraphError::JinjaError(e.to_string()))?;
    let query = env
        .get_template("template")
        .map_err(|e| GraphError::JinjaError(e.to_string()))?
        .render(context)
        .map_err(|e| GraphError::JinjaError(e.to_string()))?;
    Ok(query)
}

/// Specifies that **all** properties should be included when creating an index.
/// Use one of the predefined variants: ALL , ALL_METADATA , or ALL_TEMPORAL .
#[derive(Clone, Serialize, PartialEq)]
#[pyclass(name = "AllPropertySpec", module = "raphtory.graphql", eq, eq_int)]
pub enum PyAllPropertySpec {
    /// Include all properties (both metadata and temporal).
    #[serde(rename = "ALL")]
    All,
    /// Include only metadata.
    #[serde(rename = "ALL_METADATA")]
    AllMetadata,
    /// Include only temporal properties.
    #[serde(rename = "ALL_PROPERTIES")]
    AllProperties,
}

/// Create a SomePropertySpec by explicitly listing metadata and/or temporal property names.
///
/// Arguments:
///     metadata (list[str]): Metadata property names. Defaults to [].
///     properties (list[str]): Temporal property names. Defaults to [].
#[derive(Clone, Serialize)]
#[pyclass(name = "SomePropertySpec", module = "raphtory.graphql")]
pub struct PySomePropertySpec {
    /// Metadata property names to include in the index.
    pub metadata: Vec<String>,
    /// Temporal property names to include in the index.
    pub properties: Vec<String>,
}

#[pymethods]
impl PySomePropertySpec {
    #[new]
    #[pyo3(signature = (metadata = vec![], properties = vec![]))]
    fn new(metadata: Vec<String>, properties: Vec<String>) -> Self {
        Self {
            metadata,
            properties,
        }
    }
}

/// Create a PropsInput by choosing to include all/some properties explicitly.
///
/// Arguments:
///     all (AllPropertySpec, optional): Use a predefined spec to include all properties of a kind.
///     some (SomePropertySpec, optional): Explicitly list the properties to include.
///
/// Raises:
///     ValueError: If neither all and some are specified.
#[derive(Clone, Serialize)]
#[pyclass(name = "PropsInput", module = "raphtory.graphql")]
pub struct PyPropsInput {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub all: Option<PyAllPropertySpec>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub some: Option<PySomePropertySpec>,
}

#[pymethods]
impl PyPropsInput {
    #[new]
    #[pyo3(signature = (all=None, some=None))]
    fn new(all: Option<PyAllPropertySpec>, some: Option<PySomePropertySpec>) -> PyResult<Self> {
        if all.is_none() && some.is_none() {
            Err(PyValueError::new_err(
                "PropsInput must have exactly one of 'all' or 'some'",
            ))
        } else {
            Ok(Self { all, some })
        }
    }
}

/// Create a RemoteIndexSpec specifying which node and edge properties to index.
///
/// Arguments:
///     node_props (PropsInput): Property spec for nodes.
///     edge_props (PropsInput): Property spec for edges.
#[derive(Clone, Serialize)]
#[pyclass(name = "RemoteIndexSpec", module = "raphtory.graphql")]
pub struct PyRemoteIndexSpec {
    /// Property inclusion specification for nodes.
    #[serde(rename = "nodeProps")]
    pub node_props: PyPropsInput,
    /// Property inclusion specification for edges.
    #[serde(rename = "edgeProps")]
    pub edge_props: PyPropsInput,
}

#[pymethods]
impl PyRemoteIndexSpec {
    #[new]
    #[pyo3(signature = (node_props, edge_props))]
    fn new(node_props: PyPropsInput, edge_props: PyPropsInput) -> Self {
        Self {
            node_props,
            edge_props,
        }
    }
}