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
use serde::de::DeserializeOwned;
use serde::Serialize;

use cosmwasm_std::{StdError, StdResult, Storage};

use crate::namespace::Namespace;
use crate::snapshot::{ChangeSet, Snapshot};
use crate::{Item, Map, Strategy};

/// Item that maintains a snapshot of one or more checkpoints.
/// We can query historical data as well as current state.
/// What data is snapshotted depends on the Strategy.
pub struct SnapshotItem<T> {
    primary: Item<T>,
    changelog_namespace: Namespace,
    snapshots: Snapshot<(), T>,
}

impl<T> SnapshotItem<T> {
    /// Creates a new [`SnapshotItem`] with the given storage keys and strategy.
    /// This is a const fn only suitable when all the storage keys provided are
    /// static strings.
    ///
    /// Example:
    ///
    /// ```rust
    /// use cw_storage_plus::{SnapshotItem, Strategy};
    ///
    /// SnapshotItem::<u64>::new(
    ///     "every",
    ///     "every__check",
    ///     "every__change",
    ///     Strategy::EveryBlock);
    /// ```
    pub const fn new(
        storage_key: &'static str,
        checkpoints: &'static str,
        changelog: &'static str,
        strategy: Strategy,
    ) -> Self {
        SnapshotItem {
            primary: Item::new(storage_key),
            changelog_namespace: Namespace::from_static_str(changelog),
            snapshots: Snapshot::new(checkpoints, changelog, strategy),
        }
    }

    /// Creates a new [`SnapshotItem`] with the given storage keys and strategy.
    /// Use this if you might need to handle dynamic strings. Otherwise, you might
    /// prefer [`SnapshotItem::new`].
    ///
    /// Example:
    ///
    /// ```rust
    /// use cw_storage_plus::{SnapshotItem, Strategy};
    ///
    /// let key = "every";
    /// let checkpoints_key = format!("{}_check", key);
    /// let changelog_key = format!("{}_change", key);
    ///
    /// SnapshotItem::<u64>::new_dyn(
    ///     key,
    ///     checkpoints_key,
    ///     changelog_key,
    ///     Strategy::EveryBlock);
    /// ```
    pub fn new_dyn(
        storage_key: impl Into<Namespace>,
        checkpoints: impl Into<Namespace>,
        changelog: impl Into<Namespace>,
        strategy: Strategy,
    ) -> Self {
        let changelog = changelog.into();
        SnapshotItem {
            primary: Item::new_dyn(storage_key),
            changelog_namespace: changelog.clone(),
            snapshots: Snapshot::new_dyn(checkpoints, changelog, strategy),
        }
    }

    pub fn add_checkpoint(&self, store: &mut dyn Storage, height: u64) -> StdResult<()> {
        self.snapshots.add_checkpoint(store, height)
    }

    pub fn remove_checkpoint(&self, store: &mut dyn Storage, height: u64) -> StdResult<()> {
        self.snapshots.remove_checkpoint(store, height)
    }

    pub fn changelog(&self) -> Map<u64, ChangeSet<T>> {
        // Build and return a compatible Map with the proper key type
        Map::new_dyn(self.changelog_namespace.clone())
    }
}

