Skip to main content

AppState

Trait AppState 

Source
pub trait AppState:
    Clone
    + Send
    + Sync
    + 'static {
    // Required methods
    fn version(&self) -> &str;
    fn db(&self) -> &PgPool;
    fn cookie_key(&self) -> &CookieKey;

    // Provided methods
    fn job_enqueued(&self) { ... }
    fn eyes_base_url(&self) -> Option<&str> { ... }
    fn eyes_http_monitors(&self) -> Vec<HttpMonitor> { ... }
}
Expand description

A trait representing the application state that must be implemented by users of the cja framework.

This trait provides access to core components like the database pool and cookie encryption key. The AppState is cloned for each request, so it should be cheap to clone (usually by wrapping expensive resources in Arc).

§Example

use cja::app_state::AppState;
use cja::server::cookies::CookieKey;
use sqlx::PgPool;

#[derive(Clone)]
struct MyAppState {
    db: PgPool,
    cookie_key: CookieKey,
}

impl AppState for MyAppState {
    fn version(&self) -> &str {
        "1.0.0"
    }
     
    fn db(&self) -> &PgPool {
        &self.db
    }
     
    fn cookie_key(&self) -> &CookieKey {
        &self.cookie_key
    }
}

§Using with Axum

use cja::app_state::AppState;
use cja::server::cookies::CookieKey;
use sqlx::postgres::PgPoolOptions;
use axum::{Router, routing::get, extract::State};

#[derive(Clone)]
struct MyAppState {
    db: sqlx::PgPool,
    cookie_key: CookieKey,
}

impl AppState for MyAppState {
    fn version(&self) -> &str { "1.0.0" }
    fn db(&self) -> &sqlx::PgPool { &self.db }
    fn cookie_key(&self) -> &CookieKey { &self.cookie_key }
}

async fn handler(State(state): State<MyAppState>) -> String {
    format!("App version: {}", state.version())
}

 async fn example() -> Result<(), Box<dyn std::error::Error>> {
 use sqlx::postgres::PgPoolOptions;
let db = PgPoolOptions::new()
     .connect(&std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://test".to_string()))
     .await
     .map_err(|_| "Database connection failed")?;
     
let state = MyAppState {
    db,
    cookie_key: CookieKey::from_env_or_generate()?,
};

let app: Router = Router::new()
    .route("/", get(handler))
    .with_state(state);

// Run the server

Required Methods§

Source

fn version(&self) -> &str

Returns the version string for the application. This is useful for health checks and debugging.

Source

fn db(&self) -> &PgPool

Returns a reference to the database connection pool. The pool is typically shared across all requests.

Source

fn cookie_key(&self) -> &CookieKey

Returns the cookie encryption key used for secure cookies. This key should be consistent across application restarts to maintain session continuity.

Provided Methods§

Source

fn job_enqueued(&self)

Called after a successful autocommit job enqueue. An override may wake a process-local idle poll gate; this is not a transaction-commit hook.

Source

fn eyes_base_url(&self) -> Option<&str>

Returns the application’s public HTTP(S) origin or base URL for Eyes monitors.

Root-relative monitor targets use URL join semantics and therefore discard any path component here (https://example.com/app plus /health becomes https://example.com/health). Path-prefixed apps should declare absolute monitor targets instead.

Source

fn eyes_http_monitors(&self) -> Vec<HttpMonitor>

Returns the app-level HTTP monitors reported to Eyes.

Monitor IDs must be stable identifiers. Applications can use the cja re-export without depending on eyes-subscriber directly:

use cja::eyes_subscriber::{HttpMethod, HttpMonitor};
let monitors = vec![
    HttpMonitor::new("health", "/health"),
    HttpMonitor::new("headers", "https://example.com/").method(HttpMethod::Head),
];
assert_eq!(monitors.len(), 2);

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§