tibba_state/ctx.rs
1// Copyright 2025 Tree xie.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use arc_swap::ArcSwap;
16use std::sync::Arc;
17use std::time::{Duration, Instant};
18
19/// Trace context for the current request
20#[derive(Debug)]
21pub struct Context {
22 /// Device ID
23 pub device_id: String,
24 /// Trace ID
25 pub trace_id: String,
26 /// Start time
27 start_time: Instant,
28 /// Account
29 account: ArcSwap<String>,
30}
31
32impl Context {
33 pub fn new(device_id: &str, trace_id: &str) -> Self {
34 Self {
35 device_id: device_id.to_string(),
36 trace_id: trace_id.to_string(),
37 start_time: Instant::now(),
38 account: ArcSwap::new(Arc::new("".to_string())),
39 }
40 }
41 /// Get the elapsed time since the start of the request
42 pub fn elapsed(&self) -> Duration {
43 self.start_time.elapsed()
44 }
45 /// Get the account
46 pub fn get_account(&self) -> Arc<String> {
47 self.account.load_full()
48 }
49 /// Set the account
50 pub fn set_account(&self, account: impl Into<String>) {
51 self.account.store(Arc::new(account.into()));
52 }
53}
54
55tokio::task_local! {
56 pub static CTX: Arc<Context>;
57}