OXYGENHUB
# 4f37afcc3583 oxygenhub / crates / hub / src / lib.rs
3.8 KiB · Rust · last changed Serve the releases' .debs as a signed apt repository at /apt 1 month ago source blame history raw
8d2caf12 Andy McCall ↶ 1
//! OxygenHub: a forge for Oxygen repositories (`docs/spec.md`).
d23464c0 Andy McCall ↶ 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;
ea85398a Andy McCall ↶ 7
pub mod apt;
19bb31ff Andy McCall ↶ 8
pub mod auth;
d23464c0 Andy McCall ↶ 9
pub mod config;
10
pub mod db;
b64e2537 Andy McCall ↶ 11
pub mod events;
42fa9554 Andy McCall ↶ 12
pub mod flow;
b64e2537 Andy McCall ↶ 13
pub mod hooks;
d23464c0 Andy McCall ↶ 14
pub mod keys;
5e6d6484 Andy McCall ↶ 15
pub mod live;
34beb1a7 Andy McCall ↶ 16
pub mod mail;
3f4b0ea6 Andy McCall ↶ 17
pub mod mirror;
18e381ea Andy McCall ↶ 18
pub mod notify;
d23464c0 Andy McCall ↶ 19
pub mod protocol;
20
pub mod render;
21
pub mod repos;
22
pub mod web;
23
24
use crate::config::Config;
25
use crate::repos::Repos;
26
use std::sync::Arc;
27
28
/// Everything a request handler can reach.
29
pub struct App {
30
    pub config: Config,
31
    pub db: db::Pool,
32
    pub repos: Arc<Repos>,
33
    pub server: Arc<oxy_server::Server>,
34
    pub hub_key: keys::HubKey,
19bb31ff Andy McCall ↶ 35
    pub cookie_key: auth::CookieKey,
b64e2537 Andy McCall ↶ 36
    pub events: events::Events,
5e6d6484 Andy McCall ↶ 37
    /// Who is resolving which conflict together (hub spec §6.10).
38
    pub rooms: Arc<live::Rooms>,
d23464c0 Andy McCall ↶ 39
    pub started: std::time::Instant,
40
}
41
42
pub type Shared = Arc<App>;
43
44
/// Open the data directory and build the application state. `init` must
45
/// have run once; `serve` and the tests call this.
46
pub async fn build(config: Config) -> anyhow::Result<Shared> {
47
    std::fs::create_dir_all(config.repos_dir())?;
48
    let db = db::open(&config.db_path()).await?;
49
    let repos = Arc::new(Repos::new(config.repos_dir()));
50
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
19bb31ff Andy McCall ↶ 51
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
d23464c0 Andy McCall ↶ 52
    let backend = protocol::HubBackend::new(repos.clone(), db.clone(), config.auth.push_tokens.clone(), tokio::runtime::Handle::current());
18e381ea Andy McCall ↶ 53
    let slot = backend.app_slot();
d23464c0 Andy McCall ↶ 54
    let server = oxy_server::Server::new(backend);
b64e2537 Andy McCall ↶ 55
    let app = Arc::new(App {
56
        config,
57
        db,
58
        repos,
59
        server,
60
        hub_key,
61
        cookie_key,
62
        events: events::Events::default(),
5e6d6484 Andy McCall ↶ 63
        rooms: Arc::new(live::Rooms::default()),
b64e2537 Andy McCall ↶ 64
        started: std::time::Instant::now(),
65
    });
18e381ea Andy McCall ↶ 66
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
b64e2537 Andy McCall ↶ 67
    tokio::spawn(hooks::worker(app.clone()));
070a7b64 Andy McCall ↶ 68
    tokio::spawn(flow::reaper(app.clone()));
18e381ea Andy McCall ↶ 69
    Ok(app)
d23464c0 Andy McCall ↶ 70
}
71
72
/// The full router: pages, API, protocol and static assets.
73
pub fn router(app: Shared) -> axum::Router {
74
    web::router(app)
75
}
76
77
/// Serve on the configured addresses until the process is told to stop.
78
pub async fn serve(app: Shared) -> anyhow::Result<()> {
79
    let router = router(app.clone());
80
    let http = app.config.bind_addr()?;
81
    let https = app.config.tls_bind_addr()?;
82
    if http.is_none() && https.is_none() {
83
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
84
    }
85
    let mut tasks = tokio::task::JoinSet::new();
86
    if let Some(addr) = http {
87
        let listener = tokio::net::TcpListener::bind(addr).await?;
88
        tracing::info!("http on {addr}");
89
        let r = router.clone();
60f11b71 Andy McCall ↶ 90
        tasks.spawn(async move {
91
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>()).await.map_err(anyhow::Error::from)
92
        });
d23464c0 Andy McCall ↶ 93
    }
94
    if let Some(addr) = https {
95
        let _ = rustls::crypto::ring::default_provider().install_default();
96
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
97
            .await
98
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
99
        tracing::info!("https on {addr}");
100
        let r = router.clone();
60f11b71 Andy McCall ↶ 101
        tasks.spawn(async move {
102
            axum_server::bind_rustls(addr, tls)
103
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
104
                .await
105
                .map_err(anyhow::Error::from)
106
        });
d23464c0 Andy McCall ↶ 107
    }
108
    tokio::select! {
109
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
110
        _ = tokio::signal::ctrl_c() => { tracing::info!("stopping"); Ok(()) }
111
    }
112
}