use arc_swap::ArcSwap;
use std::sync::Arc;
use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct Context {
pub device_id: String,
pub trace_id: String,
start_time: Instant,
account: ArcSwap<String>,
}
impl Context {
pub fn new(device_id: impl Into<String>, trace_id: impl Into<String>) -> Self {
Self {
device_id: device_id.into(),
trace_id: trace_id.into(),
start_time: Instant::now(),
account: ArcSwap::new(Arc::new(String::new())),
}
}
pub fn elapsed(&self) -> Duration {
self.start_time.elapsed()
}
pub fn elapsed_ms(&self) -> u64 {
self.start_time.elapsed().as_millis() as u64
}
pub fn get_account(&self) -> Arc<String> {
self.account.load_full()
}
pub fn set_account(&self, account: impl Into<String>) {
self.account.store(Arc::new(account.into()));
}
}
tokio::task_local! {
pub static CTX: Arc<Context>;
}