impl<T> SnapshotItem<T>
where
    T: Serialize + DeserializeOwned + Clone,
{
    /// load old value and store changelog
    fn write_change(&self, store: &mut dyn Storage, height: u64) -> StdResult<()> {
        // if there is already data in the changelog for this block, do not write more
        if self.snapshots.has_changelog(store, (), height)? {
            return Ok(());
        }
        // otherwise, store the previous value
        let old = self.primary.may_load(store)?;
        self.snapshots.write_changelog(store, (), height, old)
    }

    pub fn save(&self, store: &mut dyn Storage, data: &T, height: u64) -> StdResult<()> {
        if self.snapshots.should_checkpoint(store, &())? {
            self.write_change(store, height)?;
        }
        self.primary.save(store, data)
    }

    pub fn remove(&self, store: &mut dyn Storage, height: u64) -> StdResult<()> {
        if self.snapshots.should_checkpoint(store, &())? {
            self.write_change(store, height)?;
        }
        self.primary.remove(store);
        Ok(())
    }

    /// load will return an error if no data is set, or on parse error
    pub fn load(&self, store: &dyn Storage) -> StdResult<T> {
        self.primary.load(store)
    }

    /// may_load will parse the data stored if present, returns Ok(None) if no data there.
    /// returns an error on parsing issues
    pub fn may_load(&self, store: &dyn Storage) -> StdResult<Option<T>> {
        self.primary.may_load(store)
    }

    pub fn may_load_at_height(&self, store: &dyn Storage, height: u64) -> StdResult<Option<T>> {
        let snapshot = self.snapshots.may_load_at_height(store, (), height)?;

        if let Some(r) = snapshot {
            Ok(r)
        } else {
            // otherwise, return current value
            self.may_load(store)
        }
    }

    // If there is no checkpoint for that height, then we return StdError::NotFound
    pub fn assert_checkpointed(&self, store: &dyn Storage, height: u64) -> StdResult<()> {
        self.snapshots.assert_checkpointed(store, height)
    }

    /// Loads the data, perform the specified action, and store the result in the database.
    /// This is a shorthand for some common sequences, which may be useful.
    ///
    /// If the data exists, `action(Some(value))` is called. Otherwise `action(None)` is called.
    ///
    /// This is a bit more customized than needed to only read "old" value 1 time, not 2 per naive approach
    pub fn update<A, E>(&self, store: &mut dyn Storage, height: u64, action: A) -> Result<T, E>
    where
        A: FnOnce(Option<T>) -> Result<T, E>,
        E: From<StdError>,
    {
        let input = self.may_load(store)?;
        let output = action(input)?;
        self.save(store, &output, height)?;
        Ok(output)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bound::Bound;
    use cosmwasm_std::testing::MockStorage;

    type TestItem = SnapshotItem<u64>;

    const NEVER: TestItem =
        SnapshotItem::new("never", "never__check", "never__change", Strategy::Never);
    const EVERY: TestItem = SnapshotItem::new(
        "every",
        "every__check",
        "every__change",
        Strategy::EveryBlock,
    );
    const SELECT: TestItem = SnapshotItem::new(
        "select",
        "select__check",
        "select__change",
        Strategy::Selected,
    );

    // Fills an item (u64) with the following writes:
    // 1: 5
    // 2: 7
    // 3: 8
    // 4: 1
    // 5: None
    // 6: 13
    // 7: None
    // 8: 22
    // Final value: 22
    // Value at beginning of 3 -> 7
    // Value at beginning of 5 -> 1
    fn init_data(item: &TestItem, storage: &mut dyn Storage) {
        item.save(storage, &5, 1).unwrap();
        item.save(storage, &7, 2).unwrap();

        // checkpoint 3
        item.add_checkpoint(storage, 3).unwrap();

        // also use update to set - to ensure this works
        item.save(storage, &1, 3).unwrap();
        item.update(storage, 3, |_| -> StdResult<u64> { Ok(8) })
            .unwrap();

        item.remove(storage, 4).unwrap();
        item.save(storage, &13, 4).unwrap();

        // checkpoint 5
        item.add_checkpoint(storage, 5).unwrap();
        item.remove(storage, 5).unwrap();
        item.update(storage, 5, |_| -> StdResult<u64> { Ok(22) })
            .unwrap();
        // and delete it later (unknown if all data present)
        item.remove_checkpoint(storage, 5).unwrap();
    }

    const FINAL_VALUE: Option<u64> = Some(22);

    const VALUE_START_3: Option<u64> = Some(7);

    const VALUE_START_5: Option<u64> = Some(13);

    fn assert_final_value(item: &TestItem, storage: &dyn Storage) {
        assert_eq!(FINAL_VALUE, item.may_load(storage).unwrap());
    }

    #[track_caller]
    fn assert_value_at_height(
        item: &TestItem,
        storage: &dyn Storage,
        height: u64,
        value: Option<u64>,
    ) {
        assert_eq!(value, item.may_load_at_height(storage, height).unwrap());
    }

    fn assert_missing_checkpoint(item: &TestItem, storage: &dyn Storage, height: u64) {
        assert!(item.may_load_at_height(storage, height).is_err());
    }

    #[test]
    fn never_works_like_normal_item() {
        let mut storage = MockStorage::new();
        init_data(&NEVER, &mut storage);
        assert_final_value(&NEVER, &storage);

        // historical queries return error
        assert_missing_checkpoint(&NEVER, &storage, 3);
        assert_missing_checkpoint(&NEVER, &storage, 5);
    }

    #[test]
    fn every_blocks_stores_present_and_past() {
        let mut storage = MockStorage::new();
        init_data(&EVERY, &mut storage);
        assert_final_value(&EVERY, &storage);

        // historical queries return historical values
        assert_value_at_height(&EVERY, &storage, 3, VALUE_START_3);
        assert_value_at_height(&EVERY, &storage, 5, VALUE_START_5);
    }

    #[test]
    fn selected_shows_3_not_5() {
        let mut storage = MockStorage::new();
        init_data(&SELECT, &mut storage);
        assert_final_value(&SELECT, &storage);

        // historical queries return historical values
        assert_value_at_height(&SELECT, &storage, 3, VALUE_START_3);
        // never checkpointed
        assert_missing_checkpoint(&NEVER, &storage, 1);
        // deleted checkpoint
        assert_missing_checkpoint(&NEVER, &storage, 5);
    }

    #[test]
    fn handle_multiple_writes_in_one_block() {
        let mut storage = MockStorage::new();

        println!("SETUP");
        EVERY.save(&mut storage, &5, 1).unwrap();
        EVERY.save(&mut storage, &7, 2).unwrap();
        EVERY.save(&mut storage, &2, 2).unwrap();

        // update and save - query at 3 => 2, at 4 => 12
        EVERY
            .update(&mut storage, 3, |_| -> StdResult<u64> { Ok(9) })
            .unwrap();
        EVERY.save(&mut storage, &12, 3).unwrap();
        assert_eq!(Some(5), EVERY.may_load_at_height(&storage, 2).unwrap());
        assert_eq!(Some(2), EVERY.may_load_at_height(&storage, 3).unwrap());
        assert_eq!(Some(12), EVERY.may_load_at_height(&storage, 4).unwrap());

        // save and remove - query at 4 => 1, at 5 => None
        EVERY.save(&mut storage, &17, 4).unwrap();
        EVERY.remove(&mut storage, 4).unwrap();
        assert_eq!(Some(12), EVERY.may_load_at_height(&storage, 4).unwrap());
        assert_eq!(None, EVERY.may_load_at_height(&storage, 5).unwrap());

        // remove and update - query at 5 => 2, at 6 => 13
        EVERY.remove(&mut storage, 5).unwrap();
        EVERY
            .update(&mut storage, 5, |_| -> StdResult<u64> { Ok(2) })
            .unwrap();
        assert_eq!(None, EVERY.may_load_at_height(&storage, 5).unwrap());
        assert_eq!(Some(2), EVERY.may_load_at_height(&storage, 6).unwrap());
    }

    #[test]
    #[cfg(feature = "iterator")]
    fn changelog_range_works() {
        use cosmwasm_std::Order;

        let mut store = MockStorage::new();

        // simple data for testing
        EVERY.save(&mut store, &5, 1u64).unwrap();
        EVERY.save(&mut store, &7, 2u64).unwrap();
        EVERY
            .update(&mut store, 3u64, |_| -> StdResult<u64> { Ok(8) })
            .unwrap();
        EVERY.remove(&mut store, 4u64).unwrap();

        // let's try to iterate over the changelog
        let all: StdResult<Vec<_>> = EVERY
            .changelog()
            .range(&store, None, None, Order::Ascending)
            .collect();
        let all = all.unwrap();
        assert_eq!(4, all.len());
        assert_eq!(
            all,
            vec![
                (1, ChangeSet { old: None }),
                (2, ChangeSet { old: Some(5) }),
                (3, ChangeSet { old: Some(7) }),
                (4, ChangeSet { old: Some(8) })
            ]
        );

        // let's try to iterate over a changelog range
        let all: StdResult<Vec<_>> = EVERY
            .changelog()
            .range(&store, Some(Bound::exclusive(3u64)), None, Order::Ascending)
            .collect();
        let all = all.unwrap();
        assert_eq!(1, all.len());
        assert_eq!(all, vec![(4, ChangeSet { old: Some(8) }),]);
    }
}