nodio 0.2.0

Ergonomic graph data storage with queries over relations
Documentation
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 crate::{graph::Graph, relations::RelationsTable};
use intuicio_core::{registry::Registry, types::TypeQuery};
use intuicio_data::type_hash::TypeHash;
use intuicio_framework_arena::{AnyArena, AnyIndex, ArenaError, Index};
use intuicio_framework_serde::{Intermediate, SerializationRegistry};
use serde::{Deserialize, Serialize};
use std::{
    collections::{HashMap, HashSet},
    error::Error,
};

#[derive(Debug)]
pub enum PrefabError {
    CouldNotFindType(TypeHash),
    CouldNotSerializeType {
        type_name: String,
        module_name: Option<String>,
    },
    CouldNotDeserializeType {
        type_name: String,
        module_name: Option<String>,
    },
    Arena(ArenaError),
    Custom(Box<dyn Error>),
}

impl std::fmt::Display for PrefabError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CouldNotFindType(type_hash) => {
                write!(f, "Could not find type by hash: {:?}", type_hash)
            }
            Self::CouldNotSerializeType {
                type_name,
                module_name,
            } => write!(
                f,
                "Could not serialize type: {}::{}",
                module_name.as_deref().unwrap_or_default(),
                type_name
            ),
            Self::CouldNotDeserializeType {
                type_name,
                module_name,
            } => write!(
                f,
                "Could not deserialize type: {}::{}",
                module_name.as_deref().unwrap_or_default(),
                type_name
            ),
            Self::Arena(error) => write!(f, "Arena: {}", error),
            Self::Custom(error) => write!(f, "Custom: {}", error),
        }
    }
}

impl Error for PrefabError {}

impl From<ArenaError> for PrefabError {
    fn from(error: ArenaError) -> Self {
        Self::Arena(error)
    }
}

