use std::{sync::Arc, time::SystemTime};
use bytes::Bytes;
use tokio::{
io::{AsyncWriteExt, WriteHalf},
net::TcpStream,
sync::{Mutex, RwLock},
};
use tracing::error;
pub(crate) struct LynnUser {
write_half: *mut WriteHalf<TcpStream>,
user_id: Option<u64>,
last_communicate_time: Arc<RwLock<SystemTime>>,
mutex: Mutex<()>,
}
unsafe impl Send for LynnUser {}
unsafe impl Sync for LynnUser {}
impl LynnUser {
pub(crate) fn new(
write_half: WriteHalf<TcpStream>,
last_communicate_time: Arc<RwLock<SystemTime>>,
) -> Self {
Self {
write_half: Box::into_raw(Box::new(write_half)),
user_id: None,
last_communicate_time,
mutex: Mutex::new(()),
}
}
pub(crate) fn get_last_communicate_time(&self) -> Arc<RwLock<SystemTime>> {
self.last_communicate_time.clone()
}
pub(crate) async fn send_response(&self, response: &Bytes) {
let _lock = self.mutex.lock().await;
if !self.write_half.is_null() {
if let Some(write_half) = unsafe { self.write_half.as_mut() } {
if let Err(e) = write_half.write_all(&response).await {
error!("Failed to write to socket: {}", e);
} else {
let _ = write_half.flush().await;
}
}
}
}
}
impl Drop for LynnUser {
fn drop(&mut self) {}
}