Phase 11, step 2: the journal's daily anchor by mail
CI / secret scan (push) Successful in 7s
CI / fmt, clippy, tests (push) Successful in 50s
CI / release (push) Canceled after 34s

Every day from 07:00 Chiang Mai time the app mails the journal's last
entry number and its hash to the addresses set on the Notifications page
(src/anchor.rs, migration 0012: settings, journal_anchors), when anything
was added since the last anchor that went out. A day without news is
noted without a mail; a failed send is tried again after an hour; a
transaction-level advisory lock keeps two runs from both sending. "Send
the anchor now" sends at once. Each mail says whether the chain checked
whole (in capitals when it did not) and links to /journal/anchor, which
compares a kept entry number and hash with the journal now: the same
hash, another one, or no such entry. Changing the recipients is itself a
journal entry. Every anchor mail is in the notifications log.

Tests: the daily rule (before seven, once a day, an hour after a
failure), recipients checked and journaled, one mail per recipient with
the head hash, unchanged days, by hand, the check page's three answers,
and a chain broken around the app said in the mail. 126 unit, 67
integration.
This commit is contained in:
grabowski committed 2026-11-22 23:02:20 +07:00
1 parent 94ad25b6fc
commit 72a4faf71a
14 files changed
+990 -22

No files matched your search

