diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index f563432..443fbe0 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -3,7 +3,24 @@ name = "server" version = "0.1.0" edition = "2024" +[features] +default = ["rcgen"] +rcgen = ["dep:rcgen"] + +[dev-dependencies] +tempfile = "3.27.0" + [dependencies] -common = { workspace = true, features = ["client"] } +common = { workspace = true, features = ["server"] } +rcgen = { version = "0.14.8", optional = true } tokio.workspace = true -quinn.workspace = true +quinn = { workspace = true, features = ["rustls-aws-lc-rs"] } +bitcode.workspace = true +rustls.workspace = true + +surrealdb = { version = "3.1.3", default-features = false, features = [ + "protocol-ws", + "rustls", + "kv-surrealkv", +] } +ulid = "1.2.1" diff --git a/crates/server/src/database_.rs b/crates/server/src/database_.rs new file mode 100644 index 0000000..843aa32 --- /dev/null +++ b/crates/server/src/database_.rs @@ -0,0 +1,81 @@ +use surrealdb::{ + Surreal, + engine::any::{self, Any}, + opt::auth::Root, +}; + +use crate::{ServerConfig, error::Error}; + +pub type DB = Surreal; + +pub const USER_TABLE: &str = "user"; +pub const COMMUNITY_TABLE: &str = "community"; +pub const MESSAGE_TABLE: &str = "message"; +pub const USER_COMMUNITY_TABLE: &str = "user_community"; + +pub async fn connect(server_config: &ServerConfig) -> Result { + let address = format!( + "{}://{}", + server_config.database_prefix, server_config.database_address + ); + let database_connection = any::connect(address).await?; + + database_connection + .use_ns(server_config.namespace.clone()) + .use_db(server_config.database.clone()) + .await?; + + if !server_config.username.is_empty() && !server_config.password.is_empty() { + database_connection + .signin(Root { + username: server_config.username.clone(), + password: server_config.password.clone(), + }) + .await?; + } + + Ok(database_connection) +} + +pub async fn migrate(database_connection: &DB) -> Result<(), Error> { + database_connection + .query(format!( + " + DEFINE TABLE IF NOT EXISTS {USER_TABLE} SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS username ON {USER_TABLE} TYPE string; + + DEFINE TABLE IF NOT EXISTS {COMMUNITY_TABLE} SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS community_name ON {COMMUNITY_TABLE} TYPE string; + + DEFINE TABLE IF NOT EXISTS {MESSAGE_TABLE} SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS community_id ON {MESSAGE_TABLE} TYPE record<{COMMUNITY_TABLE}>; + DEFINE FIELD IF NOT EXISTS user_id ON {MESSAGE_TABLE} TYPE record<{USER_TABLE}>; + DEFINE FIELD IF NOT EXISTS message_body ON {MESSAGE_TABLE} TYPE string; + DEFINE INDEX IF NOT EXISTS {MESSAGE_TABLE}_community_id ON {MESSAGE_TABLE} FIELDS community_id; + DEFINE INDEX IF NOT EXISTS {MESSAGE_TABLE}_user_id ON {MESSAGE_TABLE} FIELDS user_id; + + DEFINE TABLE IF NOT EXISTS {USER_COMMUNITY_TABLE} TYPE RELATION FROM {USER_TABLE} TO {COMMUNITY_TABLE} ENFORCED SCHEMAFULL; + DEFINE INDEX IF NOT EXISTS {USER_COMMUNITY_TABLE}_unique ON {USER_COMMUNITY_TABLE} FIELDS in, out UNIQUE + " + )) + .await? + .check()?; + + Ok(()) +} + +pub async fn health(database_connection: &DB) -> Result<(), Error> { + Ok(database_connection.health().await?) +} + +// pub fn user_record_id(key: impl Into) -> RecordId { +// RecordId::new(USER_TABLE, key) +// } + +// pub fn community_record_id(key: impl Into) -> RecordId { +// RecordId::new(COMMUNITY_TABLE, key) +// } + +// pub fn message_record_id(key: impl Into) -> RecordId { +// RecordId::new(MESSAGE_TABLE, key) +// } diff --git a/crates/server/src/error.rs b/crates/server/src/error.rs new file mode 100644 index 0000000..c331f3b --- /dev/null +++ b/crates/server/src/error.rs @@ -0,0 +1,98 @@ +use std::fmt::Display; + +pub mod database; + +#[derive(Debug)] +pub enum Error { + Common(common::error::Error), + Database(database::Error), +} + +impl std::error::Error for Error {} + +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Common(error_value) => error_value.fmt(f), + Error::Database(error_value) => error_value.fmt(f), + } + } +} + +impl From for Error { + fn from(value: common::error::Error) -> Self { + Self::Common(value) + } +} + +impl From for Error { + fn from(value: common::error::user::Error) -> Self { + Self::Common(value.into()) + } +} + +impl From for Error { + fn from(value: common::error::community::Error) -> Self { + Self::Common(value.into()) + } +} + +impl From for Error { + fn from(value: common::error::message::Error) -> Self { + Self::Common(value.into()) + } +} + +impl Into for Error { + fn into(self) -> common::error::Error { + match self { + Error::Common(error) => error, + Error::Database(error) => { + eprintln!("Error: Database | {}", error); + common::error::Error::Server + } + } + } +} + +impl From for Error { + fn from(value: database::Error) -> Self { + Self::Database(value) + } +} + +impl From for Error { + fn from(value: surrealdb::Error) -> Self { + database::Error::from(value).into() + } +} + +impl From for Error { + fn from(value: quinn::ConnectionError) -> Self { + Self::Common(common::error::network::Error::from(value).into()) + } +} + +impl From for Error { + fn from(value: quinn::ReadError) -> Self { + Self::Common(common::error::network::Error::from(value).into()) + } +} + +impl From for Error { + fn from(value: quinn::ReadToEndError) -> Self { + Self::Common(common::error::network::Error::from(value).into()) + } +} + +impl From for Error { + fn from(value: quinn::WriteError) -> Self { + Self::Common(common::error::network::Error::from(value).into()) + } +} + +impl From for Error { + fn from(value: bitcode::Error) -> Self { + Self::Common(common::error::decode::Error::from(value).into()) + } +} diff --git a/crates/server/src/error/database.rs b/crates/server/src/error/database.rs new file mode 100644 index 0000000..845f769 --- /dev/null +++ b/crates/server/src/error/database.rs @@ -0,0 +1,30 @@ +use std::fmt::Display; + +#[derive(Debug)] +pub enum Error { + Inner(surrealdb::Error), + Create, + Read, + Update, + Delete, +} + +impl std::error::Error for Error {} + +impl Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Inner(error) => write!(f, "{}", error), + Error::Create => write!(f, "Creating a record failed"), + Error::Read => write!(f, "Reading a record failed"), + Error::Update => write!(f, "Updating a record failed"), + Error::Delete => write!(f, "Deleting a record failed"), + } + } +} + +impl From for Error { + fn from(value: surrealdb::Error) -> Self { + Self::Inner(value) + } +} diff --git a/crates/server/src/test.rs b/crates/server/src/test.rs new file mode 100644 index 0000000..38e67f9 --- /dev/null +++ b/crates/server/src/test.rs @@ -0,0 +1,25 @@ +#[cfg(test)] +use crate::{ + ServerConfig, + database_::{self, DB}, +}; +use tempfile::TempDir; + +pub async fn get_database() -> (DB, TempDir) { + let temp_directory = TempDir::new().unwrap(); + + let server_config = ServerConfig { + database_prefix: "surrealkv".to_string(), + database_address: temp_directory.path().display().to_string(), + namespace: "yumush".to_string(), + database: "yumush".to_string(), + username: "".to_string(), + password: "".to_string(), + server_address: "127.0.0.1:2026".to_string(), + }; + + let database_connection = database_::connect(&server_config).await.unwrap(); + database_::migrate(&database_connection).await.unwrap(); + + (database_connection, temp_directory) +}