Skip to content

Commit

Permalink
History Limit.
Browse files Browse the repository at this point in the history
  • Loading branch information
kz-acheron committed Jan 19, 2025
1 parent 1f0a9b9 commit f8c1870
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 26 deletions.
21 changes: 11 additions & 10 deletions examples/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,19 @@
}

function sendMessage() {
const name = document.getElementById("name").value;
const message = document.getElementById("message").value;
const name = document.getElementById("name").value.trim();
const message = document.getElementById("message").value.trim();
if (!name || !message) return;

const msg = [
{
name: name,
message: message,
time: new Date().toISOString(),
},
];
ws.send(JSON.stringify(msg));
ws.send(
JSON.stringify([
{
name: name,
message: message,
time: new Date().toISOString(),
},
])
);
document.getElementById("message").value = "";
}

Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mod models;
mod routes;
mod state;

const HISTORY_LIMIT: usize = 100;
const CHANNEL_CAPACITY: usize = 1000;

#[tokio::main]
Expand Down
23 changes: 8 additions & 15 deletions src/routes/chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,7 @@ async fn handle_socket(socket: ws::WebSocket, state: Arc<AppState>) {
for msg in &mut messages {
msg.time = Utc::now();

// TODO: Don't F Touch This Code
{
let mut history = state_clone.history.write().await;
history.push(msg.clone());
}
state_clone.add_message(msg.clone()).await;

if let Err(e) = state_clone.tx.clone().send(msg.clone()) {
error!("Failed to send message: {}", e);
Expand All @@ -47,19 +43,16 @@ async fn handle_socket(socket: ws::WebSocket, state: Arc<AppState>) {
}
});

// Handle broadcasting and send message history
// Handle broadcasting and send message history.
let mut send_task = tokio::spawn(async move {
// TODO: Don't F Touch This Code
// Send message history to the client
{
let history = state.history.read().await;
let json = serde_json::to_string(&*history).unwrap();
if ws_tx.send(ws::Message::Text(json.into())).await.is_err() {
return; // Return if fails.
}
// Send message history to the client.
let recent_messages = state.get_recent_messages().await;
let json = serde_json::to_string(&recent_messages).unwrap();
if ws_tx.send(ws::Message::Text(json.into())).await.is_err() {
return;
}

// Broadcast new messages
// Broadcast new messages.
while let Ok(msg) = rx.recv().await {
let json = serde_json::to_string(&vec![msg]).unwrap();
if ws_tx.send(ws::Message::Text(json.into())).await.is_err() {
Expand Down
16 changes: 15 additions & 1 deletion src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::sync::Arc;

use tokio::sync::{broadcast, RwLock};

use crate::{models::Chat, CHANNEL_CAPACITY};
use crate::{models::Chat, CHANNEL_CAPACITY, HISTORY_LIMIT};

pub struct AppState {
pub tx: broadcast::Sender<Chat>,
Expand All @@ -18,4 +18,18 @@ impl AppState {
history: Arc::new(RwLock::new(Vec::new())),
})
}

pub async fn add_message(&self, message: Chat) {
let mut history = self.history.write().await;

history.push(message);

if history.len() > HISTORY_LIMIT {
history.remove(0);
}
}

pub async fn get_recent_messages(&self) -> Vec<Chat> {
self.history.read().await.iter().cloned().collect()
}
}

0 comments on commit f8c1870

Please sign in to comment.