Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.4 kB
4
Indexable
Never
use std::convert::Infallible;
use std::time::Duration;

use futures_util::StreamExt;
use salvo::prelude::*;
use salvo::sse::{self, SseEvent};
use tokio::time::interval;
use tokio_stream::wrappers::IntervalStream;
use sysinfo::{ System, SystemExt};
use std::sync::{Arc, Mutex};


struct MemoryInfo {
    total_memory_mb: f64,
    used_memory_mb: f64,
    total_swap_mb: f64,
    used_swap_mb: f64,
}

// create server-sent event
fn sse_counter(counter: u64) -> Result<SseEvent, Infallible> {
    Ok(SseEvent::default().text(counter.to_string()))
}
fn update_memory_info(memory_info: Arc<Mutex<MemoryInfo>>) {
    let mut sys = System::new();
    loop {
        sys.refresh_all();
        let mut memory_info = memory_info.lock().unwrap();
        memory_info.total_memory_mb = bytes_to_mb(sys.total_memory());
        memory_info.used_memory_mb = bytes_to_mb(sys.used_memory());
        memory_info.total_swap_mb = bytes_to_mb(sys.total_swap());
        memory_info.used_swap_mb = bytes_to_mb(sys.used_swap());
        drop(memory_info); // Release the lock
        std::thread::sleep(System::MINIMUM_CPU_UPDATE_INTERVAL);
    }
}

#[handler]
async fn handle_tick(res: &mut Response,memory_info: Arc<Mutex<MemoryInfo>>) {
    let event_stream = {
        let mut counter: u64 = 0;
        let interval = interval(Duration::from_secs(1));
        let stream = IntervalStream::new(interval);
        let mut memory_info = memory_info.lock().unwrap();
        stream.map(move |_| {
            counter += 1;
            
      
       

            sse_counter(counter)
        })
    };
    sse::streaming(res, event_stream).ok();
}

fn bytes_to_mb(bytes: u64) -> f64 {
    // Convert bytes to megabytes
    let mb = bytes as f64 / 1_048_576.0;
    return mb;
}
#[tokio::main]
async fn main() {
    let memory_info = Arc::new(Mutex::new(MemoryInfo {
        total_memory_mb: 0.0,
        used_memory_mb: 0.0,
        total_swap_mb: 0.0,
        used_swap_mb: 0.0,
    }));
    let memory_info_clone = memory_info.clone();
    std::thread::spawn(move || {
        update_memory_info(memory_info_clone);
    });
  
    tracing_subscriber::fmt().init();

    let router = Router::with_path("ticks").get(handle_tick,memory_info_clone); // Route for /ticks

    let acceptor = TcpListener::new("127.0.0.1:5800").bind().await;
    Server::new(acceptor).serve(router).await;
}