kade_proto/cmd/
dump.rs

1use crate::prelude::*;
2
3use bytes::Bytes;
4use std::fs::File;
5use std::io::Write;
6use std::path::PathBuf;
7use tracing::{info, instrument};
8
9#[derive(Debug)]
10pub struct Dump {
11    path: PathBuf,
12}
13
14impl Dump {
15    pub fn new(path: PathBuf) -> Dump { Dump { path } }
16
17    pub fn parse_frames(parse: &mut Parse) -> crate::Result<Dump> {
18        let path = parse.next_string()?;
19        Ok(Dump { path: PathBuf::from(path) })
20    }
21
22    #[instrument(skip(self, db, dst))]
23    pub async fn apply(self, db: &Db, dst: &mut Connection) -> crate::Result<()> {
24        let serializable_state = db.dump();
25        let serialized = bincode::serialize(&serializable_state)?;
26
27        let mut file = File::create(&self.path)?;
28        file.write_all(&serialized)?;
29        info!("Database state dumped to {:?}", self.path);
30
31        let response = Frame::Simple("OK".to_string());
32        dst.write_frame(&response).await?;
33
34        Ok(())
35    }
36
37    pub fn into_frame(self) -> Frame {
38        let mut frame = Frame::array();
39        frame.push_bulk(Bytes::from("dump".as_bytes()));
40        frame.push_bulk(Bytes::from(self.path.to_string_lossy().into_owned()));
41        frame
42    }
43}