1use std::collections::BTreeMap;
27use std::fmt;
28
29use serde::Serialize;
30use serde::de::DeserializeOwned;
31use serde_json::Value as Json;
32
33pub type Migration = fn(Json) -> Result<Json, String>;
35
36#[derive(Clone, Debug, PartialEq, Eq)]
38pub enum DocError {
39 Parse(String),
41 NotAnObject,
42 WrongKind {
44 expected: String,
45 found: String,
46 },
47 TooNew {
49 found: u32,
50 supported: u32,
51 },
52 MissingMigration {
54 from: u32,
55 },
56 Migration {
57 from: u32,
58 error: String,
59 },
60 Shape(String),
62}
63
64impl fmt::Display for DocError {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 match self {
67 DocError::Parse(e) => write!(f, "not JSON: {e}"),
68 DocError::NotAnObject => write!(f, "not a JSON object"),
69 DocError::WrongKind { expected, found } => {
70 write!(f, "a `{found}` document, not a `{expected}` one")
71 }
72 DocError::TooNew { found, supported } => write!(
73 f,
74 "version {found} is newer than this application reads (up to {supported})"
75 ),
76 DocError::MissingMigration { from } => {
77 write!(f, "no migration from version {from}")
78 }
79 DocError::Migration { from, error } => {
80 write!(f, "migrating from version {from}: {error}")
81 }
82 DocError::Shape(e) => write!(f, "unexpected content: {e}"),
83 }
84 }
85}
86
87impl std::error::Error for DocError {}
88
89#[derive(Clone, Debug, PartialEq)]
91pub struct Loaded<T> {
92 pub value: T,
93 pub from_version: u32,
95 pub migrated: Vec<String>,
97}
98
99#[derive(Clone, Debug)]
101pub struct Schema {
102 pub kind: &'static str,
103 pub current: u32,
104 migrations: BTreeMap<u32, Migration>,
105}
106
107impl Schema {
108 pub fn new(kind: &'static str, current: u32) -> Self {
109 Self {
110 kind,
111 current,
112 migrations: BTreeMap::new(),
113 }
114 }
115
116 pub fn migration(mut self, from: u32, f: Migration) -> Self {
118 self.migrations.insert(from, f);
119 self
120 }
121
122 pub fn gaps(&self) -> Vec<u32> {
124 (0..self.current)
125 .filter(|v| !self.migrations.contains_key(v))
126 .collect()
127 }
128
129 pub fn upgrade(&self, mut json: Json) -> Result<Loaded<Json>, DocError> {
131 let obj = json.as_object().ok_or(DocError::NotAnObject)?;
132 if let Some(kind) = obj.get("kind").and_then(Json::as_str)
133 && kind != self.kind
134 {
135 return Err(DocError::WrongKind {
136 expected: self.kind.into(),
137 found: kind.into(),
138 });
139 }
140 let from = obj
141 .get("version")
142 .and_then(Json::as_u64)
143 .map_or(0, |v| v.min(u32::MAX as u64) as u32);
144 if from > self.current {
145 return Err(DocError::TooNew {
146 found: from,
147 supported: self.current,
148 });
149 }
150 let mut migrated = Vec::new();
151 for v in from..self.current {
152 let m = self
153 .migrations
154 .get(&v)
155 .ok_or(DocError::MissingMigration { from: v })?;
156 json = m(json).map_err(|error| DocError::Migration { from: v, error })?;
157 migrated.push(format!("{v} -> {}", v + 1));
158 }
159 if let Some(obj) = json.as_object_mut() {
160 obj.insert("version".into(), self.current.into());
161 obj.insert("kind".into(), self.kind.into());
162 }
163 Ok(Loaded {
164 value: json,
165 from_version: from,
166 migrated,
167 })
168 }
169
170 pub fn load<T: DeserializeOwned>(&self, text: &str) -> Result<Loaded<T>, DocError> {
172 let json: Json = serde_json::from_str(text).map_err(|e| DocError::Parse(e.to_string()))?;
173 let up = self.upgrade(json)?;
174 let value = serde_json::from_value(up.value).map_err(|e| DocError::Shape(e.to_string()))?;
175 Ok(Loaded {
176 value,
177 from_version: up.from_version,
178 migrated: up.migrated,
179 })
180 }
181
182 pub fn save<T: Serialize>(&self, value: &T) -> Result<String, DocError> {
184 let mut json = serde_json::to_value(value).map_err(|e| DocError::Shape(e.to_string()))?;
185 let obj = json.as_object_mut().ok_or(DocError::NotAnObject)?;
186 let mut out = serde_json::Map::new();
187 out.insert("kind".into(), self.kind.into());
188 out.insert("version".into(), self.current.into());
189 for (k, v) in std::mem::take(obj) {
190 if k != "kind" && k != "version" {
191 out.insert(k, v);
192 }
193 }
194 serde_json::to_string_pretty(&Json::Object(out)).map_err(|e| DocError::Shape(e.to_string()))
195 }
196}
197
198pub(crate) fn same(json: Json) -> Result<Json, String> {
200 Ok(json)
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206 use serde_json::json;
207
208 #[test]
209 fn documents_migrate_and_refuse_what_they_cannot_read() {
210 let s = Schema::new("x", 2)
211 .migration(0, same)
212 .migration(1, |mut j| {
213 j["b"] = j["a"].take();
214 Ok(j)
215 });
216 assert!(s.gaps().is_empty());
217 let l = s.load::<Json>(r#"{"a": 1}"#).unwrap();
218 assert_eq!(l.from_version, 0);
219 assert_eq!(l.migrated, ["0 -> 1", "1 -> 2"]);
220 assert_eq!(l.value["b"], json!(1));
221 assert_eq!(l.value["version"], json!(2));
222 assert!(matches!(
223 s.load::<Json>(r#"{"version": 3}"#),
224 Err(DocError::TooNew { found: 3, .. })
225 ));
226 assert!(matches!(
227 s.load::<Json>(r#"{"kind": "y"}"#),
228 Err(DocError::WrongKind { .. })
229 ));
230 assert!(matches!(s.load::<Json>("[]"), Err(DocError::NotAnObject)));
231 assert!(matches!(s.load::<Json>("{"), Err(DocError::Parse(_))));
232 let gap = Schema::new("x", 2).migration(1, same);
233 assert_eq!(gap.gaps(), [0]);
234 assert_eq!(
235 gap.load::<Json>("{}").unwrap_err(),
236 DocError::MissingMigration { from: 0 }
237 );
238 let text = s.save(&json!({"b": 2, "version": 9})).unwrap();
239 let back: Json = serde_json::from_str(&text).unwrap();
240 assert_eq!(back, json!({"kind": "x", "version": 2, "b": 2}));
241 }
242}