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