Files
visa/src/anchor.rs
T
grabowski 62a37b677a
CI / secret scan (push) Successful in 6s
CI / fmt, clippy, tests (push) Successful in 1m18s
CI / release (push) Skipped
Anchor: each run ends its transaction itself
A run that was not due dropped its transaction, and sqlx rolls a dropped
one back only when the connection is returned, from a background task.
Until then the advisory lock stays taken, so a run right after it (the
test's next call on a busy CI runner; on the server a tick that comes at
the wrong moment) found the lock taken and skipped. Every way out of
run_daily now rolls back explicitly (sending happens on the pool; the
transaction only holds the lock). The test checks from a connection of
its own that no lock is left after a run that sent nothing.
2026-11-23 00:31:51 +07:00

463 lines
13 KiB
Rust

//! The journal's anchor (phase 11): once a day the app mails the number and
//! hash of the journal's last entry to addresses outside the server. Each
//! entry carries the hash of the one before it, so that one hash pins the
//! whole journal up to then; the mails kept by the recipients are out of
//! reach of anyone who could change the database and rebuild the chain.
//! `/journal/anchor?seq=…&hash=…` compares a mailed anchor with the journal
//! as it is now.
use anyhow::Result;
use chrono::{DateTime, NaiveDate, Timelike, Utc};
use serde::Serialize;
use sqlx::PgPool;
use tracing::{info, warn};
use crate::config::Config;
use crate::dates;
use crate::journal::{self, New};
use crate::mail::{self, Outgoing};
/// The hour in Chiang Mai from which the day's anchor goes out.
pub const HOUR: u32 = 7;
const RECIPIENTS: &str = "anchor_to";
/// The addresses the anchor goes to, as saved.
pub async fn recipients(db: &PgPool) -> Result<Vec<String>> {
let v: Option<String> = sqlx::query_scalar("SELECT value FROM settings WHERE key = $1")
.bind(RECIPIENTS)
.fetch_optional(db)
.await?;
Ok(split(&v.unwrap_or_default()))
}
/// Addresses from a line: separated by commas, spaces or new lines.
pub fn split(s: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for a in s.split([',', ';', ' ', '\n', '\r', '\t']) {
let a = a.trim().to_string();
if !a.is_empty() && !out.iter().any(|o| o.eq_ignore_ascii_case(&a)) {
out.push(a);
}
}
out
}
/// Saves the recipients; the change goes into the journal, so where the
/// anchors went is itself on record. False when nothing changed.
pub async fn set_recipients(db: &PgPool, to: &[String], by: &str) -> Result<bool> {
let before = recipients(db).await?;
if before == to {
return Ok(false);
}
let shown = |v: &[String]| {
if v.is_empty() {
"nobody".to_string()
} else {
v.join(", ")
}
};
let mut tx = db.begin().await?;
sqlx::query(
"INSERT INTO settings (key, value, updated_by) VALUES ($1, $2, $3) \
ON CONFLICT (key) DO UPDATE SET value = $2, updated_by = $3, updated_at = now()",
)
.bind(RECIPIENTS)
.bind(to.join(", "))
.bind(by)
.execute(&mut *tx)
.await?;
journal::append(
&mut tx,
&New {
actor: by,
client: None,
contract: None,
event: "anchor recipients changed",
detail: format!(
"The journal's daily anchor goes to {} (before: {}).",
shown(to),
shown(&before)
),
},
)
.await?;
tx.commit().await?;
Ok(true)
}
/// One anchor as recorded.
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
pub struct Anchor {
pub id: i64,
pub day: NaiveDate,
pub seq: i64,
pub hash: String,
pub whole: bool,
pub status: String,
pub recipients: String,
pub how: String,
pub actor: String,
pub at: DateTime<Utc>,
}
pub async fn recent(db: &PgPool, limit: i64) -> Result<Vec<Anchor>> {
Ok(
sqlx::query_as("SELECT * FROM journal_anchors ORDER BY id DESC LIMIT $1")
.bind(limit)
.fetch_all(db)
.await?,
)
}
/// Whether the day's anchor is due at `now`: from the hour on, once a day
/// sent (or found unchanged), and an hour after a failed try.
pub fn due(now: DateTime<Utc>, recent: &[Anchor]) -> bool {
let local = now.with_timezone(&dates::bangkok());
if local.hour() < HOUR {
return false;
}
let today = local.date_naive();
let done = recent
.iter()
.any(|a| a.day == today && a.status != "failed");
let tried_lately = recent
.iter()
.any(|a| a.day == today && (now - a.at).num_minutes() < 60);
!done && !tried_lately
}
/// What sending an anchor did.
#[derive(Debug)]
pub enum Outcome {
/// Mail is off, nobody to send to, or the journal is empty.
Nothing(&'static str),
/// Nothing was added since the last anchor that went out.
Unchanged,
Sent {
seq: i64,
failed: usize,
to: usize,
},
}
#[derive(sqlx::FromRow)]
struct Last {
seq: i64,
hash: String,
at: DateTime<Utc>,
}
/// The anchor's mail.
pub fn text(
public_url: &str,
seq: i64,
hash: &str,
written: DateTime<Utc>,
check: &journal::Check,
now: DateTime<Utc>,
) -> String {
let state = if check.whole() {
"The chain checked whole when this mail was sent: every entry names the hash of \
the one before it, and every contract version matches its entry."
.to_string()
} else {
format!(
"WARNING: THE CHAIN DID NOT CHECK WHOLE when this mail was sent. Tell the team's \
lead at once. What the check found:\n{}",
check
.problems
.iter()
.map(|p| format!("- {p}"))
.collect::<Vec<_>>()
.join("\n")
)
};
format!(
"The journal of Lanna Desk's back office ({public_url}) on {now}, Chiang Mai time:\n\n\
Last entry: number {seq}, written {written}\n\
Its hash: {hash}\n\n\
{state}\n\n\
Keep this mail. Each entry carries the hash of the one before it, so this hash pins \
the whole journal up to entry {seq}. If the journal is ever changed and rebuilt, \
entry {seq} will no longer have this hash. To compare it with the journal as it is \
then, open:\n\
{public_url}/journal/anchor?seq={seq}&hash={hash}\n\n\
Lanna Desk\n",
now = dates::fmt_datetime(now),
written = dates::fmt_datetime(written),
)
}
/// Sends the anchor now to every recipient, records it and logs each mail.
/// `daily` says whether the day's run sent it; by hand it always goes out.
pub async fn send(
cfg: &Config,
db: &PgPool,
daily: bool,
actor: &str,
now: DateTime<Utc>,
) -> Result<Outcome> {
let Some(mail_cfg) = cfg.mail.as_ref() else {
return Ok(Outcome::Nothing("mail is not set up on this server"));
};
let to = recipients(db).await?;
if to.is_empty() {
return Ok(Outcome::Nothing("nobody to send the anchor to"));
}
let last: Option<Last> =
sqlx::query_as("SELECT seq, hash, at FROM journal ORDER BY seq DESC LIMIT 1")
.fetch_optional(db)
.await?;
let Some(last) = last else {
return Ok(Outcome::Nothing("the journal is empty"));
};
let day = now.with_timezone(&dates::bangkok()).date_naive();
let check = journal::verify(db).await?;
if daily && check.whole() {
let sent_last: Option<i64> = sqlx::query_scalar(
"SELECT seq FROM journal_anchors WHERE status = 'sent' ORDER BY id DESC LIMIT 1",
)
.fetch_optional(db)
.await?;
if sent_last == Some(last.seq) {
record(db, day, &last, true, "unchanged", "", daily, actor).await?;
return Ok(Outcome::Unchanged);
}
}
let subject = format!(
"Lanna Desk journal, entry {}: {}",
last.seq,
&last.hash[..12]
);
let body = text(&cfg.public_url, last.seq, &last.hash, last.at, &check, now);
let hello = mail::hello_name(&cfg.public_url);
let mut failed = 0;
for addr in &to {
let result = mail::send(
mail_cfg,
&hello,
&Outgoing {
to: addr,
subject: &subject,
text: &body,
},
)
.await;
if let Err(e) = &result {
warn!("journal anchor to {addr} failed: {e:#}");
failed += 1;
}
mail::log(
db,
&mail::Entry {
channel: "email",
purpose: "anchor",
recipient: addr,
subject: &subject,
result: &result,
actor,
},
)
.await?;
}
let status = if failed == 0 { "sent" } else { "failed" };
record(
db,
day,
&last,
check.whole(),
status,
&to.join(", "),
daily,
actor,
)
.await?;
info!(
"journal anchor, entry {}: {status} ({} of {})",
last.seq,
to.len() - failed,
to.len()
);
Ok(Outcome::Sent {
seq: last.seq,
failed,
to: to.len(),
})
}
#[allow(clippy::too_many_arguments)]
async fn record(
db: &PgPool,
day: NaiveDate,
last: &Last,
whole: bool,
status: &str,
to: &str,
daily: bool,
actor: &str,
) -> Result<()> {
sqlx::query(
"INSERT INTO journal_anchors (day, seq, hash, whole, status, recipients, how, actor) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
)
.bind(day)
.bind(last.seq)
.bind(&last.hash)
.bind(whole)
.bind(status)
.bind(to)
.bind(if daily { "daily" } else { "by hand" })
.bind(actor)
.execute(db)
.await?;
Ok(())
}
/// The day's run: sends when due, else does nothing.
pub async fn run_daily(cfg: &Config, db: &PgPool, now: DateTime<Utc>) -> Result<Option<Outcome>> {
if cfg.mail.is_none() {
return Ok(None);
}
// one server sends: the lock keeps two runs from both sending. Every
// way out ends the transaction itself: a dropped one is only rolled
// back when its connection is used again, and until then it keeps the
// lock, so the next run would find it taken and skip the day.
let mut tx = db.begin().await?;
let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(7464530001)")
.fetch_one(&mut *tx)
.await?;
if !locked {
tx.rollback().await?;
return Ok(None);
}
let today = now.with_timezone(&dates::bangkok()).date_naive();
let rows: Vec<Anchor> =
sqlx::query_as("SELECT * FROM journal_anchors WHERE day = $1 ORDER BY id DESC")
.bind(today)
.fetch_all(db)
.await?;
if !due(now, &rows) {
tx.rollback().await?;
return Ok(None);
}
let out = send(cfg, db, true, "daily anchor", now).await;
tx.rollback().await?;
Ok(Some(out?))
}
/// Checks every ten minutes whether the day's anchor is due.
pub fn spawn(cfg: Config, db: PgPool) {
if cfg.mail.is_none() {
info!("journal anchor: off, mail is not set up");
return;
}
tokio::spawn(async move {
let mut tick = tokio::time::interval(std::time::Duration::from_secs(600));
loop {
tick.tick().await;
if let Err(e) = run_daily(&cfg, &db, Utc::now()).await {
warn!("journal anchor: {e:#}");
}
}
});
}
/// What the journal says about an anchor someone kept.
#[derive(Debug, Serialize)]
pub struct Compared {
pub seq: i64,
pub hash: String,
/// The entry's hash now; None when there is no such entry.
pub now: Option<String>,
pub same: bool,
pub at: Option<String>,
}
pub async fn compare(db: &PgPool, seq: i64, hash: &str) -> Result<Compared> {
let row: Option<(String, DateTime<Utc>)> =
sqlx::query_as("SELECT hash, at FROM journal WHERE seq = $1")
.bind(seq)
.fetch_optional(db)
.await?;
let hash = hash.trim().to_lowercase();
Ok(Compared {
seq,
same: row.as_ref().is_some_and(|(h, _)| *h == hash),
at: row.as_ref().map(|(_, at)| dates::fmt_datetime(*at)),
now: row.map(|(h, _)| h),
hash,
})
}
/// A hash as an anchor carries it: 64 hex digits.
pub fn is_hash(s: &str) -> bool {
let s = s.trim();
s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit())
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
fn at(h: u32, m: u32) -> DateTime<Utc> {
// Nov 22, 2026 in Chiang Mai
dates::bangkok()
.with_ymd_and_hms(2026, 11, 22, h, m, 0)
.unwrap()
.with_timezone(&Utc)
}
fn row(status: &str, when: DateTime<Utc>) -> Anchor {
Anchor {
id: 1,
day: when.with_timezone(&dates::bangkok()).date_naive(),
seq: 5,
hash: "a".repeat(64),
whole: true,
status: status.into(),
recipients: String::new(),
how: "daily".into(),
actor: "daily anchor".into(),
at: when,
}
}
#[test]
fn the_anchor_goes_once_a_day_from_seven() {
assert!(!due(at(6, 59), &[]), "not before seven");
assert!(due(at(7, 0), &[]));
assert!(!due(at(9, 0), &[row("sent", at(7, 5))]), "once a day");
assert!(!due(at(9, 0), &[row("unchanged", at(7, 5))]));
assert!(
!due(at(7, 40), &[row("failed", at(7, 5))]),
"an hour after a failure"
);
assert!(due(at(8, 10), &[row("failed", at(7, 5))]));
assert!(
due(
at(7, 10),
&[row("sent", at(7, 5) - chrono::Duration::days(1))]
),
"a new day"
);
}
#[test]
fn recipients_are_split_and_kept_once() {
assert_eq!(
split("a@x.example, b@y.example;\nA@X.example c@z.example"),
["a@x.example", "b@y.example", "c@z.example"]
);
assert!(split(" , ").is_empty());
}
#[test]
fn hashes_have_64_hex_digits() {
assert!(is_hash(&"0f".repeat(32)));
assert!(!is_hash("abc"));
assert!(!is_hash(&"zz".repeat(32)));
}
}