94 lines
2.9 KiB
Rust
94 lines
2.9 KiB
Rust
use crate::cache::redis::AppRedis;
|
|
use crate::error::{AppError, AppResult};
|
|
use crate::service::im::util::PRESENCE_PREFIX;
|
|
use ::redis::Cmd;
|
|
|
|
use super::redis_keys::*;
|
|
use super::session::WsSession;
|
|
|
|
pub fn register_redis_online(redis: &AppRedis, session: &WsSession) -> AppResult<()> {
|
|
let set_key = format!("{WS_ONLINE_PREFIX}{}", session.user_id);
|
|
let conn_id = session.connection_id.to_string();
|
|
let meta_key = format!("{WS_CONNS_PREFIX}{}", session.connection_id);
|
|
let mut conn = redis.get_connection()?;
|
|
|
|
Cmd::new()
|
|
.arg("SADD")
|
|
.arg(&set_key)
|
|
.arg(&conn_id)
|
|
.query::<i32>(&mut *conn.inner_mut())?;
|
|
Cmd::new()
|
|
.arg("EXPIRE")
|
|
.arg(&set_key)
|
|
.arg(WS_ONLINE_TTL_SECS)
|
|
.query::<()>(&mut *conn.inner_mut())?;
|
|
Cmd::new()
|
|
.arg("SETEX")
|
|
.arg(&meta_key)
|
|
.arg(WS_ONLINE_TTL_SECS)
|
|
.arg(session.workspace_name.as_str())
|
|
.query::<()>(&mut *conn.inner_mut())?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn unregister_redis_online(redis: &AppRedis, session: &WsSession) -> AppResult<()> {
|
|
let set_key = format!("{WS_ONLINE_PREFIX}{}", session.user_id);
|
|
let conn_id = session.connection_id.to_string();
|
|
let meta_key = format!("{WS_CONNS_PREFIX}{}", session.connection_id);
|
|
let mut conn = redis.get_connection()?;
|
|
|
|
Cmd::new()
|
|
.arg("SREM")
|
|
.arg(&set_key)
|
|
.arg(&conn_id)
|
|
.query::<i32>(&mut *conn.inner_mut())?;
|
|
|
|
let remaining: i32 = Cmd::new()
|
|
.arg("SCARD")
|
|
.arg(&set_key)
|
|
.query(&mut *conn.inner_mut())
|
|
.map_err(AppError::Redis)?;
|
|
if remaining == 0 {
|
|
Cmd::new()
|
|
.arg("DEL")
|
|
.arg(&set_key)
|
|
.query::<()>(&mut *conn.inner_mut())?;
|
|
let pk = format!("{PRESENCE_PREFIX}{}", session.user_id);
|
|
let _ = Cmd::new()
|
|
.arg("DEL")
|
|
.arg(&pk)
|
|
.query::<()>(&mut *conn.inner_mut());
|
|
}
|
|
let _ = Cmd::new()
|
|
.arg("DEL")
|
|
.arg(&meta_key)
|
|
.query::<()>(&mut *conn.inner_mut());
|
|
Ok(())
|
|
}
|
|
|
|
pub fn heartbeat_redis(redis: &AppRedis, session: &WsSession) -> AppResult<()> {
|
|
let set_key = format!("{WS_ONLINE_PREFIX}{}", session.user_id);
|
|
let meta_key = format!("{WS_CONNS_PREFIX}{}", session.connection_id);
|
|
let pk = format!("{PRESENCE_PREFIX}{}", session.user_id);
|
|
let mut conn = redis.get_connection()?;
|
|
|
|
let _ = Cmd::new()
|
|
.arg("EXPIRE")
|
|
.arg(&set_key)
|
|
.arg(WS_ONLINE_TTL_SECS)
|
|
.query::<()>(&mut *conn.inner_mut());
|
|
let _ = Cmd::new()
|
|
.arg("SETEX")
|
|
.arg(&meta_key)
|
|
.arg(WS_ONLINE_TTL_SECS)
|
|
.arg(session.workspace_name.as_str())
|
|
.query::<()>(&mut *conn.inner_mut());
|
|
let _ = Cmd::new()
|
|
.arg("SETEX")
|
|
.arg(&pk)
|
|
.arg(WS_ONLINE_TTL_SECS)
|
|
.arg("online")
|
|
.query::<()>(&mut *conn.inner_mut());
|
|
Ok(())
|
|
}
|