use crate::error::RuntimeError;
use std::collections::HashMap;
pub type MigrationFn = fn(Vec<u8>) -> Vec<u8>;
pub struct MigrationRegistry {
migrations: HashMap<(String, String, String), MigrationFn>,
}
impl MigrationRegistry {
pub fn new() -> Self {
Self {
migrations: HashMap::new(),
}
}
pub fn register(&mut self, module: &str, from: &str, to: &str, f: MigrationFn) {
self.migrations
.insert((module.to_string(), from.to_string(), to.to_string()), f);
}
pub fn migrate(
&self,
module: &str,
from: &str,
to: &str,
state: Vec<u8>,
) -> Result<Vec<u8>, RuntimeError> {
if from == to {
return Ok(state);
}
if let Some(&f) =
self.migrations
.get(&(module.to_string(), from.to_string(), to.to_string()))
{
return Ok(f(state));
}
let all_versions: Vec<String> = self
.migrations
.keys()
.filter(|(m, f, _)| m == module && f == from)
.map(|(_, _, t)| t.clone())
.collect();
let mut current_state = state;
let mut current_version = from;
for target in &all_versions {
if target <= ¤t_version.to_string() || target > &to.to_string() {
continue;
}
if let Some(&f) = self.migrations.get(&(
module.to_string(),
current_version.to_string(),
target.clone(),
)) {
current_state = f(current_state);
current_version = target;
if current_version == to {
break;
}
}
}
if current_version == to {
Ok(current_state)
} else {
Err(RuntimeError::RuntimeStopped)
}
}
}
impl Default for MigrationRegistry {
fn default() -> Self {
Self::new()
}
}
pub trait StateMigration: Sized {
fn migrate_from(from_version: &str, state: Vec<u8>) -> Result<Self, RuntimeError>
where
Self: Sized;
}