systemprompt-runtime 0.56.0

Application runtime for systemprompt.io AI governance infrastructure. AppContext, lifecycle builder, extension registry, and module wiring for the MCP governance pipeline.
Documentation
//! [`AppContext`] — the application-wide runtime container.
//!
//! Holds shared handles (config, database pool, extension registry,
//! analytics, route classifier, etc.) cloned cheaply via [`Arc`].
//! Constructed via [`crate::AppContextBuilder`] or [`AppContext::new`].
//!
//! Copyright (c) systemprompt.io — Business Source License 1.1.
//! See <https://systemprompt.io> for licensing details.

use std::sync::{Arc, OnceLock};


use systemprompt_agent::repository::A2ARepositories;
use systemprompt_ai::repository::AiRepositories;
use systemprompt_analytics::repository::AnalyticsRepositories;
use systemprompt_analytics::{AnalyticsService, FingerprintRepository, GeoIpReader};
use systemprompt_config::paths::AppPaths;
use systemprompt_content::repository::ContentRepositories;
use systemprompt_database::{DbPool, SchemaInstallReport, ServiceRepository};
use systemprompt_events::EventBridgeHandle;
use systemprompt_extension::ExtensionRegistry;
use systemprompt_files::FileRepository;
use systemprompt_marketplace::inventory::PublishGuard;
use systemprompt_marketplace::managed::ManagedRepository;
use systemprompt_marketplace::{MarketplaceCache, MarketplaceFilter};
use systemprompt_mcp::repository::McpSessionRepository;
use systemprompt_mcp::services::registry::RegistryService;
use systemprompt_models::services::SystemAdmin;
use systemprompt_models::{Config, ContentConfigRaw, ContentRouting, RouteClassifier};
use systemprompt_oauth::repository::OAuthRepositories;
use systemprompt_security::authz::SharedAuthzHook;
use systemprompt_security::policy::GovernanceEngine;
use systemprompt_traits::FileStorage;
use systemprompt_users::{UserRepository, UserService};

mod context_loaders;
mod debug_impls;
mod repositories;
mod services;
mod shutdown;

pub use shutdown::ShutdownRequest;

use crate::builder::AppContextBuilder;
use crate::error::RuntimeResult;
use crate::registry::ModuleApiRegistry;

/// Database pool and the data-access services layered on it.
///
/// `fingerprint_repo` and `user_service` are `None` when the corresponding
/// resource failed to initialise; callers must degrade gracefully.
#[derive(Clone)]
pub struct DataPlane {
    pub database: DbPool,
    pub analytics_service: Arc<AnalyticsService>,
    pub fingerprint_repo: Option<Arc<FingerprintRepository>>,
    pub user_service: Option<Arc<UserService>>,
    pub a2a_repositories: Arc<A2ARepositories>,
    pub content_repositories: Arc<ContentRepositories>,
    pub oauth_repositories: Arc<OAuthRepositories>,
    pub user_repository: Arc<UserRepository>,
    pub service_repository: Arc<ServiceRepository>,
    pub ai_repositories: Arc<AiRepositories>,
    pub analytics_repositories: Arc<AnalyticsRepositories>,
    pub feedback_snapshots_repository:
        Arc<systemprompt_analytics::snapshots::FeedbackSnapshotsRepository>,
    pub feedback_facts_repository: Arc<systemprompt_analytics::feedback::FeedbackFactsRepository>,
    pub file_repository: Arc<FileRepository>,
    pub mcp_session_repository: Arc<McpSessionRepository>,
    pub managed_repository: Arc<ManagedRepository>,
}

#[derive(Clone)]
pub struct ConfigPlane {
    pub config: Arc<Config>,
    pub app_paths: Arc<AppPaths>,
    pub content_config: Option<Arc<ContentConfigRaw>>,
    pub route_classifier: Arc<RouteClassifier>,
}

#[derive(Clone)]
pub struct Plugins {
    pub extension_registry: Arc<ExtensionRegistry>,
    pub api_registry: Arc<ModuleApiRegistry>,
    pub mcp_registry: RegistryService,
    pub marketplace_filter: Arc<dyn MarketplaceFilter>,
    pub marketplace_cache: Arc<MarketplaceCache>,
}

#[derive(Clone)]
pub struct Subsystems {
    pub system_admin: Arc<SystemAdmin>,
    pub authz_hook: SharedAuthzHook,
    pub governance: Arc<GovernanceEngine>,
    pub ai_service: Option<Arc<systemprompt_ai::AiService>>,
    pub artifact_ingest: Arc<systemprompt_mcp::ArtifactIngest>,
    pub schema_install: Arc<SchemaInstallReport>,
    pub event_bridge: Arc<OnceLock<EventBridgeHandle>>,
    pub geoip_reader: Option<GeoIpReader>,
    pub file_storage: Arc<dyn FileStorage>,
    pub shutdown: ShutdownRequest,
    pub publish_guard: Arc<tokio::sync::Mutex<PublishGuard>>,
    pub snapshot_wakeup: Arc<crate::reporting::SnapshotWakeup>,
}

