aboutsummaryrefslogtreecommitdiff
path: root/base/src/database.rs
blob: 2a57937598a8b4fba599407f7d0c7a27b3b0d8d0 (plain)
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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2023 metamuffin <metamuffin.org>
*/
use bincode::{Decode, Encode};
use jellycommon::{
    user::{NodeUserData, User},
    Node,
};
use log::info;
use std::{borrow::Borrow, ops::Deref, path::Path};

pub use redb::*;

pub const T_USER: TableDefinition<&str, Ser<User>> = TableDefinition::new("user");
pub const T_USER_NODE: TableDefinition<(&str, &str), Ser<NodeUserData>> =
    TableDefinition::new("user_node");
pub const T_INVITE: TableDefinition<&str, Ser<()>> = TableDefinition::new("invite");
pub const T_NODE: TableDefinition<&str, Ser<Node>> = TableDefinition::new("node");
pub const T_NODE_IMPORT: TableDefinition<&str, Ser<Vec<(Vec<usize>, Node)>>> =
    TableDefinition::new("node_import");

pub struct DataAcid {
    pub inner: redb::Database,
}

impl DataAcid {
    pub fn open(path: &Path) -> Result<Self, anyhow::Error> {
        info!("database");
        let db = redb::Database::create(path)?;
        let r = Self { inner: db };

        {
            let txn = r.begin_write()?;
            drop(txn.open_table(T_INVITE)?);
            drop(txn.open_table(T_USER)?);
            drop(txn.open_table(T_USER_NODE)?);
            drop(txn.open_table(T_NODE)?);
            drop(txn.open_table(T_NODE_IMPORT)?);
            txn.commit()?;
        }

        info!("ready");
        Ok(r)
    }
}

impl Deref for DataAcid {
    type Target = Database;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

pub trait TableExt<Key, KeyRef, Value> {
    fn get(self, db: &DataAcid, key: KeyRef) -> anyhow::Result<Option<Value>>;
    fn insert(self, db: &DataAcid, key: KeyRef, value: Value) -> anyhow::Result<()>;
    fn remove(self, db: &DataAcid, key: KeyRef) -> anyhow::Result<Option<Value>>;
}
impl<'a, 'b, 'c, Key, Value, KeyRef> TableExt<Key, KeyRef, Value>
    for TableDefinition<'a, Key, Ser<Value>>
where
    Key: Borrow<<Key as RedbValue>::SelfType<'b>> + redb::RedbKey,
    Value: bincode::Encode + bincode::Decode + std::fmt::Debug,
    KeyRef: Borrow<<Key as redb::RedbValue>::SelfType<'c>>,
{
    fn get(self, db: &DataAcid, key: KeyRef) -> anyhow::Result<Option<Value>> {
        let txn = db.inner.begin_read()?;
        let table = txn.open_table(self)?;
        let user = table.get(key)?.map(|v| v.value().0);
        drop(table);
        Ok(user)
    }
    fn insert(self, db: &DataAcid, key: KeyRef, value: Value) -> anyhow::Result<()> {
        let txn = db.inner.begin_write()?;
        let mut table = txn.open_table(self)?;
        table.insert(key, Ser(value))?;
        drop(table);
        txn.commit()?;
        Ok(())
    }
    fn remove(self, db: &DataAcid, key: KeyRef) -> anyhow::Result<Option<Value>> {
        let txn = db.inner.begin_write()?;
        let mut table = txn.open_table(self)?;
        let prev = table.remove(key)?.map(|v| v.value().0);
        drop(table);
        txn.commit()?;
        Ok(prev)
    }
}

// pub trait TableIterExt<
//     'a,
//     Key: redb::RedbKey + 'static,
//     Value: redb::RedbValue + 'static,
//     F: FnOnce(&redb::Range<'a, Key, Value>) -> anyhow::Result<T>,
//     T: 'static,
// >
// {
//     fn iter(self, db: &'a DataAcid, f: F) -> anyhow::Result<T>;
// }
// impl<'a, Key, Value, F, T> TableIterExt<'a, Key, Value, F, T>
//     for TableDefinition<'static, Key, Value>
// where
//     Key: redb::RedbKey,
//     Value: redb::RedbValue,
//     F: FnOnce(&redb::Range<'a, Key, Value>) -> anyhow::Result<T>,
//     T: 'static,
// {
//     fn iter(self, db: &DataAcid, f: F) -> anyhow::Result<T> {
//         let txn = db.begin_read()?;
//         let table = txn.open_table(self)?;
//         let iter = table.iter()?;
//         let ret = f(&iter)?;
//         drop(iter);
//         drop(table);
//         drop(txn);
//         Ok(ret)
//     }
// }

#[derive(Debug)]
#[cfg(not(feature = "db_json"))]
pub struct Ser<T>(pub T);
#[cfg(not(feature = "db_json"))]
impl<T: Encode + Decode + std::fmt::Debug> RedbValue for Ser<T> {
    type SelfType<'a> = Ser<T>
    where
        Self: 'a;
    type AsBytes<'a> = Vec<u8>
    where
        Self: 'a;

    fn fixed_width() -> Option<usize> {
        None
    }

    fn from_bytes<'a>(data: &'a [u8]) -> Self::SelfType<'a>
    where
        Self: 'a,
    {
        Ser(bincode::decode_from_slice(data, bincode::config::legacy())
            .unwrap()
            .0)
    }

    fn as_bytes<'a, 'b: 'a>(value: &'a Self::SelfType<'b>) -> Self::AsBytes<'a>
    where
        Self: 'a,
        Self: 'b,
    {
        bincode::encode_to_vec(&value.0, bincode::config::legacy()).unwrap()
    }

    fn type_name() -> redb::TypeName {
        TypeName::new("bincode")
    }
}

#[derive(Debug)]
#[cfg(feature = "db_json")]
pub struct Ser<T>(pub T);
#[cfg(feature = "db_json")]
impl<T: Serialize + for<'a> Deserialize<'a> + std::fmt::Debug> RedbValue for Ser<T> {
    type SelfType<'a> = Ser<T>
    where
        Self: 'a;
    type AsBytes<'a> = Vec<u8>
    where
        Self: 'a;

    fn fixed_width() -> Option<usize> {
        None
    }

    fn from_bytes<'a>(data: &'a [u8]) -> Self::SelfType<'a>
    where
        Self: 'a,
    {
        Ser(serde_json::from_slice(data).unwrap())
    }

    fn as_bytes<'a, 'b: 'a>(value: &'a Self::SelfType<'b>) -> Self::AsBytes<'a>
    where
        Self: 'a,
        Self: 'b,
    {
        serde_json::to_vec(&value.0).unwrap()
    }

    fn type_name() -> redb::TypeName {
        TypeName::new("json")
    }
}