OXYGENHUB
# d0fbea2eb46e oxygenhub / crates / hub / src / lib.rs
5.4 KiB · Rust · last changed A job's identity: the hub is an OIDC issuer 1 month ago source blame history raw
8d2caf12 Andy McCall ↶ 1
//! OxygenHub: a forge for Oxygen repositories (`docs/spec.md`).
d23464c0 Andy McCall ↶ 2
//!
3
//! One process: an axum router serving pages, the JSON API and the wire
4
//! protocol; SQLite for hub state; repositories as bare Oxygen stores.
5
6
pub mod api;
ea85398a Andy McCall ↶ 7
pub mod apt;
e71846aa Andy McCall ↶ 8
pub mod assistants;
19bb31ff Andy McCall ↶ 9
pub mod auth;
d23464c0 Andy McCall ↶ 10
pub mod config;
11
pub mod db;
b64e2537 Andy McCall ↶ 12
pub mod events;
42fa9554 Andy McCall ↶ 13
pub mod flow;
b64e2537 Andy McCall ↶ 14
pub mod hooks;
d23464c0 Andy McCall ↶ 15
pub mod keys;
2a83f530 Andy McCall ↶ 16
pub mod levels;
5e6d6484 Andy McCall ↶ 17
pub mod live;
34beb1a7 Andy McCall ↶ 18
pub mod mail;
8a3334b7 Andy McCall ↶ 19
pub mod maintenance;
3f4b0ea6 Andy McCall ↶ 20
pub mod mirror;
18e381ea Andy McCall ↶ 21
pub mod notify;
d1727c57 Andy McCall ↶ 22
pub mod oidc;
d23464c0 Andy McCall ↶ 23
pub mod protocol;
24
pub mod render;
25
pub mod repos;
4ac01a73 Andy McCall ↶ 26
pub mod secrets;
2a83f530 Andy McCall ↶ 27
pub mod variables;
d23464c0 Andy McCall ↶ 28
pub mod web;
29
30
use crate::config::Config;
31
use crate::repos::Repos;
32
use std::sync::Arc;
33
34
/// Everything a request handler can reach.
35
pub struct App {
36
    pub config: Config,
37
    pub db: db::Pool,
38
    pub repos: Arc<Repos>,
39
    pub server: Arc<oxy_server::Server>,
40
    pub hub_key: keys::HubKey,
19bb31ff Andy McCall ↶ 41
    pub cookie_key: auth::CookieKey,
e71846aa Andy McCall ↶ 42
    /// Seals AI assistants' tokens at rest (hub spec §13.4).
43
    pub assistant_key: assistants::SecretKey,
4ac01a73 Andy McCall ↶ 44
    /// Seals Flow secrets at rest (hub spec §13.2, #107).
45
    pub secret_key: assistants::SecretKey,
d1727c57 Andy McCall ↶ 46
    /// The OIDC issuer for jobs (hub spec §13.5), made on first use.
47
    pub oidc: tokio::sync::OnceCell<oidc::Issuer>,
7d2eb590 Andy McCall ↶ 48
    /// Which assistants are answering which proposals, and recent calls
49
    /// per repository (hub spec §13.4).
50
    pub assistant_gate: std::sync::Mutex<assistants::Gate>,
b64e2537 Andy McCall ↶ 51
    pub events: events::Events,
5e6d6484 Andy McCall ↶ 52
    /// Who is resolving which conflict together (hub spec §6.10).
53
    pub rooms: Arc<live::Rooms>,
3556d08e Andy McCall ↶ 54
    /// Outgoing mail: hub.toml's `[email]`, overridden by what the admin
55
    /// page saved (#101).
56
    pub mail: std::sync::RwLock<config::Email>,
d23464c0 Andy McCall ↶ 57
    pub started: std::time::Instant,
58
}
59
d1727c57 Andy McCall ↶ 60
impl App {
61
    /// The OIDC issuer, its key loaded or made the first time it is asked for.
62
    pub async fn oidc(&self) -> anyhow::Result<&oidc::Issuer> {
63
        let keys = self.config.keys_dir();
64
        self.oidc.get_or_try_init(|| async move { tokio::task::spawn_blocking(move || oidc::Issuer::load_or_create(&keys)).await? }).await
65
    }
66
}
67
d23464c0 Andy McCall ↶ 68
pub type Shared = Arc<App>;
69
70
/// Open the data directory and build the application state. `init` must
71
/// have run once; `serve` and the tests call this.
72
pub async fn build(config: Config) -> anyhow::Result<Shared> {
73
    std::fs::create_dir_all(config.repos_dir())?;
74
    let db = db::open(&config.db_path()).await?;
75
    let repos = Arc::new(Repos::new(config.repos_dir()));
76
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
19bb31ff Andy McCall ↶ 77
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
e71846aa Andy McCall ↶ 78
    let assistant_key = assistants::SecretKey::load_or_create(&config.keys_dir())?;
4ac01a73 Andy McCall ↶ 79
    let secret_key = assistants::SecretKey::load_or_create_named(&config.keys_dir(), "secrets.key")?;
d23464c0 Andy McCall ↶ 80
    let backend = protocol::HubBackend::new(repos.clone(), db.clone(), config.auth.push_tokens.clone(), tokio::runtime::Handle::current());
18e381ea Andy McCall ↶ 81
    let slot = backend.app_slot();
d23464c0 Andy McCall ↶ 82
    let server = oxy_server::Server::new(backend);
3556d08e Andy McCall ↶ 83
    let mail = mail::load(&db, &config.email).await;
b64e2537 Andy McCall ↶ 84
    let app = Arc::new(App {
3556d08e Andy McCall ↶ 85
        mail: std::sync::RwLock::new(mail),
b64e2537 Andy McCall ↶ 86
        config,
87
        db,
88
        repos,
89
        server,
90
        hub_key,
91
        cookie_key,
e71846aa Andy McCall ↶ 92
        assistant_key,
4ac01a73 Andy McCall ↶ 93
        secret_key,
d1727c57 Andy McCall ↶ 94
        oidc: tokio::sync::OnceCell::new(),
7d2eb590 Andy McCall ↶ 95
        assistant_gate: std::sync::Mutex::new(assistants::Gate::default()),
b64e2537 Andy McCall ↶ 96
        events: events::Events::default(),
5e6d6484 Andy McCall ↶ 97
        rooms: Arc::new(live::Rooms::default()),
b64e2537 Andy McCall ↶ 98
        started: std::time::Instant::now(),
99
    });
18e381ea Andy McCall ↶ 100
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
b64e2537 Andy McCall ↶ 101
    tokio::spawn(hooks::worker(app.clone()));
070a7b64 Andy McCall ↶ 102
    tokio::spawn(flow::reaper(app.clone()));
348f8c4b Andy McCall ↶ 103
    tokio::spawn(flow::scheduler(app.clone()));
8a3334b7 Andy McCall ↶ 104
    tokio::spawn(maintenance::nightly(app.clone()));
18e381ea Andy McCall ↶ 105
    Ok(app)
d23464c0 Andy McCall ↶ 106
}
107
108
/// The full router: pages, API, protocol and static assets.
109
pub fn router(app: Shared) -> axum::Router {
110
    web::router(app)
111
}
112
113
/// Serve on the configured addresses until the process is told to stop.
114
pub async fn serve(app: Shared) -> anyhow::Result<()> {
115
    let router = router(app.clone());
116
    let http = app.config.bind_addr()?;
117
    let https = app.config.tls_bind_addr()?;
118
    if http.is_none() && https.is_none() {
119
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
120
    }
121
    let mut tasks = tokio::task::JoinSet::new();
122
    if let Some(addr) = http {
123
        let listener = tokio::net::TcpListener::bind(addr).await?;
124
        tracing::info!("http on {addr}");
125
        let r = router.clone();
60f11b71 Andy McCall ↶ 126
        tasks.spawn(async move {
127
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>()).await.map_err(anyhow::Error::from)
128
        });
d23464c0 Andy McCall ↶ 129
    }
130
    if let Some(addr) = https {
131
        let _ = rustls::crypto::ring::default_provider().install_default();
132
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
133
            .await
134
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
135
        tracing::info!("https on {addr}");
136
        let r = router.clone();
60f11b71 Andy McCall ↶ 137
        tasks.spawn(async move {
138
            axum_server::bind_rustls(addr, tls)
139
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
140
                .await
141
                .map_err(anyhow::Error::from)
142
        });
d23464c0 Andy McCall ↶ 143
    }
144
    tokio::select! {
145
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
146
        _ = tokio::signal::ctrl_c() => { tracing::info!("stopping"); Ok(()) }
147
    }
148
}