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