/// Application-wide runtime container shared across the HTTP server, the
/// scheduler, and CLI commands.
///
/// Handles are grouped into four cohesive planes ([`DataPlane`],
/// [`ConfigPlane`], [`Plugins`], [`Subsystems`]); each field is an [`Arc`] (or
/// an `Arc`-internal handle such as [`DbPool`]), so `clone` is a
/// reference-count bump rather than a deep copy. Construct it via
/// [`AppContext::builder`] (or [`AppContext::new`] for the default build);
/// [`AppContext::from_parts`] bypasses the bootstrap and is intended for tests
/// and embedders that assemble the planes themselves. Read individual handles
/// through the accessor methods.
#[derive(Clone)]
pub struct AppContext {
    pub(crate) data: DataPlane,
    pub(crate) cfg: ConfigPlane,
    pub(crate) plugins: Plugins,
    pub(crate) subsystems: Subsystems,
}

impl AppContext {
    pub async fn new() -> RuntimeResult<Self> {
        Self::builder().build().await
    }

    #[must_use]
    pub fn builder() -> AppContextBuilder {
        AppContextBuilder::new()
    }

    #[must_use]
    pub const fn from_parts(
        data: DataPlane,
        cfg: ConfigPlane,
        plugins: Plugins,
        subsystems: Subsystems,
    ) -> Self {
        Self {
            data,
            cfg,
            plugins,
            subsystems,
        }
    }

    pub fn load_geoip_database(
        config: &Config,
        show_warnings: bool,
    ) -> Result<Option<GeoIpReader>, crate::error::RuntimeError> {
        context_loaders::load_geoip_database(config, show_warnings)
    }

    pub fn load_content_config(
        config: &Config,
        app_paths: &AppPaths,
    ) -> Option<Arc<ContentConfigRaw>> {
        context_loaders::load_content_config(config, app_paths)
    }

    pub fn config(&self) -> &Config {
        &self.cfg.config
    }

    pub fn content_config(&self) -> Option<&ContentConfigRaw> {
        self.cfg.content_config.as_ref().map(AsRef::as_ref)
    }

    pub fn content_routing(&self) -> Option<Arc<dyn ContentRouting>> {
        let concrete = Arc::clone(self.cfg.content_config.as_ref()?);
        let routing: Arc<dyn ContentRouting> = concrete;
        Some(routing)
    }

    pub const fn db_pool(&self) -> &DbPool {
        &self.data.database
    }

    pub fn api_registry(&self) -> &ModuleApiRegistry {
        &self.plugins.api_registry
    }

    pub fn extension_registry(&self) -> &ExtensionRegistry {
        &self.plugins.extension_registry
    }

    pub fn server_address(&self) -> String {
        format!("{}:{}", self.cfg.config.host, self.cfg.config.port)
    }

    pub const fn geoip_reader(&self) -> Option<&GeoIpReader> {
        self.subsystems.geoip_reader.as_ref()
    }

    pub const fn file_storage(&self) -> &Arc<dyn FileStorage> {
        &self.subsystems.file_storage
    }

    pub const fn analytics_service(&self) -> &Arc<AnalyticsService> {
        &self.data.analytics_service
    }

    #[must_use]
    pub fn session_usage(&self) -> systemprompt_traits::DynSessionUsageCounters {
        self.data.analytics_repositories.sessions.owner()
    }

    pub fn context_materializer(&self) -> systemprompt_traits::DynContextMaterializer {
        Arc::new(systemprompt_agent::services::ContextProviderService::new(
            self.data.a2a_repositories.contexts.clone(),
        ))
    }

    pub const fn route_classifier(&self) -> &Arc<RouteClassifier> {
        &self.cfg.route_classifier
    }

    pub fn app_paths(&self) -> &AppPaths {
        &self.cfg.app_paths
    }

    pub const fn app_paths_arc(&self) -> &Arc<AppPaths> {
        &self.cfg.app_paths
    }

    pub fn marketplace_filter(&self) -> &Arc<dyn MarketplaceFilter> {
        &self.plugins.marketplace_filter
    }

    pub const fn marketplace_cache(&self) -> &Arc<MarketplaceCache> {
        &self.plugins.marketplace_cache
    }

    pub const fn event_bridge(&self) -> &Arc<OnceLock<EventBridgeHandle>> {
        &self.subsystems.event_bridge
    }

    // Why: the guard memoises per-entry tree digests across passes; the
    // scheduled job and the manual route share it so neither re-captures a
    // tree the other already published.
    pub const fn publish_guard(&self) -> &Arc<tokio::sync::Mutex<PublishGuard>> {
        &self.subsystems.publish_guard
    }

    pub const fn snapshot_wakeup(&self) -> &Arc<crate::reporting::SnapshotWakeup> {
        &self.subsystems.snapshot_wakeup
    }

    pub fn system_admin(&self) -> &SystemAdmin {
        &self.subsystems.system_admin
    }

    pub const fn mcp_registry(&self) -> &RegistryService {
        &self.plugins.mcp_registry
    }

    pub const fn authz_hook(&self) -> &SharedAuthzHook {
        &self.subsystems.authz_hook
    }

    #[must_use]
    pub fn schema_install(&self) -> &SchemaInstallReport {
        &self.subsystems.schema_install
    }

    pub const fn shutdown_request(&self) -> &ShutdownRequest {
        &self.subsystems.shutdown
    }

    pub fn request_restart(&self, reason: &str) {
        self.subsystems.shutdown.request(reason);
    }
}