summaryrefslogtreecommitdiffstats
path: root/src/usecase/bootstrap.rs
blob: 6793076e348f44aeb3e4e82e7045f123a9468137 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//! Bringing a repository up, which every command does and every front end
//! used to write out for itself.

use std::sync::atomic::AtomicBool;
use std::sync::Arc;

use crate::config::Config;
use crate::db::{self, Db};
use crate::error::Result;
use crate::pipeline;

/// Directories exist, the schema is current, and the repo row is present.
///
/// Four calls in an order that matters — migrate before open, `ensure_repo`
/// before anything reads `repo_id` — which is precisely the kind of sequence
/// that quietly rots when it is copied.
pub fn open(cfg: &Config) -> Result<Db> {
    open_and_ensure(cfg).map(|(db, _)| db)
}

/// `open`, plus the id of the row named by `cfg.repo_name` — which is what
/// `init` prints, and is not necessarily the lowest repo id if a root ever
/// holds more than one repo.
fn open_and_ensure(cfg: &Config) -> Result<(Db, i64)> {
    cfg.ensure_dirs()?;
    db::migrate(&cfg.db_path())?;
    let db = Db::open_migrated(&cfg.db_path())?;
    let rid = db::ensure_repo(
        &db.writer,
        &cfg.repo_name,
        &cfg.repo_arch_dir().display().to_string(),
        &cfg.arch,
        &cfg.signing_key_id,
    )?;
    Ok((db, rid))
}

/// A first run: persist the config, bring the repository up, and hand back the
/// repo id so the operator can paste it into `pacman.conf`.
pub fn init(cfg: &Config) -> Result<i64> {
    cfg.save()?;
    open_and_ensure(cfg).map(|(_, rid)| rid)
}

/// Everything `serve` does before control passes to the UI: bring the
/// repository up, finish anything a previous run left half-published, and start
/// the two background loops.
///
/// The HTTP server is deliberately not started here. This module sits below the
/// UI and must not be able to name it.
pub fn serve(cfg: &Config) -> Result<Db> {
    let db = open(cfg)?;
    let _ = pipeline::publish::reconcile(cfg, &db);
    let stop = Arc::new(AtomicBool::new(false));
    crate::watch::scheduler::spawn_scheduler(Arc::new(cfg.clone()), db.clone(), stop.clone());
    let _pool = pipeline::dispatch::Pool::spawn(Arc::new(cfg.clone()), db.clone());
    Ok(db)
}