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