+48
View File
@@ -1524,6 +1524,54 @@ pub async fn paper_label(
// ------------------------------------------------------------- journal
#[derive(Debug, Deserialize)]
pub struct AnchorQuery {
#[serde(default)]
seq: String,
#[serde(default)]
hash: String,
}
/// Compares an anchor someone kept (a mail of the daily anchor, a note)
/// with the journal as it is now.
pub async fn anchor_check(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Query(q): Query<AnchorQuery>,
) -> Res {
let asked = !q.seq.trim().is_empty() || !q.hash.trim().is_empty();
let mut error = String::new();
let mut result = None;
if asked {
match q.seq.trim().parse::<i64>() {
Ok(seq) if seq > 0 && crate::anchor::is_hash(&q.hash) => {
result = Some(crate::anchor::compare(&st.db, seq, &q.hash).await?);
}
_ => {
error = "Enter the entry's number and its hash of 64 characters, as the anchor mail gives them.".into();
}
}
}
let check = journal::verify(&st.db).await?;
let status = if error.is_empty() {
StatusCode::OK
} else {
StatusCode::UNPROCESSABLE_ENTITY
};
Ok(page(
&st,
&user,
"anchor_check.html",
"Check an anchor",
"journal",
status,
context! {
seq => q.seq.trim(), hash => q.hash.trim(), error, result,
whole => check.whole(), count => check.entries,
},
))
}
#[derive(Debug, Deserialize)]
pub struct JournalQuery {
#[serde(default)]
+4 -1
View File
@@ -443,11 +443,14 @@ pub fn router(st: Arc<AppState>) -> Router {
.route("/papers/{pid}/move", post(l::move_paper))
.route("/papers/{pid}/label", get(l::paper_label))
.route("/journal", get(l::journal_page))
.route("/journal.csv", get(l::journal_csv));
.route("/journal.csv", get(l::journal_csv))
.route("/journal/anchor", get(l::anchor_check));
}
r.route("/activity", get(activity::page))
.route("/notifications", get(notifications::notifications))
.route("/notifications/test-email", post(notifications::test_email))
.route("/notifications/anchor-to", post(notifications::anchor_to))
.route("/notifications/anchor-now", post(notifications::anchor_now))
.route("/login", get(auth::login))
.route("/auth/callback", get(auth::callback))
.route("/logout", post(auth::logout))
+131 -15
View File
@@ -11,6 +11,7 @@ use minijinja::context;
use serde::{Deserialize, Serialize};
use super::{AppState, Res, page};
use crate::anchor;
use crate::config::MailSecurity;
use crate::dates;
use crate::forms::Fields;
@@ -22,6 +23,29 @@ pub struct NotificationsQuery {
/// The log line of a test just sent, to show how it went.
#[serde(default)]
sent: Option<i64>,
/// What "Send the anchor now" did.
#[serde(default)]
anchor: Option<String>,
}
#[derive(Debug, Serialize)]
struct AnchorLine {
day: String,
seq: i64,
hash: String,
whole: bool,
status: String,
recipients: String,
how: String,
at: String,
}
/// What the anchor form shows again after a post.
#[derive(Debug, Default)]
struct AnchorForm {
to: Option<String>,
error: String,
done: String,
}
#[derive(Debug, Serialize)]
@@ -60,7 +84,14 @@ struct MailShown {
reply_to: Option<String>,
}
async fn show(st: &AppState, user: &User, sent: Option<i64>, address: &str, error: &str) -> Res {
async fn show(
st: &AppState,
user: &User,
sent: Option<i64>,
address: &str,
error: &str,
af: AnchorForm,
) -> Res {
let mail = st.cfg.mail.as_ref().map(|m| MailShown {
from: m.from.clone(),
server: format!("{}:{}", m.host, m.port),
@@ -87,11 +118,29 @@ async fn show(st: &AppState, user: &User, sent: Option<i64>, address: &str, erro
.into_iter()
.map(line)
.collect();
let status = if error.is_empty() {
let status = if error.is_empty() && af.error.is_empty() {
StatusCode::OK
} else {
StatusCode::UNPROCESSABLE_ENTITY
};
let anchor_to = match af.to {
Some(t) => t,
None => anchor::recipients(&st.db).await?.join(", "),
};
let anchors: Vec<AnchorLine> = anchor::recent(&st.db, 7)
.await?
.into_iter()
.map(|a| AnchorLine {
day: dates::fmt_date(a.day),
at: dates::fmt_datetime(a.at),
seq: a.seq,
hash: a.hash,
whole: a.whole,
status: a.status,
recipients: a.recipients,
how: a.how,
})
.collect();
Ok(page(
st,
user,
@@ -99,7 +148,12 @@ async fn show(st: &AppState, user: &User, sent: Option<i64>, address: &str, erro
"Notifications",
"notifications",
status,
context! { mail, result, address, error, log },
context! {
mail, result, address, error, log, anchor_to, anchors,
anchor_error => af.error,
anchor_done => af.done,
anchor_hour => anchor::HOUR,
},
))
}
@@ -108,7 +162,69 @@ pub async fn notifications(
Extension(user): Extension<User>,
Query(q): Query<NotificationsQuery>,
) -> Res {
show(&st, &user, q.sent, "", "").await
let done = match q.anchor.as_deref() {
Some("sent") => "The anchor went out. The recipients' copies are in the log below.",
Some("failed") => "The anchor did not reach every recipient: see the log below.",
Some("nothing") => "Nothing was sent: the journal is still empty.",
Some("saved") => "Saved. The change is in the journal.",
_ => "",
};
let af = AnchorForm {
done: done.to_string(),
..AnchorForm::default()
};
show(&st, &user, q.sent, "", "", af).await
}
/// Saves where the daily anchor goes.
pub async fn anchor_to(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Form(f): Form<Fields>,
) -> Res {
let raw = crate::forms::get(&f, "anchor_to");
let to = anchor::split(&raw);
let bad: Vec<&String> = to.iter().filter(|a| !mail::valid_address(a)).collect();
if !bad.is_empty() || to.len() > 10 {
let error = if to.len() > 10 {
"Ten addresses at most.".to_string()
} else {
format!(
"Not an email address: {}.",
bad.iter()
.map(|s| s.as_str())
.collect::<Vec<_>>()
.join(", ")
)
};
let af = AnchorForm {
to: Some(raw.trim().to_string()),
error,
..AnchorForm::default()
};
return show(&st, &user, None, "", "", af).await;
}
anchor::set_recipients(&st.db, &to, &user.login).await?;
Ok(Redirect::to("/notifications?anchor=saved#anchor").into_response())
}
/// Sends the anchor at once, whatever the day's run did.
pub async fn anchor_now(State(st): State<Arc<AppState>>, Extension(user): Extension<User>) -> Res {
let out = anchor::send(&st.cfg, &st.db, false, &user.login, chrono::Utc::now()).await?;
let said = match out {
anchor::Outcome::Sent { failed: 0, .. } => "sent",
anchor::Outcome::Sent { .. } => "failed",
anchor::Outcome::Unchanged => "sent",
anchor::Outcome::Nothing("the journal is empty") => "nothing",
anchor::Outcome::Nothing(why) => {
let af = AnchorForm {
error: format!("Nothing was sent: {why}."),
..AnchorForm::default()
};
return show(&st, &user, None, "", "", af).await;
}
};
Ok(Redirect::to(&format!("/notifications?anchor={said}#anchor")).into_response())
}
/// Sends a test mail to the address given, logs how it went and shows it.
@@ -119,7 +235,15 @@ pub async fn test_email(
) -> Res {
let to = crate::forms::get(&f, "to").trim().to_string();
let Some(cfg) = st.cfg.mail.as_ref() else {
return show(&st, &user, None, &to, "Mail is not set up on this server.").await;
return show(
&st,
&user,
None,
&to,
"Mail is not set up on this server.",
AnchorForm::default(),
)
.await;
};
if !mail::valid_address(&to) {
return show(
@@ -128,6 +252,7 @@ pub async fn test_email(
None,
&to,
"Enter one email address, such as alex@buildfor.life.",
AnchorForm::default(),
)
.await;
}
@@ -141,16 +266,7 @@ pub async fn test_email(
who = user.login,
at = dates::fmt_datetime(chrono::Utc::now()),
);
let hello = st
.cfg
.public_url
.split("://")
.nth(1)
.unwrap_or("localhost")
.split(['/', ':'])
.next()
.unwrap_or("localhost")
.to_string();
let hello = mail::hello_name(&st.cfg.public_url);
let result = mail::send(
cfg,
&hello,