2026-06-17 20:49:17 +08:00
|
|
|
|
//! 共享应用状态。
|
|
|
|
|
|
//!
|
|
|
|
|
|
//! 采样任务(写)与 HTTP handler(读)通过一个被 `RwLock` 保护的
|
|
|
|
|
|
//! `Stats` 快照通信。`AppState` 可廉价 `clone`(内部是 `Arc`)。
|
|
|
|
|
|
|
|
|
|
|
|
use std::sync::Arc;
|
|
|
|
|
|
|
|
|
|
|
|
use tokio::sync::RwLock;
|
|
|
|
|
|
|
2026-06-18 00:00:38 +08:00
|
|
|
|
use crate::auth::UserStore;
|
2026-06-17 20:49:17 +08:00
|
|
|
|
use crate::monitor::Stats;
|
2026-06-18 20:13:18 +08:00
|
|
|
|
use crate::weather::WeatherService;
|
2026-06-17 20:49:17 +08:00
|
|
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
|
|
pub struct AppState {
|
|
|
|
|
|
/// 最新一次采样快照。
|
|
|
|
|
|
pub snapshot: Arc<RwLock<Stats>>,
|
2026-06-18 00:00:38 +08:00
|
|
|
|
/// 用户表:启动时构建一次、之后只读,故无需锁,用 `Arc` 共享即可。
|
|
|
|
|
|
pub users: Arc<UserStore>,
|
2026-06-18 20:13:18 +08:00
|
|
|
|
/// 天气/定位服务(自带每日限流 + 缓存)。
|
|
|
|
|
|
pub weather: Arc<WeatherService>,
|
2026-06-17 20:49:17 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl AppState {
|
|
|
|
|
|
pub fn new() -> Self {
|
|
|
|
|
|
Self {
|
|
|
|
|
|
snapshot: Arc::new(RwLock::new(Stats::default())),
|
2026-06-18 00:00:38 +08:00
|
|
|
|
users: Arc::new(UserStore::seed()),
|
2026-06-18 20:13:18 +08:00
|
|
|
|
weather: Arc::new(WeatherService::from_env()),
|
2026-06-17 20:49:17 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|