tuitbot_server/state.rs
1//! Shared application state for the tuitbot server.
2
3use std::collections::HashMap;
4use std::net::IpAddr;
5use std::path::PathBuf;
6use std::sync::Arc;
7use std::time::Instant;
8
9use tokio::sync::{broadcast, Mutex, RwLock};
10use tokio_util::sync::CancellationToken;
11use tuitbot_core::automation::circuit_breaker::CircuitBreaker;
12use tuitbot_core::automation::Runtime;
13use tuitbot_core::config::{ConnectorConfig, ContentSourcesConfig, DeploymentMode};
14use tuitbot_core::content::ContentGenerator;
15use tuitbot_core::storage::DbPool;
16
17use crate::ws::WsEvent;
18
19/// Pending OAuth PKCE state for connector link flows.
20pub struct PendingOAuth {
21 /// The PKCE code verifier needed to complete the token exchange.
22 pub code_verifier: String,
23 /// When this entry was created (for 10-minute expiry).
24 pub created_at: Instant,
25}
26
27/// Shared application state accessible by all route handlers.
28pub struct AppState {
29 /// SQLite connection pool.
30 pub db: DbPool,
31 /// Path to the configuration file.
32 pub config_path: PathBuf,
33 /// Data directory for media storage (parent of config file).
34 pub data_dir: PathBuf,
35 /// Broadcast channel sender for real-time WebSocket events.
36 pub event_tx: broadcast::Sender<WsEvent>,
37 /// Local bearer token for API authentication.
38 pub api_token: String,
39 /// Bcrypt hash of the web login passphrase (None if not configured).
40 pub passphrase_hash: RwLock<Option<String>>,
41 /// Host address the server is bound to.
42 pub bind_host: String,
43 /// Port the server is listening on.
44 pub bind_port: u16,
45 /// Per-IP login attempt tracking for rate limiting: (count, window_start).
46 pub login_attempts: Mutex<HashMap<IpAddr, (u32, Instant)>>,
47 /// Per-account automation runtimes (keyed by account_id).
48 pub runtimes: Mutex<HashMap<String, Runtime>>,
49 /// Per-account content generators for AI assist endpoints.
50 pub content_generators: Mutex<HashMap<String, Arc<ContentGenerator>>>,
51 /// Optional circuit breaker for X API rate-limit protection.
52 pub circuit_breaker: Option<Arc<CircuitBreaker>>,
53 /// Cancellation token for the Watchtower filesystem watcher (None if not running).
54 pub watchtower_cancel: Option<CancellationToken>,
55 /// Content sources configuration for the Watchtower.
56 pub content_sources: ContentSourcesConfig,
57 /// Connector configuration for remote source OAuth flows.
58 pub connector_config: ConnectorConfig,
59 /// Deployment mode (desktop, self_host, or cloud).
60 pub deployment_mode: DeploymentMode,
61 /// Pending OAuth PKCE challenges keyed by state parameter.
62 pub pending_oauth: Mutex<HashMap<String, PendingOAuth>>,
63}