Change to sqlx, started send_message

This commit is contained in:
2024-06-28 23:22:57 -04:00
Unverified
parent 766dbcce0c
commit 422109b4b0
5 changed files with 100 additions and 66 deletions

1
server/.env Normal file
View File

@@ -0,0 +1 @@
DATABASE_URL=mysql://root:strong_password@localhost:3307/

View File

@@ -12,4 +12,6 @@ tracing = "0.1.40"
clap = { version = "4.5.7", features = ["derive"] } clap = { version = "4.5.7", features = ["derive"] }
serde = { version = "1.0.203", features = ["derive"] } serde = { version = "1.0.203", features = ["derive"] }
emojis = "0.6.2" emojis = "0.6.2"
surrealdb = "1.5.3" chrono = { version = "0.4.24", features = ["serde"] }
sqlx = { version = "0.7", features = [ "runtime-tokio", "tls-rustls", "mysql" ] }
dotenvy = "0.15"

View File

@@ -1,11 +1,10 @@
use std::env;
use std::future::Future; use std::future::Future;
use std::net::{IpAddr, Ipv6Addr}; use std::net::{IpAddr, Ipv6Addr};
use std::sync::Arc; use dotenvy::dotenv;
use futures::future::{self}; use futures::future::{self};
use futures::StreamExt; use futures::StreamExt;
use surrealdb::engine::remote::ws::Ws; use sqlx::mysql::MySqlPoolOptions;
use surrealdb::opt::auth::Root;
use surrealdb::Surreal;
use tarpc::{ use tarpc::{
server::{Channel}, server::{Channel},
tokio_serde::formats::Json, tokio_serde::formats::Json,
@@ -21,17 +20,47 @@ async fn spawn(fut: impl Future<Output = ()> + Send + 'static) {
#[tokio::main] #[tokio::main]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
// Connect to the server dotenv().ok();
let db = Arc::new(Surreal::new::<Ws>("127.0.0.1:8000").await?);
// Signin as a namespace, database, or root user let db_pool = MySqlPoolOptions::new()
db.signin(Root { .max_connections(64)
username: "root", .connect(env::var("DATABASE_URL").expect("DATABASE_URL must be set").as_str()).await?;
password: "root",
}).await?;
// Select a specific namespace / database sqlx::query(
db.use_ns("realmchat").use_db("test").await?; "CREATE DATABASE IF NOT EXISTS realmchat; USE realmchat;"
).fetch_one(&db_pool).await?;
sqlx::query(
"CREATE TABLE IF NOT EXISTS room (
id SERIAL,
room_id VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL
);"
).execute(&db_pool).await?;
sqlx::query(
"CREATE TABLE IF NOT EXISTS user (
id SERIAL,
user_id VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
online BOOL NOT NULL
);"
).execute(&db_pool).await?;
sqlx::query(
"CREATE TABLE IF NOT EXISTS message (
id SERIAL,
timestamp DATETIME NOT NULL,
user INT NOT NULL,
room INT NOT NULL,
type ENUM('text', 'attachment', 'reply', 'edit', 'reaction', 'redaction') NOT NULL,
msgText TEXT,
referencingID INT,
emoji TEXT,
redaction BOOL
);"
).execute(&db_pool).await?;
let server_addr = (IpAddr::V6(Ipv6Addr::LOCALHOST), 5051); let server_addr = (IpAddr::V6(Ipv6Addr::LOCALHOST), 5051);

View File

