Skip to content

Commit

Permalink
socket.io basics
Browse files Browse the repository at this point in the history
  • Loading branch information
HCHogan committed Aug 2, 2024
1 parent c247f8c commit 8e6f26a
Show file tree
Hide file tree
Showing 13 changed files with 282 additions and 11 deletions.
6 changes: 4 additions & 2 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,15 @@ jobs:
}' > ~/.config/realm/realm.lua
- name: Display realm.lua for verification
run: cat ~/.config/realm/realm.lua
run: |
cat ~/.config/realm/realm.lua
echo $USER
- name: Postgres setup
run: |
sudo apt-get update
sudo apt-get install -y postgresql-client
PGPASSWORD=0528 psql -h localhost -U hank -d test_db -c "SELECT 1"
PGPASSWORD=0528 psql -h localhost -U hank -d hank -c "SELECT 1"
- name: Build
run: cargo build --verbose
Expand Down
149 changes: 149 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ chrono = { version = "0.4", features = ["serde"] }
sonyflake = { version = "0.2.0" }
argon2 = "0.5"
color-eyre = "0.6"
tower-http = { version = "0.5.2", features = ["cors"] }
tower = "0.4"
socketioxide = {version = "0.14", features = ["state"]}

entity = { path = "../entity" }
migration = { path = "../migration" }
Expand All @@ -30,6 +33,7 @@ features = [
"basic-auth",
"compression",
"affix",
"tower-compat",
]

[dependencies.sea-orm]
Expand Down
4 changes: 2 additions & 2 deletions api/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ pub async fn get_config() -> Result<Config> {
let config: Table = luai.load(&config_content).eval()?;
let config = serde_json::to_string(&config)?;

let config: Config = serde_json::from_str(&config)?;
if let Some(url) = env::var("DATABASE_URL").ok() {
let mut config: Config = serde_json::from_str(&config)?;
if let Ok(url) = env::var("DATABASE_URL") {
info!("overriding database url with DATABASE_URL");
config.db_url = url;
}
Expand Down
1 change: 1 addition & 0 deletions api/src/handler/message_handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 1 addition & 0 deletions api/src/handler/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod user_handler;
pub mod server_handler;
pub mod message_handler;
14 changes: 8 additions & 6 deletions api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ pub mod router;
pub mod state;
pub mod utils;

use crate::router::make_route;
use color_eyre::Result;
use salvo::prelude::*;
use tokio::signal;
Expand All @@ -18,11 +17,12 @@ use tracing_subscriber::EnvFilter;
#[tokio::main]
pub async fn main() -> Result<()> {
let filter = EnvFilter::from_default_env();
tracing_subscriber::fmt().with_env_filter(filter).with_test_writer().init();
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_test_writer()
.init();
color_eyre::install()?;



let config = config::get_config().await.unwrap_or_else(|_| {
info!("failed to read config file, using default instead");
config::Config::default()
Expand All @@ -32,7 +32,9 @@ pub async fn main() -> Result<()> {
.bind()
.await;

let router = Router::with_path("api").push(make_route(&config).await);
let router = Router::new()
.push(Router::with_path("api").push(router::make_router(&config).await))
.push(crate::router::socket_chat::make_router());

// TODO: http3
let server = Server::new(acceptor);
Expand All @@ -59,7 +61,7 @@ mod tests {
#[tokio::test]
async fn test_basic_auth() {
let test_config = Config::default();
let service = Service::new(super::make_route(&test_config).await);
let service = Service::new(super::make_router(&test_config).await);

let url = format!("http://{}:{}/", test_config.host, test_config.port);

Expand Down
1 change: 1 addition & 0 deletions api/src/middleware.rs → api/src/middleware/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod basic_auth;
pub mod socket_io;
Empty file added api/src/middleware/socket_io.rs
Empty file.
39 changes: 39 additions & 0 deletions api/src/models/message.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use std::collections::{HashMap, VecDeque};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
use std::sync::Arc;

use chrono::{DateTime, Utc};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
pub text: String,
pub user: String,
pub date: DateTime<Utc>
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Messages {
pub messages: Vec<Message>,
}

pub type RoomStore = HashMap<String, VecDeque<Message>>;

#[derive(Clone, Default)]
pub struct MessageStore {
pub messages: Arc<RwLock<RoomStore>>,
}

impl MessageStore {
pub async fn insert(&self, room: &str, message: Message) {
let mut binding = self.messages.write().await;
let messages = binding.entry(room.to_owned()).or_default();
messages.push_front(message);
messages.truncate(20);
}

pub async fn get(&self, room: &str) -> Vec<Message> {
let messages = self.messages.read().await.get(room).cloned();
messages.unwrap_or_default().into_iter().rev().collect()
}
}
Loading

0 comments on commit 8e6f26a

Please sign in to comment.