Skip to main content

drevo_core/
dump.rs

1//! The `drevo-json-v1` dump format: a whole graph as one value.
2//!
3//! A [`crate::dump::Dump`] is the whole graph (every node, every edge,
4//! plus the id-allocation counters) in one serde-serializable value.
5//! [`GraphEngine::export_dump`](crate::engine::GraphEngine::export_dump)
6//! produces one and [`GraphEngine::apply_dump`](crate::engine::GraphEngine::apply_dump)
7//! loads one back, losslessly — for backups and for moving a graph between
8//! stores.
9//!
10//! Only the **types** live here — [`crate::dump::Dump`],
11//! [`crate::dump::ImportReport`], [`crate::dump::DumpError`], and the
12//! [`crate::dump::FORMAT_V1`] identifier. Rendering and parsing *file* formats
13//! (pretty JSON, GraphML) is drevo's job, not this crate's.
14
15use serde::{Deserialize, Serialize};
16
17use crate::error::CoreError;
18use crate::model::{Edge, Node};
19
20/// Wire-format identifier for the v1 dump schema. Always emitted in the
21/// `format` field; import refuses to load any other value.
22pub const FORMAT_V1: &str = "drevo-json-v1";
23
24/// Top-level wire format of a `drevo-json-v1` dump.
25///
26/// Public so external tooling (CLI dumpers, migration scripts) can parse a
27/// dump without re-deriving the schema. Field order is fixed for forward-
28/// compatibility — new fields will be added with serde defaults.
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct Dump {
31    /// Schema identifier. MUST be [`FORMAT_V1`] on import.
32    pub format: String,
33    /// Producer's wall-clock at export time (Unix milliseconds). Informational.
34    pub exported_at: i64,
35    /// Producer's `next_node_id` counter — the receiver clamps its counter
36    /// to be at least this value so freshly-allocated ids never collide with
37    /// imported ones.
38    pub next_node_id: u64,
39    /// Producer's `next_edge_id` counter (see [`next_node_id`](Self::next_node_id)).
40    pub next_edge_id: u64,
41    /// Every node in the source database.
42    pub nodes: Vec<Node>,
43    /// Every edge in the source database.
44    pub edges: Vec<Edge>,
45}
46
47/// Outcome of a successful dump import
48/// ([`GraphEngine::apply_dump`](crate::engine::GraphEngine::apply_dump)).
49///
50/// Counts are reported separately so callers can distinguish "newly inserted"
51/// from "already present, skipped". `*_skipped` rows were matched by id AND
52/// byte-equal content; an id collision with different content surfaces as a
53/// [`DumpError`] before this struct is returned.
54#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
55pub struct ImportReport {
56    /// Number of nodes inserted into the receiver during this import.
57    pub nodes_imported: usize,
58    /// Number of edges inserted into the receiver during this import.
59    pub edges_imported: usize,
60    /// Number of nodes that already existed with byte-equal content and were
61    /// skipped (idempotent re-import).
62    pub nodes_skipped: usize,
63    /// Number of edges that already existed with byte-equal content and were
64    /// skipped (idempotent re-import).
65    pub edges_skipped: usize,
66}
67
68/// Import-time failure modes specific to the dump format.
69///
70/// Lifted to callers as a backend `Io` error via the `From` impls (this crate's
71/// [`CoreError`] and drevo's `DrevoError`) so the public error
72/// hierarchies stay at their well-known variants. The conversion preserves the
73/// human-readable message — `{err}` includes the original failure mode.
74#[derive(Debug, thiserror::Error)]
75pub enum DumpError {
76    /// The JSON payload was malformed and `serde_json` could not parse it.
77    #[error("malformed JSON dump: {0}")]
78    Malformed(#[from] serde_json::Error),
79    /// The `format` field is missing, empty, or names an unknown schema.
80    #[error("unsupported dump format: {0:?} — expected drevo-json-v1")]
81    UnsupportedFormat(String),
82    /// An imported node / edge collides with an existing row that has the
83    /// same id but different content.
84    #[error("id collision on import: {0}")]
85    IdCollision(String),
86    /// A GraphML payload was not well-formed XML, was missing a required
87    /// structural element (`<graphml>` / `<graph>` / a `<node>` id), or
88    /// referenced an undeclared node from an `<edge>`.
89    #[error("malformed GraphML: {0}")]
90    MalformedGraphml(String),
91}
92
93impl From<DumpError> for CoreError {
94    fn from(err: DumpError) -> Self {
95        CoreError::Io(std::io::Error::other(err.to_string()))
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn dump_error_renders_and_lifts_to_core_io() {
105        let e = DumpError::IdCollision("node 5".into());
106        assert_eq!(e.to_string(), "id collision on import: node 5");
107        let core: CoreError = e.into();
108        assert!(matches!(core, CoreError::Io(_)));
109        assert_eq!(core.to_string(), "io error: id collision on import: node 5");
110    }
111
112    #[test]
113    fn dump_round_trips_through_json() {
114        let dump = Dump {
115            format: FORMAT_V1.to_string(),
116            exported_at: 123,
117            next_node_id: 9,
118            next_edge_id: 4,
119            nodes: Vec::new(),
120            edges: Vec::new(),
121        };
122        let json = serde_json::to_string(&dump).unwrap();
123        let back: Dump = serde_json::from_str(&json).unwrap();
124        assert_eq!(back.format, FORMAT_V1);
125        assert_eq!(back.next_node_id, 9);
126        assert_eq!(back.next_edge_id, 4);
127    }
128
129    #[test]
130    fn import_report_default_is_all_zero() {
131        assert_eq!(ImportReport::default(), ImportReport::default());
132        let r = ImportReport::default();
133        assert_eq!(
134            r.nodes_imported + r.edges_imported + r.nodes_skipped + r.edges_skipped,
135            0
136        );
137    }
138}