OXYGENHUB
# 0cd118748131 oxygenhub / crates / hub / src / lib.rs
8.8 KiB · Rust · last changed The hub reads what each image is for, and learns the rest from passes 22 days ago source blame history raw
1
//! OxygenHub: a forge for Oxygen repositories (`docs/spec.md`).
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;
7
pub mod apt;
8
pub mod assistants;
9
pub mod auth;
10
pub mod backups;
11
pub mod config;
12
pub mod coverage;
13
pub mod db;
14
pub mod diffusion;
15
pub mod events;
16
pub mod flow;
17
pub mod hooks;
18
pub mod images;
19
pub mod junit;
20
pub mod keys;
21
pub mod levels;
22
pub mod live;
23
pub mod mail;
24
pub mod maintenance;
25
pub mod mirror;
26
pub mod notify;
27
pub mod oidc;
28
pub mod protocol;
29
pub mod render;
30
pub mod reports;
31
pub mod repos;
32
pub mod secrets;
33
pub mod signin;
34
pub mod social;
35
pub mod storage;
36
pub mod swarm;
37
pub mod variables;
38
pub mod web;
39
pub mod wiki;
40
41
use crate::config::Config;
42
use crate::repos::Repos;
43
use std::sync::Arc;
44
45
/// Everything a request handler can reach.
46
pub struct App {
47
    pub config: Config,
48
    pub db: db::Pool,
49
    pub repos: Arc<Repos>,
50
    /// Wikis, one Oxygen repository per repository (hub spec §6.11).
51
    pub wikis: Arc<Repos>,
52
    pub server: Arc<oxy_server::Server>,
53
    pub hub_key: keys::HubKey,
54
    pub cookie_key: auth::CookieKey,
55
    /// Seals AI assistants' tokens at rest (hub spec §13.4).
56
    pub assistant_key: assistants::SecretKey,
57
    /// Seals Flow secrets at rest (hub spec §13.2, #107).
58
    pub secret_key: assistants::SecretKey,
59
    /// The OIDC issuer for jobs (hub spec §13.5), made on first use.
60
    pub oidc: tokio::sync::OnceCell<oidc::Issuer>,
61
    /// Which assistants are answering which proposals, and recent calls
62
    /// per repository (hub spec §13.4).
63
    pub assistant_gate: std::sync::Mutex<assistants::Gate>,
64
    pub events: events::Events,
65
    /// Who is resolving which conflict together (hub spec §6.10).
66
    pub rooms: Arc<live::Rooms>,
67
    /// Outgoing mail: hub.toml's `[email]`, overridden by what the admin
68
    /// page saved (#101).
69
    pub mail: std::sync::RwLock<config::Email>,
70
    /// The image swarm's tracker (oxygenhub#144).
71
    pub swarm: swarm::Tracker,
72
    pub started: std::time::Instant,
73
}
74
75
impl App {
76
    /// The rootfs images this hub keeps for runners (oxygenflow#39).
77
    pub fn images(&self) -> images::Store {
78
        images::Store::new(&self.config.data)
79
    }
80
81
    /// The OIDC issuer, its key loaded or made the first time it is asked for.
82
    pub async fn oidc(&self) -> anyhow::Result<&oidc::Issuer> {
83
        let keys = self.config.keys_dir();
84
        self.oidc.get_or_try_init(|| async move { tokio::task::spawn_blocking(move || oidc::Issuer::load_or_create(&keys)).await? }).await
85
    }
86
}
87
88
pub type Shared = Arc<App>;
89
90
/// Open the data directory and build the application state. `init` must
91
/// have run once; `serve` and the tests call this.
92
pub async fn build(config: Config) -> anyhow::Result<Shared> {
93
    std::fs::create_dir_all(config.repos_dir())?;
94
    let db = db::open(&config.db_path()).await?;
95
    let repos = Arc::new(Repos::new(config.repos_dir()));
96
    let wikis = Arc::new(Repos::new(config.data.join("wikis")));
97
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
98
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
99
    let assistant_key = assistants::SecretKey::load_or_create(&config.keys_dir())?;
100
    let secret_key = assistants::SecretKey::load_or_create_named(&config.keys_dir(), "secrets.key")?;
101
    let backend = protocol::HubBackend::new(
102
        repos.clone(),
103
        wikis.clone(),
104
        db.clone(),
105
        config.auth.push_tokens.clone(),
106
        tokio::runtime::Handle::current(),
107
    );
108
    let slot = backend.app_slot();
109
    let server = oxy_server::Server::new(backend);
110
    let mail = mail::load(&db, &config.email).await;
111
    let app = Arc::new(App {
112
        mail: std::sync::RwLock::new(mail),
113
        config,
114
        db,
115
        repos,
116
        wikis,
117
        server,
118
        hub_key,
119
        cookie_key,
120
        assistant_key,
121
        secret_key,
122
        oidc: tokio::sync::OnceCell::new(),
123
        assistant_gate: std::sync::Mutex::new(assistants::Gate::default()),
124
        events: events::Events::default(),
125
        rooms: Arc::new(live::Rooms::default()),
126
        swarm: Default::default(),
127
        started: std::time::Instant::now(),
128
    });
129
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
130
    storage::load(&app).await?;
131
    coverage::load(&app).await?;
132
    junit::load(&app).await?;
133
    reports::load(&app).await?;
134
    tokio::spawn(hooks::worker(app.clone()));
135
    tokio::spawn(flow::reaper(app.clone()));
136
    tokio::spawn(flow::scheduler(app.clone()));
137
    tokio::spawn(flow::placement(app.clone()));
138
    tokio::spawn(maintenance::nightly(app.clone()));
139
    tokio::spawn(backups::scheduler(app.clone()));
140
    // The reverse pin index for repositories pushed before it existed (#148).
141
    tokio::spawn({
142
        let app = app.clone();
143
        async move { diffusion::backfill(&app).await }
144
    });
145
    // What each image is for, read or learned once (oxygenhub#173).
146
    tokio::spawn({
147
        let app = app.clone();
148
        async move {
149
            match images::learn_archs(&app).await {
150
                Ok(n) if n > 0 => tracing::info!(images = n, "read the architecture of kept images"),
151
                Ok(_) => {}
152
                Err(e) => tracing::warn!(error = %e, "learning image architectures"),
153
            }
154
        }
155
    });
156
    Ok(app)
157
}
158
159
/// The full router: pages, API, protocol and static assets.
160
pub fn router(app: Shared) -> axum::Router {
161
    web::router(app).layer(axum::middleware::from_fn(private_pages)).layer(axum::middleware::from_fn(slow_requests))
162
}
163
164
/// Requests slower than this are logged, with their path (#145).
165
const SLOW: std::time::Duration = std::time::Duration::from_secs(2);
166
167
/// Log a slow request's method, path and time, so a slow page can be
168
/// found afterwards. Never the query, which may hold a token.
169
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
170
    let (method, path) = (req.method().clone(), req.uri().path().to_string());
