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