Skip to main content

tibba_runtime/
ctx.rs

1// Copyright 2026 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/// 当前请求的追踪上下文,记录设备 ID、Trace ID、起始时间和登录账号。
20#[derive(Debug)]
21pub struct Context {
22    /// 设备 ID
23    pub device_id: String,
24    /// 链路追踪 ID
25    pub trace_id: String,
26    /// 请求开始时间(用于计算耗时)
27    start_time: Instant,
28    /// 当前登录账号,无锁原子更新
29    account: ArcSwap<String>,
30}
31
32impl Context {
33    /// 创建新的请求上下文,记录设备 ID 和 Trace ID,并以当前时刻为起始时间。
34    pub fn new(device_id: impl Into<String>, trace_id: impl Into<String>) -> Self {
35        Self {
36            device_id: device_id.into(),
37            trace_id: trace_id.into(),
38            start_time: Instant::now(),
39            account: ArcSwap::new(Arc::new(String::new())),
40        }
41    }
42
43    /// 返回自请求开始以来经过的时间。
44    pub fn elapsed(&self) -> Duration {
45        self.start_time.elapsed()
46    }
47
48    /// 返回自请求开始以来经过的毫秒数。
49    pub fn elapsed_ms(&self) -> u64 {
50        self.start_time.elapsed().as_millis() as u64
51    }
52
53    /// 返回当前上下文关联的登录账号。
54    pub fn get_account(&self) -> Arc<String> {
55        self.account.load_full()
56    }
57
58    /// 设置当前上下文的登录账号,无锁原子写入。
59    pub fn set_account(&self, account: impl Into<String>) {
60        self.account.store(Arc::new(account.into()));
61    }
62}
63
64tokio::task_local! {
65    /// Tokio task-local 变量,存储当前请求的追踪上下文,生命周期与请求任务绑定。
66    pub static CTX: Arc<Context>;
67}