@@ -1,23 +1,23 @@
use std::net::SocketAddr; use std::net::SocketAddr;
use std::sync::Arc;
use futures::future; use futures::future;
use futures::future::Ready; use futures::future::Ready;
use surrealdb::engine::remote::ws::Client; use sqlx::{MySql, Pool};
use surrealdb::{Error, Response, Surreal};
use tarpc::context::Context; use tarpc::context::Context;
use crate::types::{Message, RealmChat, Room, ErrorCode, User, Record}; use tarpc::server::incoming::Incoming;
use crate::types::{ErrorCode, Message, MessageData, RealmChat, Room, User};
#[derive(Clone)] #[derive(Clone)]
pub struct RealmChatServer { pub struct RealmChatServer {
pub socket: SocketAddr, pub socket: SocketAddr,
pub db: Arc<Surreal<Client>>, pub db_pool: Pool<MySql>,
} }
impl RealmChatServer { impl RealmChatServer {
pub fn new(socket: SocketAddr, db: Arc<Surreal<Client>>) -> RealmChatServer { pub fn new(socket: SocketAddr, db_pool: Pool<MySql>) -> RealmChatServer {
RealmChatServer { RealmChatServer {
socket, socket,
db, db_pool,
} }
} }
} }
@@ -28,15 +28,43 @@ impl RealmChat for RealmChatServer {
} }
async fn send_message(self, context: Context, message: Message) -> Result<Message, ErrorCode> { async fn send_message(self, context: Context, message: Message) -> Result<Message, ErrorCode> {
let created: surrealdb::Result<Vec<Record>> = self.db //TODO: verify authentication somehow
.create(message.room.roomid.clone())
.content(message.clone())
.await;
//TODO: Tell everyone let result = match &message.data {
MessageData::Text(text) => {
sqlx::query("INSERT INTO message (timestamp, user, room, type, msgText) VALUES (?, ?, ?, 'text', ?)")
.bind(message.timestamp).bind(message.user.id).bind(message.room.id).bind(text)
.execute(&self.db_pool).await
}
MessageData::Attachment(attachment) => { todo!() }
MessageData::Reply(reply) => {
sqlx::query("INSERT INTO message (timestamp, user, room, type, msgText, referencingID) VALUES (?, ?, ?, 'reply', ?, ?)")
.bind(message.timestamp).bind(message.user.id).bind(message.room.id).bind(reply.text.clone()).bind(reply.referencing_id)
.execute(&self.db_pool).await
}
MessageData::Edit(edit) => {
sqlx::query("INSERT INTO message (timestamp, user, room, type, msgText, referencingID) VALUES (?, ?, ?, 'edit', ?, ?)")
.bind(message.timestamp).bind(message.user.id).bind(message.room.id).bind(edit.text.clone()).bind(edit.referencing_id)
.execute(&self.db_pool).await
}
MessageData::Reaction(reaction) => {
sqlx::query("INSERT INTO message (timestamp, user, room, type, emoji, referencingID) VALUES (?, ?, ?, 'reaction', ?, ?)")
.bind(message.timestamp).bind(message.user.id).bind(message.room.id).bind(reaction.emoji.clone()).bind(reaction.referencing_id)
.execute(&self.db_pool).await
}
MessageData::Redaction(redaction) => {
sqlx::query("INSERT INTO message (timestamp, user, room, type, redaction, referencingID) VALUES (?, ?, ?, 'redaction', ?, ?)")
.bind(message.timestamp).bind(message.user.id).bind(message.room.id).bind(true).bind(redaction.referencing_id)
.execute(&self.db_pool).await
}
};
match created { match result {
Ok(ids) => Ok(message), Ok(ids) => {
//TODO: Tell everyone
Ok(message)
},
Err(_) => Err(ErrorCode::Error), Err(_) => Err(ErrorCode::Error),
} }
} }
@@ -62,12 +90,7 @@ impl RealmChat for RealmChatServer {
} }
async fn get_rooms(self, context: Context) -> Result<Vec<Room>, ErrorCode> { async fn get_rooms(self, context: Context) -> Result<Vec<Room>, ErrorCode> {
let result: surrealdb::Result<Vec<Room>> = self.db.select("room").await; todo!()
match result {
Ok(rooms) => Ok(rooms),
Err(_) => Err(ErrorCode::Error),
}
} }
async fn get_room(self, context: Context, roomid: String) -> Result<Room, ErrorCode> { async fn get_room(self, context: Context, roomid: String) -> Result<Room, ErrorCode> {
@@ -79,26 +102,10 @@ impl RealmChat for RealmChatServer {
} }
async fn get_joined_users(self, context: Context) -> Result<Vec<User>, ErrorCode> { async fn get_joined_users(self, context: Context) -> Result<Vec<User>, ErrorCode> {
let result: surrealdb::Result<Vec<User>> = self.db.select("user").await; todo!()
match result {
Ok(users) => Ok(users),
Err(_) => Err(ErrorCode::Error),
}
} }
async fn get_online_users(self, context: Context) -> Result<Vec<User>, ErrorCode> { async fn get_online_users(self, context: Context) -> Result<Vec<User>, ErrorCode> {
let result: surrealdb::Result<Response> = self.db.query("SELECT * FROM user WHERE online = true").await; //TODO: We're switching to MySQL todo!()
match result {
Ok(mut response) => {
let users: Result<Vec<User>, Error> = response.take(0);
match users {
Ok(vec) => Ok(vec),
Err(_) => Err(ErrorCode::Error),
}
},
Err(_) => Err(ErrorCode::Error),
}
} }
} }

View File

@@ -1,11 +1,5 @@
use surrealdb::sql::Thing;
use tarpc::serde::{Deserialize, Serialize}; use tarpc::serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize)]
pub struct Record {
id: Thing,
}
#[tarpc::service] #[tarpc::service]
pub trait RealmChat { pub trait RealmChat {
async fn test(name: String) -> String; async fn test(name: String) -> String;
@@ -31,7 +25,7 @@ pub trait RealmChat {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ErrorCode { pub enum ErrorCode {
None = 0, None,
Error, Error,
Unauthorized, Unauthorized,
NotFound, NotFound,
@@ -39,8 +33,8 @@ pub enum ErrorCode {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message { pub struct Message {
pub guid: String, pub id: u32,
pub timestamp: u64, pub timestamp: u64, //TODO: Change to a real time for SQL
pub user: User, pub user: User,
pub room: Room, pub room: Room,
pub data: MessageData, pub data: MessageData,
@@ -55,7 +49,6 @@ pub enum MessageData {
Edit(Edit), //NOTE: Have to be the owner of the referencing_guid Edit(Edit), //NOTE: Have to be the owner of the referencing_guid
Reaction(Reaction), Reaction(Reaction),
Redaction(Redaction), Redaction(Redaction),
TypingIndicator(bool), //isTyping
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -65,29 +58,30 @@ pub struct Attachment {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Reply { pub struct Reply {
pub referencing_guid: String, pub referencing_id: u32,
pub text: String, pub text: String,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Edit { pub struct Edit {
pub referencing_guid: String, pub referencing_id: u32,
pub text: String, pub text: String,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Reaction { pub struct Reaction {
pub referencing_guid: String, pub referencing_id: u32,
pub emoji: String pub emoji: String
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Redaction { pub struct Redaction {
pub referencing_guid: String, pub referencing_id: u32,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User { pub struct User {
pub id: u32,
pub userid: String, pub userid: String,
pub name: String, pub name: String,
pub online: bool, pub online: bool,
@@ -96,6 +90,7 @@ pub struct User {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Room { pub struct Room {
pub id: u32,
pub roomid: String, pub roomid: String,
pub name: String, pub name: String,
//TODO //TODO