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