OXYGENHUB
◆ v0.3.1 oxygenhub / crates / hub / src / lib.rs
3.9 KiB · Rust · last changed Scheduled runs: on { schedule } jobs start on the default bookmark when due 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
    tokio::spawn(flow::scheduler(app.clone()));
70
    Ok(app)
71
}
72
73
/// The full router: pages, API, protocol and static assets.
74
pub fn router(app: Shared) -> axum::Router {
75
    web::router(app)
76
}
77
78
/// Serve on the configured addresses until the process is told to stop.
79
pub async fn serve(app: Shared) -> anyhow::Result<()> {
80
    let router = router(app.clone());
81
    let http = app.config.bind_addr()?;
82
    let https = app.config.tls_bind_addr()?;
83
    if http.is_none() && https.is_none() {
84
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
85
    }
86
    let mut tasks = tokio::task::JoinSet::new();
87
    if let Some(addr) = http {
88
        let listener = tokio::net::TcpListener::bind(addr).await?;
89
        tracing::info!("http on {addr}");
90
        let r = router.clone();
91
        tasks.spawn(async move {
92
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>()).await.map_err(anyhow::Error::from)
93
        });
94
    }
95
    if let Some(addr) = https {
96
        let _ = rustls::crypto::ring::default_provider().install_default();
97
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
98
            .await
99
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
100
        tracing::info!("https on {addr}");
101
        let r = router.clone();
102
        tasks.spawn(async move {
103
            axum_server::bind_rustls(addr, tls)
104
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
105
                .await
106
                .map_err(anyhow::Error::from)
107
        });
108
    }
109
    tokio::select! {
110
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
111
        _ = tokio::signal::ctrl_c() => { tracing::info!("stopping"); Ok(()) }
112
    }
113
}