Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

3.2 KB
Raw Blame
use std::sync::Arc;
use std::time::Duration;

use common_database::PoolConfig;
use tokio::sync::Semaphore;

use crate::backup::BackupStore;
use crate::cache::TtlCache;
use crate::config::Config;
use crate::etcd::EtcdHandle;
use crate::jobs::JobRegistry;
use crate::k8s::PodDiscovery;
use crate::kafka::lag::{ConsumerTarget, LagOverview};
use crate::teams::TeamResolver;

#[derive(Clone)]
pub struct AppState {
    pub config: Arc<Config>,
    pub jobs: Arc<JobRegistry>,
    pub teams: Arc<TeamResolver>,
    pub pods: Arc<PodDiscovery>,
    pub http: reqwest::Client,
    /// Discovered group/topic targets; topology changes rarely.
    pub discovery: Arc<TtlCache<Vec<ConsumerTarget>>>,
    /// Overview scan results; short TTL + single-flight bounds broker load.
    pub overview: Arc<TtlCache<LagOverview>>,
    /// Caps concurrent synchronous message-browse scans; each holds a Kafka
    /// consumer on the blocking pool for up to the browse deadline.
    pub browse_permits: Arc<Semaphore>,
    /// `None` when `ETCD_ENDPOINTS` is unset; the etcd tools then 503.
    pub etcd: Option<Arc<EtcdHandle>>,
    pub backups: Option<Arc<dyn BackupStore>>,
}

impl AppState {
    pub fn new(config: Config) -> anyhow::Result<Self> {
        // Treat set-but-empty like unset so a templated empty env var can't
        // half-enable resolution with an unusable URL.
        let pool = match config.database_url.as_deref().filter(|url| !url.is_empty()) {
            None => {
                tracing::info!("DATABASE_URL not set; token -> team resolution disabled");
                None
            }
            Some(database_url) => {
                let pool_config = PoolConfig {
                    max_connections: config.pg_max_connections,
                    pool_name: Some("ingestion-control-plane".to_string()),
                    ..PoolConfig::default()
                };
                Some(common_database::get_pool_with_config(
                    database_url,
                    pool_config,
                )?)
            }
        };

        let etcd = EtcdHandle::from_config(&config);
        if etcd.is_none() {
            tracing::info!("ETCD_ENDPOINTS not set; etcd tools disabled");
        }

        // No overall request timeout: the debug proxy pipes long-lived SSE
        // streams. Connect timeout still bounds unreachable pods.
        let http = reqwest::Client::builder()
            .connect_timeout(Duration::from_secs(2))
            .build()
            .expect("reqwest client construction cannot fail with static config");

        Ok(Self {
            jobs: Arc::new(JobRegistry::new(config.analysis_max_concurrent_jobs)),
            teams: Arc::new(TeamResolver::new(pool)),
            pods: Arc::new(PodDiscovery::from_config(&config)?),
            http,
            discovery: Arc::new(TtlCache::new(Duration::from_secs(
                config.discovery_cache_ttl_secs,
            ))),
            overview: Arc::new(TtlCache::new(Duration::from_secs(
                config.overview_cache_ttl_secs,
            ))),
            browse_permits: Arc::new(Semaphore::new(config.browse_max_concurrent.max(1))),
            etcd: etcd.map(Arc::new),
            backups: None,
            config: Arc::new(config),
        })
    }
}