version_migrate/
lib.rs

1//! # version-migrate
2//!
3//! A library for explicit, type-safe schema versioning and migration.
4//!
5//! ## Features
6//!
7//! - **Type-safe migrations**: Define migrations between versions using traits
8//! - **Validation**: Automatic validation of migration paths (circular path detection, version ordering)
9//! - **Multi-format support**: Load from JSON, TOML, YAML, or any serde-compatible format
10//! - **Vec support**: Migrate collections of versioned entities
11//! - **Hierarchical structures**: Support for nested versioned entities
12//! - **Async migrations**: Optional async support for I/O-heavy migrations
13//!
14//! ## Basic Example
15//!
16//! ```ignore
17//! use version_migrate::{Versioned, MigratesTo, IntoDomain, Migrator};
18//! use serde::{Serialize, Deserialize};
19//!
20//! // Version 1.0.0
21//! #[derive(Serialize, Deserialize, Versioned)]
22//! #[versioned(version = "1.0.0")]
23//! struct TaskV1_0_0 {
24//!     id: String,
25//!     title: String,
26//! }
27//!
28//! // Version 1.1.0
29//! #[derive(Serialize, Deserialize, Versioned)]
30//! #[versioned(version = "1.1.0")]
31//! struct TaskV1_1_0 {
32//!     id: String,
33//!     title: String,
34//!     description: Option<String>,
35//! }
36//!
37//! // Domain model
38//! struct TaskEntity {
39//!     id: String,
40//!     title: String,
41//!     description: Option<String>,
42//! }
43//!
44//! impl MigratesTo<TaskV1_1_0> for TaskV1_0_0 {
45//!     fn migrate(self) -> TaskV1_1_0 {
46//!         TaskV1_1_0 {
47//!             id: self.id,
48//!             title: self.title,
49//!             description: None,
50//!         }
51//!     }
52//! }
53//!
54//! impl IntoDomain<TaskEntity> for TaskV1_1_0 {
55//!     fn into_domain(self) -> TaskEntity {
56//!         TaskEntity {
57//!             id: self.id,
58//!             title: self.title,
59//!             description: self.description,
60//!         }
61//!     }
62//! }
63//! ```
64//!
65//! ## Working with Collections (Vec)
66//!
67//! ```ignore
68//! // Save multiple versioned entities
69//! let tasks = vec![
70//!     TaskV1_0_0 { id: "1".into(), title: "Task 1".into() },
71//!     TaskV1_0_0 { id: "2".into(), title: "Task 2".into() },
72//! ];
73//! let json = migrator.save_vec(tasks)?;
74//!
75//! // Load and migrate multiple entities
76//! let domains: Vec<TaskEntity> = migrator.load_vec("task", &json)?;
77//! ```
78//!
79//! ## Hierarchical Structures
80//!
81//! For complex configurations with nested versioned entities:
82//!
83//! ```ignore
84//! #[derive(Serialize, Deserialize, Versioned)]
85//! #[versioned(version = "1.0.0")]
86//! struct ConfigV1 {
87//!     setting: SettingV1,
88//!     items: Vec<ItemV1>,
89//! }
90//!
91//! #[derive(Serialize, Deserialize, Versioned)]
92//! #[versioned(version = "2.0.0")]
93//! struct ConfigV2 {
94//!     setting: SettingV2,
95//!     items: Vec<ItemV2>,
96//! }
97//!
98//! impl MigratesTo<ConfigV2> for ConfigV1 {
99//!     fn migrate(self) -> ConfigV2 {
100//!         ConfigV2 {
101//!             // Migrate nested entities
102//!             setting: self.setting.migrate(),
103//!             items: self.items.into_iter()
104//!                 .map(|item| item.migrate())
105//!                 .collect(),
106//!         }
107//!     }
108//! }
109//! ```
110//!
111//! ## Design Philosophy
112//!
113//! This library follows the **explicit versioning** approach:
114//!
115//! - Each version has its own type (V1, V2, V3, etc.)
116//! - Migration logic is explicit and testable
117//! - Version changes are tracked in code
118//! - Root-level versioning ensures consistency
119//!
120//! This differs from ProtoBuf's "append-only" approach but allows for:
121//! - Schema refactoring and cleanup
122//! - Type-safe migration paths
123//! - Clear version history in code
124
125use serde::{Deserialize, Serialize};
126
127pub mod errors;
128mod migrator;
129pub mod paths;
130pub mod storage;
131
132// Re-export the derive macros
133pub use version_migrate_macro::Versioned;
134
135// Re-export Queryable derive macro (same name as trait is OK in Rust)
136#[doc(inline)]
137pub use version_migrate_macro::Queryable as DeriveQueryable;
138
139// Re-export VersionMigrate derive macro
140#[doc(inline)]
141pub use version_migrate_macro::VersionMigrate;
142
143// Re-export error types
144pub use errors::MigrationError;
145
146// Re-export migrator types
147pub use migrator::{ConfigMigrator, MigrationPath, Migrator};
148
149// Re-export storage types
150pub use storage::{
151    AtomicWriteConfig, FileStorage, FileStorageStrategy, FormatStrategy, LoadBehavior,
152};
153
154// Re-export paths types
155pub use paths::{AppPaths, PathStrategy};
156
157// Re-export async-trait for user convenience
158pub use async_trait::async_trait;
159
160/// A trait for versioned data schemas.
161///
162/// This trait marks a type as representing a specific version of a data schema.
163/// It should be derived using `#[derive(Versioned)]` along with the `#[versioned(version = "x.y.z")]` attribute.
164///
165/// # Custom Keys
166///
167/// You can customize the serialization keys:
168///
169/// ```ignore
170/// #[derive(Versioned)]
171/// #[versioned(
172///     version = "1.0.0",
173///     version_key = "schema_version",
174///     data_key = "payload"
175/// )]
176/// struct Task { ... }
177/// // Serializes to: {"schema_version":"1.0.0","payload":{...}}
178/// ```
179pub trait Versioned {
180    /// The semantic version of this schema.
181    const VERSION: &'static str;
182
183    /// The key name for the version field in serialized data.
184    /// Defaults to "version".
185    const VERSION_KEY: &'static str = "version";
186
187    /// The key name for the data field in serialized data.
188    /// Defaults to "data".
189    const DATA_KEY: &'static str = "data";
190}
191
192/// Defines explicit migration logic from one version to another.
193///
194/// Implementing this trait establishes a migration path from `Self` (the source version)
195/// to `T` (the target version).
196pub trait MigratesTo<T: Versioned>: Versioned {
197    /// Migrates from the current version to the target version.
198    fn migrate(self) -> T;
199}
200
201/// Converts a versioned DTO into the application's domain model.
202///
203/// This trait should be implemented on the latest version of a DTO to convert
204/// it into the clean, version-agnostic domain model.
205pub trait IntoDomain<D>: Versioned {
206    /// Converts this versioned data into the domain model.
207    fn into_domain(self) -> D;
208}
209
210/// Converts a domain model back into a versioned DTO.
211///
212/// This trait should be implemented on versioned DTOs to enable conversion
213/// from the domain model back to the versioned format for serialization.
214///
215/// # Example
216///
217/// ```ignore
218/// impl FromDomain<TaskEntity> for TaskV1_1_0 {
219///     fn from_domain(domain: TaskEntity) -> Self {
220///         TaskV1_1_0 {
221///             id: domain.id,
222///             title: domain.title,
223///             description: domain.description,
224///         }
225///     }
226/// }
227/// ```
228pub trait FromDomain<D>: Versioned + Serialize {
229    /// Converts a domain model into this versioned format.
230    fn from_domain(domain: D) -> Self;
231}
232
233/// Associates a domain entity with its latest versioned representation.
234///
235/// This trait enables automatic saving of domain entities using their latest version.
236/// It should typically be derived using the `#[version_migrate]` attribute macro.
237///
238/// # Example
239///
240/// ```ignore
241/// #[derive(Serialize, Deserialize)]
242/// #[version_migrate(entity = "task", latest = TaskV1_1_0)]
243/// struct TaskEntity {
244///     id: String,
245///     title: String,
246///     description: Option<String>,
247/// }
248///
249/// // Now you can save entities directly
250/// let entity = TaskEntity { ... };
251/// let json = migrator.save_entity(entity)?;
252/// ```
253pub trait LatestVersioned: Sized {
254    /// The latest versioned type for this entity.
255    type Latest: Versioned + Serialize + FromDomain<Self>;
256
257    /// The entity name used for migration paths.
258    const ENTITY_NAME: &'static str;
259
260    /// Converts this domain entity into its latest versioned format.
261    fn to_latest(self) -> Self::Latest {
262        Self::Latest::from_domain(self)
263    }
264}
265
266/// Marks a domain type as queryable, associating it with an entity name.
267///
268/// This trait enables `ConfigMigrator` to automatically determine which entity
269/// path to use when querying or updating data.
270///
271/// # Example
272///
273/// ```ignore
274/// impl Queryable for TaskEntity {
275///     const ENTITY_NAME: &'static str = "task";
276/// }
277///
278/// let tasks: Vec<TaskEntity> = config.query("tasks")?;
279/// ```
280pub trait Queryable {
281    /// The entity name used to look up migration paths in the `Migrator`.
282    const ENTITY_NAME: &'static str;
283}
284
285/// Async version of `MigratesTo` for migrations requiring I/O operations.
286///
287/// Use this trait when migrations need to perform asynchronous operations
288/// such as database queries or API calls.
289#[async_trait::async_trait]
290pub trait AsyncMigratesTo<T: Versioned>: Versioned + Send {
291    /// Asynchronously migrates from the current version to the target version.
292    ///
293    /// # Errors
294    ///
295    /// Returns `MigrationError` if the migration fails.
296    async fn migrate(self) -> Result<T, MigrationError>;
297}
298
299/// Async version of `IntoDomain` for domain conversions requiring I/O operations.
300///
301/// Use this trait when converting to the domain model requires asynchronous
302/// operations such as fetching additional data from external sources.
303#[async_trait::async_trait]
304pub trait AsyncIntoDomain<D>: Versioned + Send {
305    /// Asynchronously converts this versioned data into the domain model.
306    ///
307    /// # Errors
308    ///
309    /// Returns `MigrationError` if the conversion fails.
310    async fn into_domain(self) -> Result<D, MigrationError>;
311}
312
313/// A wrapper for serialized data that includes explicit version information.
314///
315/// This struct is used for persistence to ensure that the version of the data
316/// is always stored alongside the data itself.
317#[derive(Serialize, Deserialize, Debug, Clone)]
318pub struct VersionedWrapper<T> {
319    /// The semantic version of the data.
320    pub version: String,
321    /// The actual data.
322    pub data: T,
323}
324
325impl<T> VersionedWrapper<T> {
326    /// Creates a new versioned wrapper with the specified version and data.
327    pub fn new(version: String, data: T) -> Self {
328        Self { version, data }
329    }
330}
331
332impl<T: Versioned> VersionedWrapper<T> {
333    /// Creates a wrapper from a versioned value, automatically extracting its version.
334    pub fn from_versioned(data: T) -> Self {
335        Self {
336            version: T::VERSION.to_string(),
337            data,
338        }
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345
346    #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
347    struct TestData {
348        value: String,
349    }
350
351    impl Versioned for TestData {
352        const VERSION: &'static str = "1.0.0";
353    }
354
355    #[test]
356    fn test_versioned_wrapper_from_versioned() {
357        let data = TestData {
358            value: "test".to_string(),
359        };
360        let wrapper = VersionedWrapper::from_versioned(data);
361
362        assert_eq!(wrapper.version, "1.0.0");
363        assert_eq!(wrapper.data.value, "test");
364    }
365
366    #[test]
367    fn test_versioned_wrapper_new() {
368        let data = TestData {
369            value: "manual".to_string(),
370        };
371        let wrapper = VersionedWrapper::new("2.0.0".to_string(), data);
372
373        assert_eq!(wrapper.version, "2.0.0");
374        assert_eq!(wrapper.data.value, "manual");
375    }
376
377    #[test]
378    fn test_versioned_wrapper_serialization() {
379        let data = TestData {
380            value: "serialize_test".to_string(),
381        };
382        let wrapper = VersionedWrapper::from_versioned(data);
383
384        // Serialize
385        let json = serde_json::to_string(&wrapper).expect("Serialization failed");
386
387        // Deserialize
388        let deserialized: VersionedWrapper<TestData> =
389            serde_json::from_str(&json).expect("Deserialization failed");
390
391        assert_eq!(deserialized.version, "1.0.0");
392        assert_eq!(deserialized.data.value, "serialize_test");
393    }
394
395    #[test]
396    fn test_versioned_wrapper_with_complex_data() {
397        #[derive(Serialize, Deserialize, Debug, PartialEq)]
398        struct ComplexData {
399            id: u64,
400            name: String,
401            tags: Vec<String>,
402            metadata: Option<String>,
403        }
404
405        impl Versioned for ComplexData {
406            const VERSION: &'static str = "3.2.1";
407        }
408
409        let data = ComplexData {
410            id: 42,
411            name: "complex".to_string(),
412            tags: vec!["tag1".to_string(), "tag2".to_string()],
413            metadata: Some("meta".to_string()),
414        };
415
416        let wrapper = VersionedWrapper::from_versioned(data);
417        assert_eq!(wrapper.version, "3.2.1");
418        assert_eq!(wrapper.data.id, 42);
419        assert_eq!(wrapper.data.tags.len(), 2);
420    }
421
422    #[test]
423    fn test_versioned_wrapper_clone() {
424        let data = TestData {
425            value: "clone_test".to_string(),
426        };
427        let wrapper = VersionedWrapper::from_versioned(data);
428        let cloned = wrapper.clone();
429
430        assert_eq!(cloned.version, wrapper.version);
431        assert_eq!(cloned.data.value, wrapper.data.value);
432    }
433
434    #[test]
435    fn test_versioned_wrapper_debug() {
436        let data = TestData {
437            value: "debug".to_string(),
438        };
439        let wrapper = VersionedWrapper::from_versioned(data);
440        let debug_str = format!("{:?}", wrapper);
441
442        assert!(debug_str.contains("1.0.0"));
443        assert!(debug_str.contains("debug"));
444    }
445}