forge
Explore
Log in

Don't you dare go Hollow

Add surrealdb database layer

Browse files at this commit

adbd6fb9db96d604e3cb6c0a00c07b70fb1c4481Ahmet Kaan GümüşParent: aeaaada
  • feat
    • add surrealdb database layer
Show full message
✨ feat(server): add surrealdb database layer

Connect to SurrealDB through the any engine, define schemafull tables
with a relation-backed membership table and message indexes, and add
a tempdir-backed surrealkv helper for tests.
crates/server/Cargo.tomlmodified+19 -2
@@ -3,7 +3,24 @@ name = "server"
3 version = "0.1.0"3 version = "0.1.0"
4 edition = "2024"4 edition = "2024"
5 5
6+[features]
7+default = ["rcgen"]
8+rcgen = ["dep:rcgen"]
9+
10+[dev-dependencies]
11+tempfile = "3.27.0"
12+
6 [dependencies]13 [dependencies]
7-common = { workspace = true, features = ["client"] }14+common = { workspace = true, features = ["server"] }
15+rcgen = { version = "0.14.8", optional = true }
8 tokio.workspace = true16 tokio.workspace = true
9-quinn.workspace = true17+quinn = { workspace = true, features = ["rustls-aws-lc-rs"] }
18+bitcode.workspace = true
19+rustls.workspace = true
20+
21+surrealdb = { version = "3.1.3", default-features = false, features = [
22+ "protocol-ws",
23+ "rustls",
24+ "kv-surrealkv",
25+] }
26+ulid = "1.2.1"
crates/server/src/database_.rsadded+81 -0
@@ -0,0 +1,81 @@
1+use surrealdb::{
2+ Surreal,
3+ engine::any::{self, Any},
4+ opt::auth::Root,
5+};
6+
7+use crate::{ServerConfig, error::Error};
8+
9+pub type DB = Surreal<Any>;
10+
11+pub const USER_TABLE: &str = "user";
12+pub const COMMUNITY_TABLE: &str = "community";
13+pub const MESSAGE_TABLE: &str = "message";
14+pub const USER_COMMUNITY_TABLE: &str = "user_community";
15+
16+pub async fn connect(server_config: &ServerConfig) -> Result<DB, Error> {
17+ let address = format!(
18+ "{}://{}",
19+ server_config.database_prefix, server_config.database_address
20+ );
21+ let database_connection = any::connect(address).await?;
22+
23+ database_connection
24+ .use_ns(server_config.namespace.clone())
25+ .use_db(server_config.database.clone())
26+ .await?;
27+
28+ if !server_config.username.is_empty() && !server_config.password.is_empty() {
29+ database_connection
30+ .signin(Root {
31+ username: server_config.username.clone(),
32+ password: server_config.password.clone(),
33+ })
34+ .await?;
35+ }
36+
37+ Ok(database_connection)
38+}
39+
40+pub async fn migrate(database_connection: &DB) -> Result<(), Error> {
41+ database_connection
42+ .query(format!(
43+ "
44+ DEFINE TABLE IF NOT EXISTS {USER_TABLE} SCHEMAFULL;
45+ DEFINE FIELD IF NOT EXISTS username ON {USER_TABLE} TYPE string;
46+
47+ DEFINE TABLE IF NOT EXISTS {COMMUNITY_TABLE} SCHEMAFULL;
48+ DEFINE FIELD IF NOT EXISTS community_name ON {COMMUNITY_TABLE} TYPE string;
49+
50+ DEFINE TABLE IF NOT EXISTS {MESSAGE_TABLE} SCHEMAFULL;
51+ DEFINE FIELD IF NOT EXISTS community_id ON {MESSAGE_TABLE} TYPE record<{COMMUNITY_TABLE}>;
52+ DEFINE FIELD IF NOT EXISTS user_id ON {MESSAGE_TABLE} TYPE record<{USER_TABLE}>;
53+ DEFINE FIELD IF NOT EXISTS message_body ON {MESSAGE_TABLE} TYPE string;
54+ DEFINE INDEX IF NOT EXISTS {MESSAGE_TABLE}_community_id ON {MESSAGE_TABLE} FIELDS community_id;
55+ DEFINE INDEX IF NOT EXISTS {MESSAGE_TABLE}_user_id ON {MESSAGE_TABLE} FIELDS user_id;
56+
57+ DEFINE TABLE IF NOT EXISTS {USER_COMMUNITY_TABLE} TYPE RELATION FROM {USER_TABLE} TO {COMMUNITY_TABLE} ENFORCED SCHEMAFULL;
58+ DEFINE INDEX IF NOT EXISTS {USER_COMMUNITY_TABLE}_unique ON {USER_COMMUNITY_TABLE} FIELDS in, out UNIQUE
59+ "
60+ ))
61+ .await?
62+ .check()?;
63+
64+ Ok(())
65+}
66+
67+pub async fn health(database_connection: &DB) -> Result<(), Error> {
68+ Ok(database_connection.health().await?)
69+}
70+
71+// pub fn user_record_id(key: impl Into<RecordIdKey>) -> RecordId {
72+// RecordId::new(USER_TABLE, key)
73+// }
74+
75+// pub fn community_record_id(key: impl Into<RecordIdKey>) -> RecordId {
76+// RecordId::new(COMMUNITY_TABLE, key)
77+// }
78+
79+// pub fn message_record_id(key: impl Into<RecordIdKey>) -> RecordId {
80+// RecordId::new(MESSAGE_TABLE, key)
81+// }
crates/server/src/error.rsadded+98 -0
@@ -0,0 +1,98 @@
1+use std::fmt::Display;
2+
3+pub mod database;
4+
5+#[derive(Debug)]
6+pub enum Error {
7+ Common(common::error::Error),
8+ Database(database::Error),
9+}
10+
11+impl std::error::Error for Error {}
12+
13+impl Display for Error {
14+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15+ match self {
16+ Error::Common(error_value) => error_value.fmt(f),
17+ Error::Database(error_value) => error_value.fmt(f),
18+ }
19+ }
20+}
21+
22+impl From<common::error::Error> for Error {
23+ fn from(value: common::error::Error) -> Self {
24+ Self::Common(value)
25+ }
26+}
27+
28+impl From<common::error::user::Error> for Error {
29+ fn from(value: common::error::user::Error) -> Self {
30+ Self::Common(value.into())
31+ }
32+}
33+
34+impl From<common::error::community::Error> for Error {
35+ fn from(value: common::error::community::Error) -> Self {
36+ Self::Common(value.into())
37+ }
38+}
39+
40+impl From<common::error::message::Error> for Error {
41+ fn from(value: common::error::message::Error) -> Self {
42+ Self::Common(value.into())
43+ }
44+}
45+
46+impl Into<common::error::Error> for Error {
47+ fn into(self) -> common::error::Error {
48+ match self {
49+ Error::Common(error) => error,
50+ Error::Database(error) => {
51+ eprintln!("Error: Database | {}", error);
52+ common::error::Error::Server
53+ }
54+ }
55+ }
56+}
57+
58+impl From<database::Error> for Error {
59+ fn from(value: database::Error) -> Self {
60+ Self::Database(value)
61+ }
62+}
63+
64+impl From<surrealdb::Error> for Error {
65+ fn from(value: surrealdb::Error) -> Self {
66+ database::Error::from(value).into()
67+ }
68+}
69+
70+impl From<quinn::ConnectionError> for Error {
71+ fn from(value: quinn::ConnectionError) -> Self {
72+ Self::Common(common::error::network::Error::from(value).into())
73+ }
74+}
75+
76+impl From<quinn::ReadError> for Error {
77+ fn from(value: quinn::ReadError) -> Self {
78+ Self::Common(common::error::network::Error::from(value).into())
79+ }
80+}
81+
82+impl From<quinn::ReadToEndError> for Error {
83+ fn from(value: quinn::ReadToEndError) -> Self {
84+ Self::Common(common::error::network::Error::from(value).into())
85+ }
86+}
87+
88+impl From<quinn::WriteError> for Error {
89+ fn from(value: quinn::WriteError) -> Self {
90+ Self::Common(common::error::network::Error::from(value).into())
91+ }
92+}
93+
94+impl From<bitcode::Error> for Error {
95+ fn from(value: bitcode::Error) -> Self {
96+ Self::Common(common::error::decode::Error::from(value).into())
97+ }
98+}
crates/server/src/error/database.rsadded+30 -0
@@ -0,0 +1,30 @@
1+use std::fmt::Display;
2+
3+#[derive(Debug)]
4+pub enum Error {
5+ Inner(surrealdb::Error),
6+ Create,
7+ Read,
8+ Update,
9+ Delete,
10+}
11+
12+impl std::error::Error for Error {}
13+
14+impl Display for Error {
15+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16+ match self {
17+ Error::Inner(error) => write!(f, "{}", error),
18+ Error::Create => write!(f, "Creating a record failed"),
19+ Error::Read => write!(f, "Reading a record failed"),
20+ Error::Update => write!(f, "Updating a record failed"),
21+ Error::Delete => write!(f, "Deleting a record failed"),
22+ }
23+ }
24+}
25+
26+impl From<surrealdb::Error> for Error {
27+ fn from(value: surrealdb::Error) -> Self {
28+ Self::Inner(value)
29+ }
30+}
crates/server/src/test.rsadded+25 -0
@@ -0,0 +1,25 @@
1+#[cfg(test)]
2+use crate::{
3+ ServerConfig,
4+ database_::{self, DB},
5+};
6+use tempfile::TempDir;
7+
8+pub async fn get_database() -> (DB, TempDir) {
9+ let temp_directory = TempDir::new().unwrap();
10+
11+ let server_config = ServerConfig {
12+ database_prefix: "surrealkv".to_string(),
13+ database_address: temp_directory.path().display().to_string(),
14+ namespace: "yumush".to_string(),
15+ database: "yumush".to_string(),
16+ username: "".to_string(),
17+ password: "".to_string(),
18+ server_address: "127.0.0.1:2026".to_string(),
19+ };
20+
21+ let database_connection = database_::connect(&server_config).await.unwrap();
22+ database_::migrate(&database_connection).await.unwrap();
23+
24+ (database_connection, temp_directory)
25+}