OXYGENHUB
# 39442b000e6b oxygenhub / crates / hub / src / lib.rs
4.1 KiB · Rust · last changed Keep bookmark briefs across restarts, and log slow requests 24 days ago source blame history raw
d23464c0 Andy McCall ↶ 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;
19bb31ff Andy McCall ↶ 7
pub mod auth;
d23464c0 Andy McCall ↶ 8
pub mod config;
9
pub mod db;
b64e2537 Andy McCall ↶ 10
pub mod events;
42fa9554 Andy McCall ↶ 11
pub mod flow;
b64e2537 Andy McCall ↶ 12
pub mod hooks;
d23464c0 Andy McCall ↶ 13
pub mod keys;
3f4b0ea6 Andy McCall ↶ 14
pub mod mirror;
18e381ea Andy McCall ↶ 15
pub mod notify;
d23464c0 Andy McCall ↶ 16
pub mod protocol;
17
pub mod render;
18
pub mod repos;
19
pub mod web;
20
21
use crate::config::Config;
22
use crate::repos::Repos;
23
use std::sync::Arc;
24
25
/// Everything a request handler can reach.
26
pub struct App {
27
    pub config: Config,
28
    pub db: db::Pool,
29
    pub repos: Arc<Repos>,
30
    pub server: Arc<oxy_server::Server>,
31
    pub hub_key: keys::HubKey,
19bb31ff Andy McCall ↶ 32
    pub cookie_key: auth::CookieKey,
b64e2537 Andy McCall ↶ 33
    pub events: events::Events,
d23464c0 Andy McCall ↶ 34
    pub started: std::time::Instant,
35
}
36
37
pub type Shared = Arc<App>;
38
39
/// Open the data directory and build the application state. `init` must
40
/// have run once; `serve` and the tests call this.
41
pub async fn build(config: Config) -> anyhow::Result<Shared> {
42
    std::fs::create_dir_all(config.repos_dir())?;
43
    let db = db::open(&config.db_path()).await?;
44
    let repos = Arc::new(Repos::new(config.repos_dir()));
45
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
19bb31ff Andy McCall ↶ 46
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
d23464c0 Andy McCall ↶ 47
    let backend = protocol::HubBackend::new(repos.clone(), db.clone(), config.auth.push_tokens.clone(), tokio::runtime::Handle::current());
18e381ea Andy McCall ↶ 48
    let slot = backend.app_slot();
d23464c0 Andy McCall ↶ 49
    let server = oxy_server::Server::new(backend);
b64e2537 Andy McCall ↶ 50
    let app = Arc::new(App {
51
        config,
52
        db,
53
        repos,
54
        server,
55
        hub_key,
56
        cookie_key,
57
        events: events::Events::default(),
58
        started: std::time::Instant::now(),
59
    });
18e381ea Andy McCall ↶ 60
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
b64e2537 Andy McCall ↶ 61
    tokio::spawn(hooks::worker(app.clone()));
18e381ea Andy McCall ↶ 62
    Ok(app)
d23464c0 Andy McCall ↶ 63
}
64
65
/// The full router: pages, API, protocol and static assets.
66
pub fn router(app: Shared) -> axum::Router {
39442b00 Andy McCall ↶ 67
    web::router(app).layer(axum::middleware::from_fn(slow_requests))
d23464c0 Andy McCall ↶ 68
}
69
39442b00 Andy McCall ↶ 70
/// Requests slower than this are logged, with their path (#145).
71
const SLOW: std::time::Duration = std::time::Duration::from_secs(2);
72
73
/// Log a slow request's method, path and time, so a slow page can be
74
/// found afterwards. Never the query, which may hold a token.
75
async fn slow_requests(req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
76
    let (method, path) = (req.method().clone(), req.uri().path().to_string());
77
    let start = std::time::Instant::now();
78
    let res = next.run(req).await;
79
    let took = start.elapsed();
80
    if took >= SLOW {
81
        tracing::warn!("slow request: {method} {path} took {:.1} s ({})", took.as_secs_f64(), res.status().as_u16());
82
    }
83
    res
84
}
85
d23464c0 Andy McCall ↶ 86
/// Serve on the configured addresses until the process is told to stop.
87
pub async fn serve(app: Shared) -> anyhow::Result<()> {
88
    let router = router(app.clone());
89
    let http = app.config.bind_addr()?;
90
    let https = app.config.tls_bind_addr()?;
91
    if http.is_none() && https.is_none() {
92
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
93
    }
94
    let mut tasks = tokio::task::JoinSet::new();
95
    if let Some(addr) = http {
96
        let listener = tokio::net::TcpListener::bind(addr).await?;
97
        tracing::info!("http on {addr}");
98
        let r = router.clone();
99
        tasks.spawn(async move { axum::serve(listener, r).await.map_err(anyhow::Error::from) });
100
    }
101
    if let Some(addr) = https {
102
        let _ = rustls::crypto::ring::default_provider().install_default();
103
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
104
            .await
105
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
106
        tracing::info!("https on {addr}");
107
        let r = router.clone();
108
        tasks.spawn(async move { axum_server::bind_rustls(addr, tls).serve(r.into_make_service()).await.map_err(anyhow::Error::from) });
109
    }
110
    tokio::select! {
111
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
112
        _ = tokio::signal::ctrl_c() => { tracing::info!("stopping"); Ok(()) }
113
    }
114
}