impl From<Box<dyn Error>> for PrefabError {
    fn from(error: Box<dyn Error>) -> Self {
        Self::Custom(error)
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrefabDataType {
    pub type_name: String,
    pub module_name: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrefabNodesArchetype {
    pub data_type: PrefabDataType,
    pub indices: Vec<Index>,
    pub data: Vec<Intermediate>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrefabRelationsTableItem {
    pub data_type: PrefabDataType,
    pub index: Index,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrefabRelationsTable {
    pub source_data_type: PrefabDataType,
    pub source_index: Index,
    pub target: Vec<PrefabRelationsTableItem>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PrefabRelationArchetype {
    pub data_type: PrefabDataType,
    pub incoming: Vec<PrefabRelationsTable>,
    pub outgoing: Vec<PrefabRelationsTable>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Prefab {
    pub nodes: Vec<PrefabNodesArchetype>,
    pub relations: Vec<PrefabRelationArchetype>,
}

impl Prefab {
    pub fn from_graph(
        graph: &Graph,
        serialization: &SerializationRegistry,
        registry: &Registry,
    ) -> Result<Self, PrefabError> {
        let nodes = graph
            .nodes
            .arenas()
            .iter()
            .map(|arena| {
                let type_ = registry
                    .find_type(TypeQuery {
                        type_hash: Some(arena.type_hash()),
                        ..Default::default()
                    })
                    .ok_or_else(|| PrefabError::CouldNotFindType(arena.type_hash()))?;
                let data_type = PrefabDataType {
                    type_name: type_.name().to_owned(),
                    module_name: type_.module_name().map(|name| name.to_owned()),
                };
                let indices = arena.indices().collect::<Vec<_>>();
                let data = indices
                    .iter()
                    .map(|index| unsafe {
                        let data = arena.read_ptr(*index)?;
                        serialization
                            .dynamic_serialize_from(arena.type_hash(), data)
                            .map_err(|_| PrefabError::CouldNotSerializeType {
                                type_name: type_.name().to_owned(),
                                module_name: type_.module_name().map(|name| name.to_owned()),
                            })
                    })
                    .collect::<Result<Vec<_>, PrefabError>>()?;
                Ok(PrefabNodesArchetype {
                    data_type,
                    indices,
                    data,
                })
            })
            .collect::<Result<Vec<_>, PrefabError>>()?;
        let relations = graph
            .relations
            .iter()
            .map(|(type_hash, table)| {
                let type_ = registry
                    .find_type(TypeQuery {
                        type_hash: Some(*type_hash),
                        ..Default::default()
                    })
                    .ok_or_else(|| PrefabError::CouldNotFindType(*type_hash))?;
                let data_type = PrefabDataType {
                    type_name: type_.name().to_owned(),
                    module_name: type_.module_name().map(|name| name.to_owned()),
                };
                let incoming = table
                    .incoming
                    .iter()
                    .map(|(source, target)| {
                        let source_type = registry
                            .find_type(TypeQuery {
                                type_hash: Some(source.type_hash()),
                                ..Default::default()
                            })
                            .ok_or_else(|| PrefabError::CouldNotFindType(source.type_hash()))?;
                        let source_data_type = PrefabDataType {
                            type_name: source_type.name().to_owned(),
                            module_name: source_type.module_name().map(|name| name.to_owned()),
                        };
                        Ok(PrefabRelationsTable {
                            source_data_type,
                            source_index: source.index(),
                            target: target
                                .iter()
                                .map(|target| {
                                    let target_type = registry
                                        .find_type(TypeQuery {
                                            type_hash: Some(target.type_hash()),
                                            ..Default::default()
                                        })
                                        .ok_or_else(|| {
                                            PrefabError::CouldNotFindType(target.type_hash())
                                        })?;
                                    let target_data_type = PrefabDataType {
                                        type_name: target_type.name().to_owned(),
                                        module_name: target_type
                                            .module_name()
                                            .map(|name| name.to_owned()),
                                    };
                                    Ok(PrefabRelationsTableItem {
                                        data_type: target_data_type,
                                        index: target.index(),
                                    })
                                })
                                .collect::<Result<Vec<_>, PrefabError>>()?,
                        })
                    })
                    .collect::<Result<Vec<_>, PrefabError>>()?;
                let outgoing = table
                    .outgoing
                    .iter()
                    .map(|(source, target)| {
                        let source_type = registry
                            .find_type(TypeQuery {
                                type_hash: Some(source.type_hash()),
                                ..Default::default()
                            })
                            .ok_or_else(|| PrefabError::CouldNotFindType(source.type_hash()))?;
                        let source_data_type = PrefabDataType {
                            type_name: source_type.name().to_owned(),
                            module_name: source_type.module_name().map(|name| name.to_owned()),
                        };
                        Ok(PrefabRelationsTable {
                            source_data_type,
                            source_index: source.index(),
                            target: target
                                .iter()
                                .map(|target| {
                                    let target_type = registry
                                        .find_type(TypeQuery {
                                            type_hash: Some(target.type_hash()),
                                            ..Default::default()
                                        })
                                        .ok_or_else(|| {
                                            PrefabError::CouldNotFindType(target.type_hash())
                                        })?;
                                    let target_data_type = PrefabDataType {
                                        type_name: target_type.name().to_owned(),
                                        module_name: target_type
                                            .module_name()
                                            .map(|name| name.to_owned()),
                                    };
                                    Ok(PrefabRelationsTableItem {
                                        data_type: target_data_type,
                                        index: target.index(),
                                    })
                                })
                                .collect::<Result<Vec<_>, PrefabError>>()?,
                        })
                    })
                    .collect::<Result<Vec<_>, PrefabError>>()?;
                Ok(PrefabRelationArchetype {
                    data_type,
                    outgoing,
                    incoming,
                })
            })
            .collect::<Result<Vec<_>, PrefabError>>()?;
        Ok(Self { nodes, relations })
    }

    pub fn to_graph(
        &self,
        serialization: &SerializationRegistry,
        registry: &Registry,
    ) -> Result<(Graph, HashMap<AnyIndex, AnyIndex>), PrefabError> {
        let mut mappings = HashMap::<AnyIndex, AnyIndex>::default();
        let mut nodes = AnyArena::default();
        for archetype in &self.nodes {
            let type_ = registry
                .find_type(TypeQuery {
                    name: Some(archetype.data_type.type_name.as_str().into()),
                    module_name: archetype
                        .data_type
                        .module_name
                        .as_ref()
                        .map(|name| name.as_str().into()),
                    ..Default::default()
                })
                .ok_or_else(|| PrefabError::CouldNotDeserializeType {
                    type_name: archetype.data_type.type_name.to_owned(),
                    module_name: archetype.data_type.module_name.to_owned(),
                })?;
            unsafe {
                let arena = {
                    nodes.ensure_arena_raw(type_.type_hash(), *type_.layout(), type_.finalizer())
                };
                for (old_index, data) in archetype.indices.iter().zip(archetype.data.iter()) {
                    let (new_index, memory) = arena.allocate();
                    type_.initialize(memory.cast::<_>());
                    serialization
                        .dynamic_deserialize_to(type_.type_hash(), memory, data)
                        .map_err(|_| PrefabError::CouldNotDeserializeType {
                            type_name: type_.name().to_owned(),
                            module_name: type_.module_name().map(|name| name.to_owned()),
                        })?;
                    mappings.insert(
                        AnyIndex::new(*old_index, type_.type_hash()),
                        AnyIndex::new(new_index, type_.type_hash()),
                    );
                }
            }
        }
        let relations = self
            .relations
            .iter()
            .map(|archetype| {
                let type_ = registry
                    .find_type(TypeQuery {
                        name: Some(archetype.data_type.type_name.as_str().into()),
                        module_name: archetype
                            .data_type
                            .module_name
                            .as_ref()
                            .map(|name| name.as_str().into()),
                        ..Default::default()
                    })
                    .ok_or_else(|| PrefabError::CouldNotDeserializeType {
                        type_name: archetype.data_type.type_name.to_owned(),
                        module_name: archetype.data_type.module_name.to_owned(),
                    })?;
                let outgoing = archetype
                    .outgoing
                    .iter()
                    .map(|table| {
                        let source_type = registry
                            .find_type(TypeQuery {
                                name: Some(table.source_data_type.type_name.as_str().into()),
                                module_name: table
                                    .source_data_type
                                    .module_name
                                    .as_ref()
                                    .map(|name| name.as_str().into()),
                                ..Default::default()
                            })
                            .ok_or_else(|| PrefabError::CouldNotDeserializeType {
                                type_name: table.source_data_type.type_name.to_owned(),
                                module_name: table.source_data_type.module_name.to_owned(),
                            })?;
                        let target = table
                            .target
                            .iter()
                            .map(|target| {
                                let target_type = registry
                                    .find_type(TypeQuery {
                                        name: Some(target.data_type.type_name.as_str().into()),
                                        module_name: target
                                            .data_type
                                            .module_name
                                            .as_ref()
                                            .map(|name| name.as_str().into()),
                                        ..Default::default()
                                    })
                                    .ok_or_else(|| PrefabError::CouldNotDeserializeType {
                                        type_name: target.data_type.type_name.to_owned(),
                                        module_name: target.data_type.module_name.to_owned(),
                                    })?;
                                let index = AnyIndex::new(target.index, target_type.type_hash());
                                let index = mappings.get(&index).copied().ok_or_else(|| {
                                    PrefabError::Arena(ArenaError::IndexNotFound {
                                        type_hash: index.type_hash(),
                                        index: index.index(),
                                    })
                                })?;
                                Ok(index)
                            })
                            .collect::<Result<HashSet<_>, PrefabError>>()?;
                        let index = AnyIndex::new(table.source_index, source_type.type_hash());
                        let index = mappings.get(&index).copied().ok_or_else(|| {
                            PrefabError::Arena(ArenaError::IndexNotFound {
                                type_hash: index.type_hash(),
                                index: index.index(),
                            })
                        })?;
                        Ok((index, target))
                    })
                    .collect::<Result<HashMap<_, _>, PrefabError>>()?;
                let incoming = archetype
                    .incoming
                    .iter()
                    .map(|table| {
                        let source_type = registry
                            .find_type(TypeQuery {
                                name: Some(table.source_data_type.type_name.as_str().into()),
                                module_name: table
                                    .source_data_type
                                    .module_name
                                    .as_ref()
                                    .map(|name| name.as_str().into()),
                                ..Default::default()
                            })
                            .ok_or_else(|| PrefabError::CouldNotDeserializeType {
                                type_name: table.source_data_type.type_name.to_owned(),
                                module_name: table.source_data_type.module_name.to_owned(),
                            })?;
                        let target = table
                            .target
                            .iter()
                            .map(|target| {
                                let target_type = registry
                                    .find_type(TypeQuery {
                                        name: Some(target.data_type.type_name.as_str().into()),
                                        module_name: target
                                            .data_type
                                            .module_name
                                            .as_ref()
                                            .map(|name| name.as_str().into()),
                                        ..Default::default()
                                    })
                                    .ok_or_else(|| PrefabError::CouldNotDeserializeType {
                                        type_name: target.data_type.type_name.to_owned(),
                                        module_name: target.data_type.module_name.to_owned(),
                                    })?;
                                let index = AnyIndex::new(target.index, target_type.type_hash());
                                let index = mappings.get(&index).copied().ok_or_else(|| {
                                    PrefabError::Arena(ArenaError::IndexNotFound {
                                        type_hash: index.type_hash(),
                                        index: index.index(),
                                    })
                                })?;
                                Ok(index)
                            })
                            .collect::<Result<HashSet<_>, PrefabError>>()?;
                        let index = AnyIndex::new(table.source_index, source_type.type_hash());
                        let index = mappings.get(&index).copied().ok_or_else(|| {
                            PrefabError::Arena(ArenaError::IndexNotFound {
                                type_hash: index.type_hash(),
                                index: index.index(),
                            })
                        })?;
                        Ok((index, target))
                    })
                    .collect::<Result<HashMap<_, _>, PrefabError>>()?;
                Ok((type_.type_hash(), RelationsTable { outgoing, incoming }))
            })
            .collect::<Result<HashMap<_, _>, PrefabError>>()?;
        Ok((Graph { nodes, relations }, mappings))
    }
}