From 745d97acfd4993b24cee153867b7d9bad0ea452f Mon Sep 17 00:00:00 2001 From: realaravinth Date: Tue, 2 Nov 2021 21:03:23 +0530 Subject: [PATCH] versioned migrations for cache --- src/data.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/data.rs b/src/data.rs index 56f38ac..a29bd11 100644 --- a/src/data.rs +++ b/src/data.rs @@ -19,10 +19,13 @@ use std::path::Path; use actix_web::web; use graphql_client::{reqwest::post_graphql, GraphQLQuery}; use reqwest::Client; +use serde::{Deserialize, Serialize}; use sled::{Db, Tree}; use crate::SETTINGS; +const CACHE_VERSION: usize = 1; + #[derive(Clone)] pub struct Data { pub client: Client, @@ -47,11 +50,31 @@ impl Data { let path = Path::new(SETTINGS.cache.as_ref().unwrap()).join("posts_cache"); let cache = sled::open(path).unwrap(); let posts = cache.open_tree("posts").unwrap(); - AppData::new(Self { + let res = Self { client: Client::new(), cache, posts, - }) + }; + res.migrate(); + + AppData::new(res) + } + + fn migrate(&self) { + const KEY: &str = "POST_CACHE_VERSION"; + let mut clean = true; + if let Ok(Some(v)) = self.posts.get(KEY) { + let version = bincode::deserialize::(&v[..]).unwrap(); + clean = !(version == CACHE_VERSION); + } + + if clean { + self.posts.clear().unwrap(); + self.posts.flush().unwrap(); + self.posts + .insert(KEY, bincode::serialize(&CACHE_VERSION).unwrap()) + .unwrap(); + } } pub async fn get_post(&self, id: &str) -> PostResp {