-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmigratable.rs
More file actions
366 lines (347 loc) · 12.1 KB
/
Copy pathmigratable.rs
File metadata and controls
366 lines (347 loc) · 12.1 KB
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
//! Type-safe, bidirectional schema migration with compile-time chain validation.
//!
//! This module provides an Alembic-inspired migration system where every version
//! transition is a typed, bidirectional step between concrete Rust structs.
//!
//! # Architecture
//!
//! - [`MigrationStep`] — a single upgrade/downgrade between two concrete types
//! - [`MigrationChain`] — runtime dispatch generated by the `migration_chain!` macro
//! - `migration_chain!` — proc-macro (defined in `aimdb-derive`, re-exported here as
//! `aimdb_data_contracts::migration_chain!`) that validates the chain at compile time
//!
//! # How It Works
//!
//! Each schema version is a concrete Rust struct. Migration steps convert between
//! adjacent versions with full type safety — no raw JSON manipulation.
//!
//! The `migration_chain!` macro generates, for a chain of any length:
//! 1. **Const assertions** — version sequence validated at compile time
//! 2. **Type-checked dispatch** — compiler rejects mismatched type chains
//! 3. **`MigrationChain` impl** — runtime upgrade/downgrade with version detection, `O(N)`
//! in generated code size (one helper function per step, not one per historical version
//! reachable from every other version)
//!
//! # Example
//!
//! ```rust
//! use aimdb_data_contracts::{SchemaType, MigrationStep, MigrationChain, MigrationError};
//! use aimdb_data_contracts::migration_chain;
//! use serde::{Deserialize, Serialize};
//!
//! // v1 schema
//! #[derive(Clone, Debug, Serialize, Deserialize)]
//! struct SensorV1 {
//! schema_version: u32,
//! temp: f32,
//! timestamp: u64,
//! }
//! impl SchemaType for SensorV1 {
//! const NAME: &'static str = "sensor_v1";
//! const VERSION: u32 = 1;
//! }
//!
//! // v2 schema (current)
//! #[derive(Clone, Debug, Serialize, Deserialize)]
//! struct Sensor {
//! schema_version: u32,
//! celsius: f32,
//! timestamp: u64,
//! }
//! impl SchemaType for Sensor {
//! const NAME: &'static str = "sensor";
//! const VERSION: u32 = 2;
//! }
//!
//! // Migration step: v1 -> v2
//! struct SensorV1ToV2;
//! impl MigrationStep for SensorV1ToV2 {
//! type Older = SensorV1;
//! type Newer = Sensor;
//! const FROM_VERSION: u32 = 1;
//! const TO_VERSION: u32 = 2;
//!
//! fn up(v1: SensorV1) -> Result<Sensor, MigrationError> {
//! Ok(Sensor { schema_version: 2, celsius: v1.temp, timestamp: v1.timestamp })
//! }
//! fn down(v2: Sensor) -> Result<SensorV1, MigrationError> {
//! Ok(SensorV1 { schema_version: 1, temp: v2.celsius, timestamp: v2.timestamp })
//! }
//! }
//!
//! // Wire up the chain
//! migration_chain! {
//! type Current = Sensor;
//! version_field = "schema_version";
//! steps {
//! SensorV1ToV2: SensorV1 => Sensor,
//! }
//! }
//!
//! // Upgrade from v1 bytes
//! let v1_json = r#"{"schema_version":1,"temp":22.5,"timestamp":100}"#;
//! let sensor = Sensor::migrate_from_bytes(v1_json.as_bytes()).unwrap();
//! assert_eq!(sensor.celsius, 22.5);
//!
//! // Downgrade to v1 bytes
//! let v1_bytes = sensor.migrate_to_version(1).unwrap();
//! let v1_roundtrip: serde_json::Value = serde_json::from_slice(&v1_bytes).unwrap();
//! assert_eq!(v1_roundtrip["temp"], 22.5);
//! ```
use crate::SchemaType;
/// Error returned when schema migration fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MigrationError {
/// The source version is newer than this binary supports
VersionTooNew { source: u32, current: u32 },
/// The target downgrade version is below the minimum supported
VersionTooOld { target: u32, minimum: u32 },
/// Deserialization of a versioned payload failed
DeserializationFailed(&'static str),
/// Serialization during downgrade failed
SerializationFailed(&'static str),
/// A domain-specific conversion error in a MigrationStep
ConversionFailed(&'static str),
/// Payload is missing the version field
MissingVersion,
}
impl core::fmt::Display for MigrationError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::VersionTooNew { source, current } => {
write!(
f,
"source version {} is newer than current {}",
source, current
)
}
Self::VersionTooOld { target, minimum } => {
write!(
f,
"target version {} is below minimum supported {}",
target, minimum
)
}
Self::DeserializationFailed(msg) => write!(f, "deserialization failed: {}", msg),
Self::SerializationFailed(msg) => write!(f, "serialization failed: {}", msg),
Self::ConversionFailed(msg) => write!(f, "conversion failed: {}", msg),
Self::MissingVersion => write!(f, "payload missing version field"),
}
}
}
/// A single, typed, bidirectional migration step between two schema versions.
///
/// Each step converts between two concrete Rust types with full type safety.
/// The compiler enforces that `up()` and `down()` operate on the correct types.
///
/// # Example
///
/// ```rust
/// # use aimdb_data_contracts::{MigrationError, MigrationStep};
/// # struct TemperatureV1 { schema_version: u32, temp: f64, timestamp: u64, unit: String }
/// # struct TemperatureV2 { schema_version: u32, celsius: f64, timestamp: u64 }
/// struct TemperatureV1ToV2;
/// impl MigrationStep for TemperatureV1ToV2 {
/// type Older = TemperatureV1;
/// type Newer = TemperatureV2;
/// const FROM_VERSION: u32 = 1;
/// const TO_VERSION: u32 = 2;
///
/// fn up(v1: TemperatureV1) -> Result<TemperatureV2, MigrationError> {
/// let celsius = match v1.unit.as_str() {
/// "F" => (v1.temp - 32.0) * 5.0 / 9.0,
/// "K" => v1.temp - 273.15,
/// _ => v1.temp,
/// };
/// Ok(TemperatureV2 { schema_version: 2, celsius, timestamp: v1.timestamp })
/// }
/// fn down(v2: TemperatureV2) -> Result<TemperatureV1, MigrationError> {
/// Ok(TemperatureV1 { schema_version: 1, temp: v2.celsius, timestamp: v2.timestamp, unit: "C".into() })
/// }
/// }
/// ```
pub trait MigrationStep {
/// The older schema type (input to `up`, output of `down`)
type Older;
/// The newer schema type (output of `up`, input to `down`)
type Newer;
/// The version number of the Older type
const FROM_VERSION: u32;
/// The version number of the Newer type
const TO_VERSION: u32;
/// Upgrade: convert from older to newer representation.
fn up(older: Self::Older) -> Result<Self::Newer, MigrationError>;
/// Downgrade: convert from newer to older representation.
fn down(newer: Self::Newer) -> Result<Self::Older, MigrationError>;
}
/// A complete, validated migration chain for a schema type.
///
/// Generated by the `migration_chain!` macro. Provides runtime dispatch
/// for upgrading from any historical version to the current version,
/// and downgrading from the current version to any historical version.
///
/// All chain validation (sequential versions, type chaining) happens
/// at compile time via const assertions and type checking in the macro expansion.
pub trait MigrationChain: SchemaType + serde::de::DeserializeOwned + serde::Serialize {
/// The minimum version this chain can upgrade from.
const MIN_VERSION: u32;
/// Deserialize from bytes, auto-detecting version and upgrading to current.
///
/// Reads the version field from the JSON payload and walks the migration
/// chain upward to produce the current schema version.
fn migrate_from_bytes(data: &[u8]) -> Result<Self, MigrationError>;
/// Downgrade to a target version and serialize to bytes.
///
/// Walks the migration chain downward from the current version to produce
/// the serialized representation of an older schema version.
fn migrate_to_version(
&self,
target_version: u32,
) -> Result<alloc::vec::Vec<u8>, MigrationError>;
}
/// Compile-only proof that `migration_chain!` arity is unbounded — a 4-step
/// chain (5 schema versions), not itself a test. Runtime correctness for
/// chains beyond the historical 3-step ceiling is proven on host by
/// `tests/migration_roundtrip.rs`; this module exists purely so the
/// `thumbv7em-none-eabihf` check lane (which can't compile `tests/*.rs` —
/// no `std` test harness on a bare-metal target) still exercises a >3-step
/// chain. Lives inside this crate (not `tests/`), so it needs
/// `extern crate self as aimdb_data_contracts;` (see `lib.rs`) for the
/// macro's generated `::aimdb_data_contracts::...` absolute paths to
/// resolve.
#[allow(dead_code)]
mod arity_check {
use crate::{MigrationError, MigrationStep, SchemaType};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
struct V1 {
schema_version: u32,
n: u32,
}
impl SchemaType for V1 {
const NAME: &'static str = "arity_check";
const VERSION: u32 = 1;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct V2 {
schema_version: u32,
n: u32,
}
impl SchemaType for V2 {
const NAME: &'static str = "arity_check";
const VERSION: u32 = 2;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct V3 {
schema_version: u32,
n: u32,
}
impl SchemaType for V3 {
const NAME: &'static str = "arity_check";
const VERSION: u32 = 3;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct V4 {
schema_version: u32,
n: u32,
}
impl SchemaType for V4 {
const NAME: &'static str = "arity_check";
const VERSION: u32 = 4;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct V5 {
schema_version: u32,
n: u32,
}
impl SchemaType for V5 {
const NAME: &'static str = "arity_check";
const VERSION: u32 = 5;
}
struct Step1;
impl MigrationStep for Step1 {
type Older = V1;
type Newer = V2;
const FROM_VERSION: u32 = 1;
const TO_VERSION: u32 = 2;
fn up(v: V1) -> Result<V2, MigrationError> {
Ok(V2 {
schema_version: 2,
n: v.n,
})
}
fn down(v: V2) -> Result<V1, MigrationError> {
Ok(V1 {
schema_version: 1,
n: v.n,
})
}
}
struct Step2;
impl MigrationStep for Step2 {
type Older = V2;
type Newer = V3;
const FROM_VERSION: u32 = 2;
const TO_VERSION: u32 = 3;
fn up(v: V2) -> Result<V3, MigrationError> {
Ok(V3 {
schema_version: 3,
n: v.n,
})
}
fn down(v: V3) -> Result<V2, MigrationError> {
Ok(V2 {
schema_version: 2,
n: v.n,
})
}
}
struct Step3;
impl MigrationStep for Step3 {
type Older = V3;
type Newer = V4;
const FROM_VERSION: u32 = 3;
const TO_VERSION: u32 = 4;
fn up(v: V3) -> Result<V4, MigrationError> {
Ok(V4 {
schema_version: 4,
n: v.n,
})
}
fn down(v: V4) -> Result<V3, MigrationError> {
Ok(V3 {
schema_version: 3,
n: v.n,
})
}
}
struct Step4;
impl MigrationStep for Step4 {
type Older = V4;
type Newer = V5;
const FROM_VERSION: u32 = 4;
const TO_VERSION: u32 = 5;
fn up(v: V4) -> Result<V5, MigrationError> {
Ok(V5 {
schema_version: 5,
n: v.n,
})
}
fn down(v: V5) -> Result<V4, MigrationError> {
Ok(V4 {
schema_version: 4,
n: v.n,
})
}
}
crate::migration_chain! {
type Current = V5;
version_field = "schema_version";
steps {
Step1: V1 => V2,
Step2: V2 => V3,
Step3: V3 => V4,
Step4: V4 => V5,
}
}
}