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
use microkv::namespace::NamespaceMicroKV;
use microkv::MicroKV;
use support_common::error::BridgerError;
mod v0;
mod v1;
mod v2;
mod v3;
type MigrationStep = Vec<Box<dyn Fn(&MicroKV) -> color_eyre::Result<()>>>;
pub fn migrate(microkv: &MicroKV, version: usize) -> color_eyre::Result<()> {
let saved_version = current_version(microkv)?;
if saved_version == version {
return Ok(());
}
let steps: MigrationStep = vec![
Box::new(v0::migrate),
Box::new(v1::migrate),
Box::new(v2::migrate),
Box::new(v3::migrate),
];
let max_version = steps.len() - 1;
if version > max_version {
return Err(BridgerError::Migration(format!(
"Support max version: {}, but want upgrade to {}.",
max_version, version
))
.into());
}
let from = if saved_version == 0 {
0
} else {
saved_version + 1
};
let to = version + 1;
for ix in from..to {
let migration = steps.get(ix).unwrap();
if let Err(e) = migration(microkv) {
return Err(BridgerError::Migration(format!(
"Failed to migrate. step [{}]: {:?}",
ix, e
))
.into());
}
}
flush_version(microkv, version)?;
Ok(())
}
fn current_version(microkv: &MicroKV) -> color_eyre::Result<usize> {
let n_microkv = better_namespace_kv(microkv)?;
let version: Option<usize> = n_microkv.get_as(".version")?;
Ok(version.unwrap_or(0))
}
fn flush_version(microkv: &MicroKV, version: usize) -> color_eyre::Result<()> {
let n_microkv = better_namespace_kv(microkv)?;
n_microkv.put(".version", &version)?;
Ok(())
}
fn better_namespace_kv(microkv: &MicroKV) -> color_eyre::Result<NamespaceMicroKV> {
let nss = microkv.namespaces()?;
if let Some(old) = nss.iter().find(|&ns| &ns[..] == "task-pangolin-ropsten") {
Ok(microkv.namespace(old))
} else {
Ok(microkv.namespace("pangolin-ropsten"))
}
}