OXYGENHUB
# 62cdf34daec1 oxygenhub / crates / hub / src / lib.rs
9.8 KiB · Rust · last changed Diffusion reconciler: every 10 minutes the pin index is checked and mended 20 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
    // Mend the pin index and the bumps it drives (oxygenhub#210).
146
    tokio::spawn(diffusion::reconciler(app.clone()));
147
    // What each image is for, read or learned once (oxygenhub#173).
148
    tokio::spawn({
149
        let app = app.clone();
150
        async move {
151
            match images::learn_archs(&app).await {
152
                Ok(n) if n > 0 => tracing::info!(images = n, "read the architecture of kept images"),
153
                Ok(_) => {}
154
                Err(e) => tracing::warn!(error = %e, "learning image architectures"),
155
            }
156
        }
157
    });
158
    Ok(app)
159
}
160
161
/// The full router: pages, API, protocol and static assets.
162
pub fn router(app: Shared) -> axum::Router {
163
    web::router(app.clone())
164
        .layer(axum::middleware::from_fn_with_state(app, agent_requests))
165
        .layer(axum::middleware::from_fn(private_pages))
166
        .layer(axum::middleware::from_fn(slow_requests))
167
}
168
169
/// A request made with a token its owner marked as an agent's runs with
170
/// that token's name in [`notify::AGENT`], so what the agent does is told
171
/// to its owner (oxygenhub#183).
172
async fn agent_requests(
173
    axum::extract::State(app): axum::extract::State<Shared>,
174
    req: axum::extract::Request,
175
    next: axum::middleware::Next,
176
) -> axum::response::Response {
177
    let token = req
178
        .headers()
179
        .get(axum::http::header::AUTHORIZATION)
180
        .and_then(|v| v.to_str().ok())
181
        .and_then(|v| v.strip_prefix("Bearer "))
182
        .map(|t| auth::token_hash(t.trim()));
183
    let agent = match token {
184
        Some(hash) => db::accounts::token_by_hash(&app.db, &hash).await.ok().flatten().filter(|t| t.agent).map(|t| t.name),
185
        None => None,
186
    };
187
    notify::AGENT.scope(agent, next.run(req)).await
188
}
189
190
/// Requests slower than this are logged, with their path (#145).
191
const SLOW: std::time::Duration = std::time::Duration::from_secs(2);
192
193
/// Log a slow request's method, path and time, so a slow page can be
194
/// found afterwards. Never the query, which may hold a token.
195
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
196
    let (method, path) = (req.method().clone(), req.uri().path().to_string());
197
    let start = std::time::Instant::now();
198
    let res = next.run(req).await;
199
    let took = start.elapsed();
200
    if took >= SLOW {
201
        tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16());
202
    }
203
    res
204
}
205
206
/// A page for a signed-in viewer is theirs alone: it may list private
207
/// repositories, and the dashboard's sky carries their activity (#157). An
208
/// HTML response to a request with a session cookie, which has not said
209
/// how to cache itself, says `private, no-store`, so no shared cache (a
210
/// proxy or a CDN in front of the hub) ever serves it to anyone else.
211
async fn private_pages(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
212
    use axum::http::header;
213
    let signed_in = req
214
        .headers()
215
        .get_all(header::COOKIE)
216
        .iter()
217
        .filter_map(|v| v.to_str().ok())
218
        .any(|c| c.split(';').any(|kv| kv.trim_start().starts_with("oxyhub=")));
219
    let mut res = next.run(req).await;
220
    let html = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/html"));
221
    if signed_in && html && !res.headers().contains_key(header::CACHE_CONTROL) {
222
        res.headers_mut().insert(header::CACHE_CONTROL, header::HeaderValue::from_static("private, no-store"));
223
    }
224
    res
225
}
226
227
/// Serve on the configured addresses until the process is told to stop.
228
pub async fn serve(app: Shared) -> anyhow::Result<()> {
229
    let router = router(app.clone());
230
    let http = app.config.bind_addr()?;
231
    let https = app.config.tls_bind_addr()?;
232
    if http.is_none() && https.is_none() {
233
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
234
    }
235
    let mut tasks = tokio::task::JoinSet::new();
236
    if let Some(addr) = http {
237
        let listener = tokio::net::TcpListener::bind(addr).await?;
238
        tracing::info!("http on {addr}");
239
        let r = router.clone();
240
        tasks.spawn(async move {
241
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>()).await.map_err(anyhow::Error::from)
242
        });
243
    }
244
    if let Some(addr) = https {
245
        let _ = rustls::crypto::ring::default_provider().install_default();
246
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
247
            .await
248
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
249
        tracing::info!("https on {addr}");
250
        let r = router.clone();
251
        tasks.spawn(async move {
252
            axum_server::bind_rustls(addr, tls)
253
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
254
                .await
255
                .map_err(anyhow::Error::from)
256
        });
257
    }
258
    tokio::select! {
259
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
260
        _ = tokio::signal::ctrl_c() => { tracing::info!("stopping"); Ok(()) }
261
    }
262
}