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