forked from bitfinity-network/canister-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stable.rs
372 lines (331 loc) · 10.8 KB
/
stable.rs
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
367
368
369
370
371
372
#![deny(missing_docs)]
//! This module provides versioned data for stable storage.
//!
//! **IMPORTANT**: do note that it's not possible to store more than one type (and one instance of that type)
//! in stable storage. Any subsequent writes will overwrite what is currently stored.
//!
//! This library makes it possible to change the type that is serialized and written to stable storage.
//!
//! Versioning happens between types, not data.
//! This means that any data written to stable storage through the `write` function
//! will overwrite whatever data was stored there from before.
//!
//! To be able to read and write a struct from stable storage
//! using these functions, the struct needs to implement the [`Versioned`] trait
//! (which in turn requires [`Deserialize`] and [`CandidType`])
//!
//! The first four bytes written is the version number as a [`u32`],
//! the remaining bytes represent the struct.
//! ```text
//! 0 1 2 3 ...
//! +-+-+-+-+-+-+-+-+-+
//! |V|E|R|S| Struct |
//! +-+-+-+-+-+-+-+-+-+
//! ```
//!
//! ## Examples
//!
//! ### Creating a versioned struct
//! ```
//! use ic_storage::stable::Versioned;
//! use candid::CandidType;
//! use serde::Deserialize;
//!
//! #[derive(Debug, Deserialize, CandidType)]
//! struct First(usize, usize);
//!
//! impl Versioned for First {
//! type Previous = ();
//!
//! fn version() -> u32 { 1 }
//!
//! fn upgrade((): ()) -> Self {
//! First(0, 0)
//! }
//! }
//!
//! #[derive(Debug, Deserialize, CandidType)]
//! struct Second(String);
//!
//! impl Versioned for Second {
//! type Previous = First;
//!
//! fn version() -> u32 { 2 }
//!
//! fn upgrade(previous: Self::Previous) -> Self {
//! Second(format!("{}, {}", previous.0, previous.1))
//! }
//! }
//! ```
//!
//! ## Reading
//!
//! Read the latest implementation from stable memory.
//! If there is a previous version stored, this version will be upgraded.
//!
//! ```
//! use ic_storage::stable::{Versioned, read};
//! # use candid::CandidType;
//! # use serde::Deserialize;
//!
//! # #[derive(Debug, Deserialize, CandidType)]
//! # struct First(usize, usize);
//! # impl Versioned for First {
//! # type Previous = ();
//! # fn version() -> u32 { 1 }
//! # fn upgrade((): ()) -> Self {
//! # First(0, 0)
//! # }
//! # }
//! # #[derive(Debug, Deserialize, CandidType)]
//! # struct Second(String);
//! # impl Versioned for Second {
//! # type Previous = First;
//! # fn version() -> u32 { 2 }
//! # fn upgrade(previous: Self::Previous) -> Self {
//! # Self(format!("{}, {}", previous.0, previous.1))
//! # }
//! # }
//! // #[post_upgrade]
//! fn post_upgrade_canister() {
//! let second = read::<Second>().unwrap();
//! }
//!
//! ```
//!
//! ## Writing
//!
//! Write the current version to stable storage.
//!
//! ```
//! use ic_storage::stable::{Versioned, write};
//! # use candid::CandidType;
//! # use serde::Deserialize;
//!
//! # #[derive(Debug, Deserialize, CandidType)]
//! # struct First(usize, usize);
//! # impl Versioned for First {
//! # type Previous = ();
//! # fn version() -> u32 { 1 }
//! # fn upgrade((): ()) -> Self {
//! # First(0, 0)
//! # }
//! # }
//! # fn get_first() -> First { First(1, 2) }
//! // #[pre_upgrade]
//! fn pre_upgrade_canister() {
//! let first: First = get_first();
//! write(&first).unwrap();
//! }
//! ```
use std::mem::size_of;
use ic_exports::candid::de::IDLDeserialize;
use ic_exports::candid::ser::IDLBuilder;
use ic_exports::candid::types::CandidType;
#[cfg(target_family = "wasm")]
use ic_exports::ic_cdk::api::stable::{stable_bytes, stable_read, stable_size, StableWriter};
use serde::Deserialize;
#[cfg(not(target_family = "wasm"))]
use crate::testing::{stable_bytes, stable_read, stable_size, StableWriter};
use crate::{Error, Result};
const VERSION_SIZE: usize = size_of::<u32>();
/// Versioned data that can be written to, and read from stable storage.
pub trait Versioned: for<'de> Deserialize<'de> + CandidType {
/// The previous version of this data.
/// If there is no previous version specify a unit (`()`).
/// This is required until defaults for associated types are stable.
///
/// A unit has a version number of zero, and a `Previous` type of a unit,
/// which means it's not possible to upgrade a unit from anything but it self,
/// and calling `upgrade` will simply return `()`.
type Previous: Versioned;
/// The version of the data
fn version() -> u32 {
Self::Previous::version() + 1
}
/// Upgrade to this version from the previous version.
fn upgrade(previous: Self::Previous) -> Self;
}
// -----------------------------------------------------------------------------
// - Versioned implementation for a unit -
// This is useful for the first version of a struct,
// as we can set the `Previous` version of that implementation to a unit,
// since a unit can never have a version lower than zero.
//
// Trying to upgrade TO a unit (rather than FROM a unit) will panic!
// -----------------------------------------------------------------------------
impl Versioned for () {
type Previous = ();
fn version() -> u32 {
0
}
fn upgrade((): ()) -> Self {
panic!("It's not possible to upgrade to a unit, only from");
}
}
fn read_version() -> Result<u32> {
let mut version = [0u8; VERSION_SIZE];
if ((stable_size() << 16) as usize) < version.len() {
return Err(Error::InsufficientSpace);
}
stable_read(0, &mut version);
Ok(u32::from_ne_bytes(version))
}
/// Load a [`Versioned`] from stable storage.
pub fn read<T: Versioned>() -> Result<T> {
let version = read_version()?;
if T::version() < version {
return Err(Error::AttemptedDowngrade);
}
let bytes = stable_bytes();
let res = recursive_upgrade::<T>(version, &bytes[VERSION_SIZE..])?;
Ok(res)
}
/// Write a [`Versioned`] to stable storage.
/// This will overwrite anything that was previously stored, however
/// it is not allowed to write an older version than what is currently stored.
pub fn write<T: Versioned>(payload: &T) -> Result<()> {
let current_version = match read_version() {
Ok(v) => Some(v),
Err(Error::InsufficientSpace) => None,
Err(e) => return Err(e),
};
let version = T::version();
if let Some(current_version) = current_version {
if current_version > version {
return Err(Error::ExistingVersionIsNewer);
}
}
let mut writer = StableWriter::default();
// Write the version number to the first four bytes.
// There is no point in checking that the four bytes were actually
// written as one would normally do with with an `io::Write`,
// as the failure point lies in growing the stable storage,
// and the usize returned from the `write` call isn't actually the number
// of bytes written, but rather the size of the slice that was passed in.
writer.write(&version.to_ne_bytes())?;
// Serialize and write the `Versioned`
let mut serializer = IDLBuilder::new();
serializer.arg(payload)?.serialize(writer)?;
Ok(())
}
// -----------------------------------------------------------------------------
// - Recursively upgrade -
// Recursively upgrade a `Versioned`.
// -----------------------------------------------------------------------------
fn recursive_upgrade<T: Versioned>(version: u32, bytes: &[u8]) -> Result<T> {
if version == T::version() {
let mut de = IDLDeserialize::new(bytes)?;
let res = de.get_value()?;
Ok(res)
} else {
let val = recursive_upgrade::<T::Previous>(version, bytes)?;
Ok(T::upgrade(val))
}
}
#[cfg(test)]
mod test {
use candid::CandidType;
use super::*;
#[derive(Debug, CandidType, Deserialize)]
struct Version1(u32);
#[derive(Debug, CandidType, Deserialize)]
struct Version2(u32, u32);
#[derive(Debug, CandidType, Deserialize)]
struct Version3(u32, u32, u32);
impl Versioned for Version1 {
type Previous = ();
fn version() -> u32 {
1
}
fn upgrade(_: Self::Previous) -> Self {
Self(0)
}
}
impl Versioned for Version2 {
type Previous = Version1;
fn version() -> u32 {
2
}
fn upgrade(previous: Self::Previous) -> Self {
Self(previous.0, 5)
}
}
impl Versioned for Version3 {
type Previous = Version2;
fn version() -> u32 {
3
}
fn upgrade(previous: Self::Previous) -> Self {
Self(previous.0, previous.1, 900)
}
}
#[test]
fn upgrade_versions() {
let mut v1_bytes = vec![];
let mut serializer = IDLBuilder::new();
serializer
.arg(&Version1(1))
.unwrap()
.serialize(&mut v1_bytes)
.unwrap();
let v2 = super::recursive_upgrade::<Version2>(1, &v1_bytes).unwrap();
let Version2(a, b) = v2;
assert_eq!((a, b), (1, 5));
}
#[test]
fn upgrade_across_two_versions() {
let mut v1_bytes = vec![];
let mut serializer = IDLBuilder::new();
serializer
.arg(&Version1(1))
.unwrap()
.serialize(&mut v1_bytes)
.unwrap();
let v3 = super::recursive_upgrade::<Version3>(1, &v1_bytes).unwrap();
let Version3(a, b, c) = v3;
assert_eq!((a, b, c), (1, 5, 900));
}
#[test]
fn write_and_upgrade() {
let first = Version1(42);
write(&first).unwrap();
let Version2(a, b) = read::<Version2>().unwrap();
assert_eq!((a, b), (42, 5));
}
#[test]
#[should_panic(expected = "insufficient space available")]
fn try_read_unwritten() {
// Try to read when no version has ever been written
let err = read::<Version1>().unwrap_err();
panic!("{err}");
}
#[test]
fn try_to_downgrade() {
// Downgrading is not currently supported
let second = Version2(1, 2);
write(&second).unwrap();
let err = read::<Version1>().unwrap_err();
assert!(matches!(err, Error::AttemptedDowngrade))
}
#[test]
fn overwrite_current_version_with_current_version() {
let v1 = Version1(1);
write(&v1).unwrap();
let v1 = Version1(2);
write(&v1).unwrap();
let v1 = read::<Version1>().unwrap();
let actual = v1.0;
let expected = 2;
assert_eq!(expected, actual);
}
#[test]
#[should_panic(expected = "existing version is newer")]
fn write_an_older_version() {
// Write a version that is older than the one that
// currently exists in storage.
write(&Version2(0, 0)).unwrap();
let err = write(&Version1(1)).unwrap_err();
panic!("{err}");
}
}