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