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