OXYGENHUB
# 16cb2b3aa947 oxygenhub / crates / hub / src / lib.rs
3.4 KiB · Rust · last changed OxygenFlow runs: pushes start pipeline runs, a runner API with job tokens, jobs as checks, and a Flow tab with the job graph and live logs 1 month 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 auth;
8
pub mod config;
9
pub mod db;
10
pub mod events;
11
pub mod flow;
12
pub mod hooks;
13
pub mod keys;
14
pub mod mirror;
15
pub mod notify;
16
pub mod protocol;
17
pub mod render;
18
pub mod repos;
19
pub mod web;
20
21
use crate::config::Config;
22
use crate::repos::Repos;
23
use std::sync::Arc;
24
25
/// Everything a request handler can reach.
26
pub struct App {
27
    pub config: Config,
28
    pub db: db::Pool,
29
    pub repos: Arc<Repos>,
30
    pub server: Arc<oxy_server::Server>,
31
    pub hub_key: keys::HubKey,
32
    pub cookie_key: auth::CookieKey,
33
    pub events: events::Events,
34
    pub started: std::time::Instant,
35
}
36
37
pub type Shared = Arc<App>;
38
39
/// Open the data directory and build the application state. `init` must
40
/// have run once; `serve` and the tests call this.
41
pub async fn build(config: Config) -> anyhow::Result<Shared> {
42
    std::fs::create_dir_all(config.repos_dir())?;
43
    let db = db::open(&config.db_path()).await?;
44
    let repos = Arc::new(Repos::new(config.repos_dir()));
45
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
46
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
47
    let backend = protocol::HubBackend::new(repos.clone(), db.clone(), config.auth.push_tokens.clone(), tokio::runtime::Handle::current());
48
    let slot = backend.app_slot();
49
    let server = oxy_server::Server::new(backend);
50
    let app = Arc::new(App {
51
        config,
52
        db,
53
        repos,
54
        server,
55
        hub_key,
56
        cookie_key,
57
        events: events::Events::default(),
58
        started: std::time::Instant::now(),
59
    });
60
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
61
    tokio::spawn(hooks::worker(app.clone()));
62
    Ok(app)
63
}
64
65
/// The full router: pages, API, protocol and static assets.
66
pub fn router(app: Shared) -> axum::Router {
67
    web::router(app)
68
}
69
70
/// Serve on the configured addresses until the process is told to stop.
71
pub async fn serve(app: Shared) -> anyhow::Result<()> {
72
    let router = router(app.clone());
73
    let http = app.config.bind_addr()?;
74
    let https = app.config.tls_bind_addr()?;
75
    if http.is_none() && https.is_none() {
76
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
77
    }
78
    let mut tasks = tokio::task::JoinSet::new();
79
    if let Some(addr) = http {
80
        let listener = tokio::net::TcpListener::bind(addr).await?;
81
        tracing::info!("http on {addr}");
82
        let r = router.clone();
83
        tasks.spawn(async move { axum::serve(listener, r).await.map_err(anyhow::Error::from) });
84
    }
85
    if let Some(addr) = https {
86
        let _ = rustls::crypto::ring::default_provider().install_default();
87
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
88
            .await
89
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
90
        tracing::info!("https on {addr}");
91
        let r = router.clone();
92
        tasks.spawn(async move { axum_server::bind_rustls(addr, tls).serve(r.into_make_service()).await.map_err(anyhow::Error::from) });
93
    }
94
    tokio::select! {
95
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
96
        _ = tokio::signal::ctrl_c() => { tracing::info!("stopping"); Ok(()) }
97
    }
98
}