rustango_cms/block/migrate.rs
1//! Stepwise schema migration for block-stored JSON.
2//!
3//! When a block's [`crate::Block::version`] is bumped, every load
4//! comparing the *stored* version on a JSON entry to the *current*
5//! version triggers [`apply_migrations`], which walks each integer
6//! version between them calling [`crate::Block::migrate`] once per
7//! step. Authors write single-version-step migrators only; the
8//! framework chains them.
9//!
10//! ## Wire-format version
11//!
12//! The JSON envelope of a block entry stores `version: u32` next to
13//! `type` / `id` / `value` (explicit per-item versions beat
14//! implicit ones). Missing
15//! `version` is treated as `1` (the initial baseline).
16
17use serde_json::Value;
18
19use super::{Block, BlockError};
20
21/// Read the stored version off a `{type, id, value, version?}`
22/// envelope. Missing / non-integer falls back to `1` so legacy
23/// streams that pre-date version-stamping just sail through unchanged
24/// (their `migrate(1, …)` for blocks at v1 is a no-op).
25#[must_use]
26pub fn read_stored_version(envelope: &Value) -> u32 {
27 envelope
28 .get("version")
29 .and_then(Value::as_u64)
30 .map_or(1, |v| u32::try_from(v).unwrap_or(1))
31}
32
33/// Apply every step between `stored` and `block.version()` in order.
34/// Each step gets the previous step's output. Already-current values
35/// (or future values stored by a newer process) short-circuit.
36///
37/// # Errors
38/// First failing [`crate::Block::migrate`] short-circuits with
39/// [`BlockError::MigrateFailed`] carrying the offending step.
40pub fn apply_migrations<B: Block + ?Sized>(
41 block: &B,
42 stored: u32,
43 mut value: Value,
44) -> Result<Value, BlockError> {
45 let target = block.version();
46 if stored >= target {
47 // Already at-or-past current; nothing to do.
48 return Ok(value);
49 }
50 for step in stored..target {
51 value = block.migrate(step, value).map_err(|e| {
52 // Re-wrap into a step-aware error if the block returned a
53 // bare BlockError without context.
54 match e {
55 BlockError::MigrateFailed { .. } => e,
56 other => BlockError::MigrateFailed {
57 block_type: block.type_name().to_owned(),
58 from: step,
59 to: step + 1,
60 reason: other.to_string(),
61 },
62 }
63 })?;
64 }
65 Ok(value)
66}