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