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