OXYGENHUB
# 3556d08e17f9 oxygenhub / crates / hub / src / lib.rs
4.2 KiB · Rust · last changed Mail settings on the admin page, with a test message 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;
8a3334b7 Andy McCall ↶ 17
pub mod maintenance;
3f4b0ea6 Andy McCall ↶ 18
pub mod mirror;
18e381ea Andy McCall ↶ 19
pub mod notify;
d23464c0 Andy McCall ↶ 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,
19bb31ff Andy McCall ↶ 36
    pub cookie_key: auth::CookieKey,
b64e2537 Andy McCall ↶ 37
    pub events: events::Events,
5e6d6484 Andy McCall ↶ 38
    /// Who is resolving which conflict together (hub spec §6.10).
39
    pub rooms: Arc<live::Rooms>,
3556d08e Andy McCall ↶ 40
    /// Outgoing mail: hub.toml's `[email]`, overridden by what the admin
41
    /// page saved (#101).
42
    pub mail: std::sync::RwLock<config::Email>,
d23464c0 Andy McCall ↶ 43
    pub started: std::time::Instant,
44
}
45
46
pub type Shared = Arc<App>;
47
48
/// Open the data directory and build the application state. `init` must
49
/// have run once; `serve` and the tests call this.
50
pub async fn build(config: Config) -> anyhow::Result<Shared> {
51
    std::fs::create_dir_all(config.repos_dir())?;
52
    let db = db::open(&config.db_path()).await?;
53
    let repos = Arc::new(Repos::new(config.repos_dir()));
54
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
19bb31ff Andy McCall ↶ 55
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
d23464c0 Andy McCall ↶ 56
    let backend = protocol::HubBackend::new(repos.clone(), db.clone(), config.auth.push_tokens.clone(), tokio::runtime::Handle::current());
18e381ea Andy McCall ↶ 57
    let slot = backend.app_slot();
d23464c0 Andy McCall ↶ 58
    let server = oxy_server::Server::new(backend);
3556d08e Andy McCall ↶ 59
    let mail = mail::load(&db, &config.email).await;
b64e2537 Andy McCall ↶ 60
    let app = Arc::new(App {
3556d08e Andy McCall ↶ 61
        mail: std::sync::RwLock::new(mail),
b64e2537 Andy McCall ↶ 62
        config,
63
        db,
64
        repos,
65
        server,
66
        hub_key,
67
        cookie_key,
68
        events: events::Events::default(),
5e6d6484 Andy McCall ↶ 69
        rooms: Arc::new(live::Rooms::default()),
b64e2537 Andy McCall ↶ 70
        started: std::time::Instant::now(),
71
    });
18e381ea Andy McCall ↶ 72
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
b64e2537 Andy McCall ↶ 73
    tokio::spawn(hooks::worker(app.clone()));
070a7b64 Andy McCall ↶ 74
    tokio::spawn(flow::reaper(app.clone()));
348f8c4b Andy McCall ↶ 75
    tokio::spawn(flow::scheduler(app.clone()));
8a3334b7 Andy McCall ↶ 76
    tokio::spawn(maintenance::nightly(app.clone()));
18e381ea Andy McCall ↶ 77
    Ok(app)
d23464c0 Andy McCall ↶ 78
}
79
80
/// The full router: pages, API, protocol and static assets.
81
pub fn router(app: Shared) -> axum::Router {
82
    web::router(app)
83
}
84
85
/// Serve on the configured addresses until the process is told to stop.
86
pub async fn serve(app: Shared) -> anyhow::Result<()> {
87
    let router = router(app.clone());
88
    let http = app.config.bind_addr()?;
89
    let https = app.config.tls_bind_addr()?;
90
    if http.is_none() && https.is_none() {
91
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
92
    }
93
    let mut tasks = tokio::task::JoinSet::new();
94
    if let Some(addr) = http {
95
        let listener = tokio::net::TcpListener::bind(addr).await?;
96
        tracing::info!("http on {addr}");
97
        let r = router.clone();
60f11b71 Andy McCall ↶ 98
        tasks.spawn(async move {
99
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>()).await.map_err(anyhow::Error::from)
100
        });
d23464c0 Andy McCall ↶ 101
    }
102
    if let Some(addr) = https {
103
        let _ = rustls::crypto::ring::default_provider().install_default();
104
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
105
            .await
106
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
107
        tracing::info!("https on {addr}");
108
        let r = router.clone();
60f11b71 Andy McCall ↶ 109
        tasks.spawn(async move {
110
            axum_server::bind_rustls(addr, tls)
111
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
112
                .await
113
                .map_err(anyhow::Error::from)
114
        });
d23464c0 Andy McCall ↶ 115
    }
116
    tokio::select! {
117
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
118
        _ = tokio::signal::ctrl_c() => { tracing::info!("stopping"); Ok(()) }
119
    }
120
}