171
    let start = std::time::Instant::now();
172
    let res = next.run(req).await;
173
    let took = start.elapsed();
174
    if took >= SLOW {
175
        tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16());
176
    }
177
    res
178
}
179
180
/// A page for a signed-in viewer is theirs alone: it may list private
181
/// repositories, and the dashboard's sky carries their activity (#157). An
182
/// HTML response to a request with a session cookie, which has not said
183
/// how to cache itself, says `private, no-store`, so no shared cache (a
184
/// proxy or a CDN in front of the hub) ever serves it to anyone else.
185
async fn private_pages(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
186
    use axum::http::header;
187
    let signed_in = req
188
        .headers()
189
        .get_all(header::COOKIE)
190
        .iter()
191
        .filter_map(|v| v.to_str().ok())
192
        .any(|c| c.split(';').any(|kv| kv.trim_start().starts_with("oxyhub=")));
193
    let mut res = next.run(req).await;
194
    let html = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html"));
195
    if signed_in && html && !res.headers().contains_key(header::CACHE_CONTROL) {
196
        res.headers_mut().insert(header::CACHE_CONTROL, header::HeaderValue::from_static("private, no-store"));
197
    }
198
    res
199
}
200
201
/// Serve on the configured addresses until the process is told to stop.
202
pub async fn serve(app: Shared) -> anyhow::Result<()> {
203
    let router = router(app.clone());
204
    let http = app.config.bind_addr()?;
205
    let https = app.config.tls_bind_addr()?;
206
    if http.is_none() && https.is_none() {
207
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
208
    }
209
    let mut tasks = tokio::task::JoinSet::new();
210
    if let Some(addr) = http {
211
        let listener = tokio::net::TcpListener::bind(addr).await?;
212
        tracing::info!("http on {addr}");
213
        let r = router.clone();
214
        tasks.spawn(async move {
215
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>()).await.map_err(anyhow::Error::from)
216
        });
217
    }
218
    if let Some(addr) = https {
219
        let _ = rustls::crypto::ring::default_provider().install_default();
220
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
221
            .await
222
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
223
        tracing::info!("https on {addr}");
224
        let r = router.clone();
225
        tasks.spawn(async move {
226
            axum_server::bind_rustls(addr, tls)
227
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
228
                .await
229
                .map_err(anyhow::Error::from)
230
        });
231
    }
232
    tokio::select! {
233
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
234
        _ = tokio::signal::ctrl_c() => { tracing::info!("stopping"); Ok(()) }
235
    }
236
}