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