1mod filesystem;
2mod inmemory;
3
4use directip::Message;
5use filesystem::FileSystemStorage;
6use inmemory::VolatileStorage;
7
8#[cfg(feature = "sqlite")]
10mod sqlite;
11
12trait Storage {
13 }
16
17enum Database {
18 M(VolatileStorage),
19 F(FileSystemStorage),
20 #[cfg(feature = "sqlite")]
21 L(sqlite::SQLiteStorage),
22}
23
24impl Database {
25 pub async fn open(cfg: &str) -> Result<Self, Box<dyn std::error::Error>> {
26 if (&cfg.len() >= &(11 as usize)) && (cfg[..11] == "volatile://".to_string()) {
27 Ok(Database::M(VolatileStorage::connect()?))
28 } else if (&cfg.len() >= &(13 as usize)) && (cfg[..13] == "filesystem://".to_string()) {
29 Ok(Database::F(FileSystemStorage::connect()?))
30 } else if cfg[..9] == "sqlite://".to_string() {
31 #[cfg(feature = "sqlite")]
32 {
33 let db = crate::sqlite::SQLiteStorage::connect().await;
34 Ok(Database::L(db))
35 }
36 #[cfg(not(feature = "sqlite"))]
37 unimplemented!("Missing sqlite feature")
38 } else {
39 unimplemented!("Unknown storage")
40 }
41 }
47
48 pub async fn save(&self, msg: Message) {
49 match self {
50 Database::M(s) => s.save(msg).await,
51 Database::F(s) => s.save(msg).await,
52 #[cfg(feature = "sqlite")]
53 Database::L(s) => s.save(msg).await,
54 _ => todo!(),
55 }
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::Database;
62
63 fn sample() -> directip::Message {
64 let msg = directip::mt::MTMessage::from_reader(
65 [
66 0x01, 0x00, 0x1c, 0x44, 0x00, 0x19, 0x00, 0x00, 0x27, 0x0f, 0x00, 0x01, 0x02, 0x03,
67 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0xff, 0xff, 0xff,
68 0xff, 0xff, 0xf5,
69 ]
70 .as_slice(),
71 );
72 directip::Message::MT(msg.unwrap())
73 }
74
75 #[tokio::test]
76 async fn volatile() {
77 let db = Database::open("volatile://").await.unwrap();
78 db.save(sample());
79 }
80
81 async fn filesystem() {
83 let db = Database::open("filesystem://").await.unwrap();
84 db.save(sample());
85 }
86
87 #[cfg(feature = "sqlite")]
88 #[tokio::test]
89 async fn open_sqlite() {
90 let db = Database::open("sqlite://").await.unwrap();
91 db.save(sample());
92 }
93}