For a public demo: no login on any address, everyone is "Demo visitor" (actor demo), a note at the top of every page, the back office's and the client's (#demo-note), and the invented demo data added at start when the database is empty (the server drops it every night). Every file upload is refused with a message (documents, the office photo, the client's uploads; a contract version keeps its text without the file), a mail server in its settings is refused, so nothing leaves it, and it needs a place for the files and their key (the demo's own files and the signed copies). seed-demo also runs in it. Sign out leads home. Checked: config test (address, files, no mail), tests/demo.rs (the note, an upload refused and nothing kept, a version with text only, the journal's actor), a local run on an empty database (seeds itself: 27 documents, the clients and contracts) and screenshots light and dark, desk and phone (PROBLEMS: 0).
269 lines
9.2 KiB
Rust
269 lines
9.2 KiB
Rust
//! `visa [serve|migrate|seed-demo|files-check|files-migrate|files-mirror|version|help]`:
|
|
//! the server and its admin commands.
|
|
|
|
use std::path::PathBuf;
|
|
use std::process::ExitCode;
|
|
|
|
use anyhow::{Context, Result, bail, ensure};
|
|
use tracing::{info, warn};
|
|
|
|
use visa::config::Config;
|
|
use visa::files::{self, Store};
|
|
use visa::{dates, db, documents, seed, web};
|
|
|
|
const USAGE: &str = "\
|
|
visa: immigration records, deadlines and extension packs (Lanna Desk, lannadesk.com)
|
|
|
|
Usage: visa [COMMAND]
|
|
|
|
Commands:
|
|
serve run the web server (default); applies pending migrations first
|
|
migrate apply pending database migrations and exit
|
|
seed-demo add invented demo people and documents (local development and the
|
|
demo; the demo also does it itself at start)
|
|
files-check read every document's file back and compare it with its upload;
|
|
list files without a document (exit status 1 on any problem)
|
|
files-migrate --from DIR
|
|
copy the documents' files from a files directory (the store
|
|
before the bucket, or a backup's mirror) into the store, each
|
|
checked against its upload; again is harmless
|
|
files-mirror --to DIR
|
|
make DIR hold exactly the store's files, still encrypted, for
|
|
the backups
|
|
version print the version and the commit it is built from (also --version)
|
|
help show this text
|
|
|
|
Settings come from the environment; see src/config.rs or README.md.";
|
|
|
|
#[tokio::main]
|
|
async fn main() -> ExitCode {
|
|
tracing_subscriber::fmt()
|
|
.with_max_level(tracing::Level::INFO)
|
|
.with_target(false)
|
|
.init();
|
|
let cmd = std::env::args().nth(1).unwrap_or_else(|| "serve".into());
|
|
match run(&cmd).await {
|
|
Ok(()) => ExitCode::SUCCESS,
|
|
Err(e) => {
|
|
eprintln!("visa: {e:#}");
|
|
ExitCode::FAILURE
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The directory after `flag` on the command line.
|
|
fn dir_arg(flag: &str) -> Result<PathBuf> {
|
|
let args: Vec<String> = std::env::args().skip(2).collect();
|
|
match args.as_slice() {
|
|
[f, dir] if f == flag && !dir.is_empty() => Ok(PathBuf::from(dir)),
|
|
_ => bail!("give the directory as {flag} DIR; `visa help` lists the commands"),
|
|
}
|
|
}
|
|
|
|
/// The store the settings name; an error when documents are off.
|
|
fn store(cfg: &Config) -> Result<Store> {
|
|
let f = cfg
|
|
.files
|
|
.as_ref()
|
|
.context("documents are off here: no VISA_S3_BUCKET (or VISA_FILES_DIR) and file key")?;
|
|
Store::open(f)
|
|
}
|
|
|
|
async fn run(cmd: &str) -> Result<()> {
|
|
match cmd {
|
|
"serve" => serve().await,
|
|
// CI checks it, and cnx01 runs it before it installs a release
|
|
"version" | "--version" => {
|
|
println!(
|
|
"visa {} ({})",
|
|
env!("CARGO_PKG_VERSION"),
|
|
visa::embedded::COMMIT
|
|
);
|
|
Ok(())
|
|
}
|
|
"migrate" => {
|
|
let cfg = Config::from_env()?;
|
|
let pool = db::connect(&cfg).await?;
|
|
db::migrate(&pool).await?;
|
|
println!("migrations applied");
|
|
Ok(())
|
|
}
|
|
"seed-demo" => {
|
|
let cfg = Config::from_env()?;
|
|
ensure!(
|
|
!cfg.login_enabled(),
|
|
"seed-demo writes invented people and runs only in local development or the \
|
|
demo (VISA_INSECURE_NO_LOGIN=1 or VISA_DEMO=1, no VISA_OIDC_ISSUER)"
|
|
);
|
|
let pool = db::connect(&cfg).await?;
|
|
db::migrate(&pool).await?;
|
|
for line in seed_demo(&cfg, &pool).await? {
|
|
println!("{line}");
|
|
}
|
|
Ok(())
|
|
}
|
|
"files-check" => {
|
|
let cfg = Config::from_env()?;
|
|
let store = store(&cfg)?;
|
|
let pool = db::connect(&cfg).await?;
|
|
let check = documents::check(&pool, &store).await?;
|
|
for p in &check.problems {
|
|
println!("problem: {p}");
|
|
}
|
|
println!(
|
|
"{} documents checked in {} (file key {}): {} problems",
|
|
check.documents,
|
|
store.describe(),
|
|
store.key_id(),
|
|
check.problems.len()
|
|
);
|
|
ensure!(check.problems.is_empty(), "the files need attention");
|
|
Ok(())
|
|
}
|
|
"files-migrate" => {
|
|
let from = dir_arg("--from")?;
|
|
let cfg = Config::from_env()?;
|
|
let store = store(&cfg)?;
|
|
let pool = db::connect(&cfg).await?;
|
|
let moved = documents::migrate(&pool, &from, &store).await?;
|
|
for name in &moved.strays {
|
|
println!(
|
|
"left in {}: {name}, which is no document's file",
|
|
from.display()
|
|
);
|
|
}
|
|
for id in &moved.missing {
|
|
println!(
|
|
"problem: document {id} has no file in {} and none in the store",
|
|
from.display()
|
|
);
|
|
}
|
|
println!(
|
|
"{} files copied into {}, {} there already (file key {})",
|
|
moved.copied,
|
|
store.describe(),
|
|
moved.there,
|
|
store.key_id()
|
|
);
|
|
Ok(())
|
|
}
|
|
"files-mirror" => {
|
|
let to = dir_arg("--to")?;
|
|
let cfg = Config::from_env()?;
|
|
let store = store(&cfg)?;
|
|
let m = files::mirror(&store, &to).await?;
|
|
println!(
|
|
"{} mirrored into {}: {} copied, {} kept, {} removed",
|
|
store.describe(),
|
|
to.display(),
|
|
m.copied,
|
|
m.kept,
|
|
m.removed
|
|
);
|
|
Ok(())
|
|
}
|
|
"help" | "--help" | "-h" => {
|
|
println!("{USAGE}");
|
|
Ok(())
|
|
}
|
|
other => bail!("unknown command {other:?}; `visa help` lists the commands"),
|
|
}
|
|
}
|
|
|
|
async fn serve() -> Result<()> {
|
|
let cfg = Config::from_env()?;
|
|
let pool = db::connect(&cfg).await?;
|
|
db::migrate(&pool).await?;
|
|
if cfg.demo() {
|
|
// an empty database (the server's nightly reset) gets the demo data
|
|
for line in seed_demo(&cfg, &pool).await? {
|
|
info!("demo: {line}");
|
|
}
|
|
}
|
|
let listen = cfg.listen;
|
|
let login = cfg.login_enabled();
|
|
let demo = cfg.demo();
|
|
let st = web::AppState::new(cfg, pool)?;
|
|
match &st.files {
|
|
Some(s) => {
|
|
info!("documents in {} (file key {})", s.describe(), s.key_id());
|
|
// A store that is not there yet (Garage starting) costs the
|
|
// documents, not the records: the check only warns, and the
|
|
// server listens meanwhile.
|
|
let s = s.clone();
|
|
tokio::spawn(async move {
|
|
match s.check().await {
|
|
Ok(()) => info!("documents: {} answers", s.describe()),
|
|
Err(e) => warn!("documents: {} does not answer yet: {e:#}", s.describe()),
|
|
}
|
|
});
|
|
}
|
|
None => info!("documents are off: no place for them (local development)"),
|
|
}
|
|
web::spawn_background(st.clone());
|
|
// the journal's daily anchor by mail (phase 11)
|
|
visa::anchor::spawn(st.cfg.clone(), st.db.clone());
|
|
let app = web::router(st);
|
|
let listener = tokio::net::TcpListener::bind(listen)
|
|
.await
|
|
.with_context(|| format!("cannot listen on {listen}"))?;
|
|
if demo {
|
|
info!("the public demo: no login, invented data, no uploads, no mail (VISA_DEMO)");
|
|
} else if !login {
|
|
info!("no login: VISA_INSECURE_NO_LOGIN is set (loopback only)");
|
|
}
|
|
info!("listening on http://{listen}");
|
|
axum::serve(listener, app)
|
|
.with_graceful_shutdown(shutdown())
|
|
.await
|
|
.context("serving")?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Adds the invented demo data where it is missing: people, their
|
|
/// documents, clients and contracts. What it did, a line each.
|
|
async fn seed_demo(cfg: &Config, pool: &sqlx::PgPool) -> Result<Vec<String>> {
|
|
let mut out = Vec::new();
|
|
out.push(if seed::demo(pool, dates::today()).await? {
|
|
"demo people added".to_string()
|
|
} else {
|
|
"demo people are there already".to_string()
|
|
});
|
|
let store = cfg.files.as_ref().map(|_| store(cfg)).transpose()?;
|
|
match &store {
|
|
Some(s) => {
|
|
let n = seed::demo_documents(pool, s, dates::today()).await?;
|
|
out.push(format!("demo documents added: {n}"));
|
|
}
|
|
None => out.push("no demo documents: documents are off (no place for them)".into()),
|
|
}
|
|
out.push(
|
|
if seed::legal::demo(pool, store.as_ref(), dates::today()).await? {
|
|
"demo clients and contracts added".to_string()
|
|
} else {
|
|
"demo clients and contracts are there already".to_string()
|
|
},
|
|
);
|
|
Ok(out)
|
|
}
|
|
|
|
async fn shutdown() {
|
|
let ctrl_c = async {
|
|
let _ = tokio::signal::ctrl_c().await;
|
|
};
|
|
#[cfg(unix)]
|
|
let term = async {
|
|
if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
|
{
|
|
s.recv().await;
|
|
}
|
|
};
|
|
#[cfg(not(unix))]
|
|
let term = std::future::pending::<()>();
|
|
tokio::select! {
|
|
_ = ctrl_c => {},
|
|
_ = term => {},
|
|
}
|
|
info!("shutting down");
|
|
}
|