laravel-rust-studio 0.1.1

See what a running Laravel for Rust application did: requests with their queries, errors with their source lines, mail, queued jobs, and durable workflows. For you in the browser, and for coding agents over MCP.
Documentation
//! The service provider that installs Studio into an application.

use std::fmt;
use std::sync::Arc;

use laravel::config::app::Environment;
use laravel::config::{Config, Env};
use laravel::container::{Container, Registrar};
use laravel::foundation::ServiceProvider;
use laravel::http::{IntoMiddleware, MiddlewareGroup, Request};
use tracing_subscriber::Layer;
use tracing_subscriber::filter::LevelFilter;

use crate::config::{AuthorizeFn, StudioConfig, StudioGate};
use crate::docs::InstallSkill;
use crate::hooks;
use crate::http;
use crate::layer::StudioLayer;
use crate::store::StudioStore;

/// Installs Studio: its capture of the application's telemetry, its pages and API under `/studio`,
/// its MCP server, and the `studio:skill` command.
///
/// Register it in `src/app.rs`:
///
/// ```no_run
/// use laravel::Application;
/// use laravel_rust_studio::StudioServiceProvider;
///
/// Application::configure().with_providers(|providers| {
///     providers.add(StudioServiceProvider::new());
/// });
/// ```
///
/// Studio answers in the `local` and `testing` environments. Elsewhere it responds `403` and
/// captures nothing, until you decide who may see it with [`authorize`](Self::authorize).
#[derive(Default)]
pub struct StudioServiceProvider {
    authorize: Option<AuthorizeFn>,
    middleware: Option<MiddlewareGroup>,
}

impl StudioServiceProvider {
    /// A provider with Studio's defaults.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Decide which requests may reach Studio, in every environment. A request the callback turns
    /// away gets a `403`.
    ///
    /// ```no_run
    /// use laravel_rust_studio::StudioServiceProvider;
    ///
    /// StudioServiceProvider::new()
    ///     .authorize(|request| request.bearer_token() == Some("a-long-secret"));
    /// ```
    #[must_use]
    pub fn authorize(mut self, check: impl Fn(&Request) -> bool + Send + Sync + 'static) -> Self {
        self.authorize = Some(Arc::new(check));
        self
    }

    /// Run middleware on every Studio route, such as `Authenticate`, or a middleware of your own
    /// that checks the signed-in user.
    ///
    /// Studio's routes then join the `web` middleware group, so the session has started by the
    /// time the middleware runs. Without middleware, they run outside the group, and Studio's
    /// requests start no session.
    ///
    /// The middleware runs after Studio's own check, which still answers only in `local` and
    /// `testing` unless you also [`authorize`](Self::authorize) requests or set
    /// `STUDIO_ALLOW_IN_PRODUCTION`.
    #[must_use]
    pub fn middleware(mut self, middleware: impl IntoMiddleware) -> Self {
        self.middleware = Some(self.middleware.unwrap_or_default().with(middleware));
        self
    }

    /// Whether any request could reach Studio in this environment. When none could, Studio
    /// captures nothing, so an application that ships with Studio installed pays nothing for it
    /// in production.
    fn is_open(&self, config: &Config) -> bool {
        let environment = &config.app.env;

        self.authorize.is_some()
            || environment.is_local()
            || *environment == Environment::Testing
            || config.section::<StudioConfig>().allow_in_production
    }
}

impl fmt::Debug for StudioServiceProvider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StudioServiceProvider")
            .field("authorizes", &self.authorize.is_some())
            .finish_non_exhaustive()
    }
}

impl ServiceProvider for StudioServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
    }

    fn register(&self, app: &mut Registrar) {
        app.commands().add::<InstallSkill>();

        let config = app.config().section::<StudioConfig>().clone();
        if !config.enabled {
            return;
        }

        let environment = app.config().app.env.clone();
        let testing = environment == Environment::Testing;
        let mut allowed_hosts: Vec<String> = config
            .allowed_hosts
            .iter()
            .map(|host| host.trim().to_ascii_lowercase())
            .filter(|host| !host.is_empty())
            .collect();
        allowed_hosts.extend(host_of(&app.config().app.url));
        let gate = StudioGate {
            enabled: true,
            is_local_or_testing: environment.is_local() || testing,
            allow_in_production: config.allow_in_production,
            authorize: self.authorize.clone(),
            allowed_hosts,
        };

        // Tests run side by side in one directory, and each wants only what it captured itself...
        let open = self.is_open(app.config());
        let store = if open && config.journal && !testing {
            StudioStore::with_journal(config.clone(), app.config().app.storage_path("studio"))
        } else {
            StudioStore::new(config.clone())
        };
        app.instance(store.clone());

        if open {
            // `trace` spans and events are the framework's and its dependencies' internals. Leaving
            // them out here also keeps them switched off when no other layer wants them...
            app.logging()
                .layer(StudioLayer::new(store.clone()).with_filter(LevelFilter::DEBUG));
            hooks::register_hooks(app, &store);
        }

        app.routing().assets("studio", laravel::embed!("dist"));

        // A closed Studio keeps its routes, which say why they answer `403`...
        let mount = config.mount_path();
        let in_web_group = self.middleware.is_some();
        let middleware = self.middleware.clone().unwrap_or_default();
        let routes = move |route: &mut laravel::routing::Router| {
            http::register_routes(route, &mount, gate, middleware, store, config.mcp_enabled);
        };
        if in_web_group {
            app.routing().web(routes);
        } else {
            app.routing().routes(routes);
        }
    }

    async fn boot(&self, app: &Container) -> laravel::Result<()> {
        #[cfg(feature = "database")]
        if app.config().section::<StudioConfig>().enabled && self.is_open(app.config()) {
            let store = app.resolve::<StudioStore>().await?;
            hooks::install_db_listener((*store).clone());
        }
        #[cfg(not(feature = "database"))]
        let _ = app;

        Ok(())
    }
}

/// The host of the application's URL, as `app.test` of `https://app.test:8443/`.
fn host_of(url: &str) -> Option<String> {
    let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
    let authority = rest.split(['/', '?', '#']).next()?;
    let host = authority.rsplit_once('@').map_or(authority, |(_, host)| host);
    let host = match host.strip_prefix('[') {
        Some(bracketed) => bracketed.split(']').next()?,
        None => host.split(':').next()?,
    };

    Some(host.to_ascii_lowercase()).filter(|host| !host.is_empty())
}

#[cfg(test)]
mod tests {
    use super::host_of;

    #[test]
    fn the_application_urls_host_is_found() {
        assert_eq!(host_of("https://app.test:8443/path").as_deref(), Some("app.test"));
        assert_eq!(host_of("http://127.0.0.1:8000").as_deref(), Some("127.0.0.1"));
        assert_eq!(host_of("http://[::1]:8000").as_deref(), Some("::1"));
        assert_eq!(
            host_of("https://user:secret@Example.com").as_deref(),
            Some("example.com")
        );
        assert_eq!(host_of(""), None);
    }
}