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