OXYGENHUB
# d7ce41acf22c 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
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 apt;
8
pub mod auth;
9
pub mod config;
10
pub mod db;
11
pub mod events;
12
pub mod flow;
13
pub mod hooks;
14
pub mod keys;
15
pub mod live;
16
pub mod mail;
17
pub mod mirror;
18
pub mod notify;
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,
35
    pub cookie_key: auth::CookieKey,
36
    pub events: events::Events,
37
    /// Who is resolving which conflict together (hub spec §6.10).
38
    pub rooms: Arc<live::Rooms>,
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())?;
51
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
52
    let backend = protocol::HubBackend::new(repos.clone(), db.clone(), config.auth.push_tokens.clone(), tokio::runtime::Handle::current());
53
    let slot = backend.app_slot();
54
    let server = oxy_server::Server::new(backend);
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(),
63
        rooms: Arc::new(live::Rooms::default()),
64
        started: std::time::Instant::now(),
65
    });
66
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
67
    tokio::spawn(hooks::worker(app.clone()));
68
    tokio::spawn(flow::reaper(app.clone()));
69
    Ok(app)
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();
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
        });
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();
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
        });
107
    }
108
    tokio::select! {
109
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
110
        _ = tokio::signal::ctrl_c() => { tracing::info!("stopping"); Ok(()) }
111
    }
112
}