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
|
/*
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) 2024 metamuffin <metamuffin.org>
*/
use bincode::{Decode, Encode};
use jellycommon::{
user::{NodeUserData, User},
ExtendedNode, Node,
};
use log::info;
use serde::{Deserialize, Serialize};
use std::{borrow::Borrow, fs::create_dir_all, ops::Deref, path::Path};
use tantivy::{
schema::{Field, Schema, FAST, STORED, TEXT},
Index, IndexReader, ReloadPolicy,
};
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_EXTENDED: TableDefinition<&str, Ser<ExtendedNode>> =
TableDefinition::new("node-ext");
pub const T_NODE_IMPORT: TableDefinition<&str, Ser<Vec<(Vec<usize>, Node)>>> =
TableDefinition::new("node-import");
pub struct DataAcid {
pub inner: redb::Database,
pub ft_node: NodeFulltextIndex,
}
impl DataAcid {
pub fn open(path: &Path) -> Result<Self, anyhow::Error> {
info!("database");
let db = redb::Database::create(path.join("data"))?;
let ft_node = NodeFulltextIndex::new(path)?;
let r = Self { inner: db, ft_node };
{
// this creates all tables such that read operations on them do not fail.
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)?);
drop(txn.open_table(T_NODE_EXTENDED)?);
txn.commit()?;
}
info!("ready");
Ok(r)
}
}
impl Deref for DataAcid {
type Target = Database;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
pub struct NodeFulltextIndex {
pub schema: Schema,
pub reader: IndexReader,
pub id: Field,
pub title: Field,
pub description: Field,
pub index: Index,
}
impl NodeFulltextIndex {
fn new(path: &Path) -> anyhow::Result<Self> {
let mut schema = Schema::builder();
let id = schema.add_text_field("id", TEXT | STORED | FAST);
let title = schema.add_text_field("title", TEXT);
let description = schema.add_text_field("description", TEXT);
let schema = schema.build();
create_dir_all(path.join("node_fts_index"))?;
let index = Index::create_in_dir(path.join("node_fts_index"), schema.clone())?;
let reader = index
.reader_builder()
.reload_policy(ReloadPolicy::OnCommitWithDelay)
.try_into()?;
Ok(Self {
index,
reader,
schema,
id,
description,
title,
})
}
}
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: Encode + Decode + std::fmt::Debug + Serialize + for<'x> Deserialize<'x>,
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")
}
}
|