diff --git a/crates/forge-core/migrations/0038_display_name.sql b/crates/forge-core/migrations/0038_display_name.sql new file mode 100644 index 0000000..d3db521 --- /dev/null +++ b/crates/forge-core/migrations/0038_display_name.sql @@ -0,0 +1,4 @@ +-- Optional display name shown as the big heading on the profile page. NULL when the user has +-- not set one; the username is shown instead. Free text, validated by store/mod.rs. + +ALTER TABLE users ADD COLUMN display_name TEXT NULL; diff --git a/crates/forge-core/migrations/0039_totp_device.sql b/crates/forge-core/migrations/0039_totp_device.sql new file mode 100644 index 0000000..f0d2324 --- /dev/null +++ b/crates/forge-core/migrations/0039_totp_device.sql @@ -0,0 +1,9 @@ +-- The authenticator device behind two-factor sign-in: when it was turned on, when a code last +-- passed, and the name the user gave it (NULL means the default "Authenticator app"). Also +-- when the password last changed, for the "Last changed" line on the security page. Stamps are +-- RFC 3339 UTC, the same format as created_at elsewhere. Existing rows stay NULL. + +ALTER TABLE users ADD COLUMN totp_created_at TEXT NULL; +ALTER TABLE users ADD COLUMN totp_last_used_at TEXT NULL; +ALTER TABLE users ADD COLUMN totp_name TEXT NULL; +ALTER TABLE users ADD COLUMN password_changed_at TEXT NULL; diff --git a/crates/forge-core/migrations/0040_mail_queue.sql b/crates/forge-core/migrations/0040_mail_queue.sql new file mode 100644 index 0000000..3b4846c --- /dev/null +++ b/crates/forge-core/migrations/0040_mail_queue.sql @@ -0,0 +1,15 @@ +-- Mail queue visibility (M4). `kind` says what the message is for, `user_id` ties it to the +-- account it was sent about (NULL for mail with no account, such as an invite), and +-- `discarded_at` marks a failed message an admin gave up on by hand. Existing rows get their kind +-- from the idempotency key prefix the old call sites used. +ALTER TABLE mail_outbox ADD COLUMN kind TEXT NOT NULL DEFAULT 'other'; +ALTER TABLE mail_outbox ADD COLUMN user_id TEXT; +ALTER TABLE mail_outbox ADD COLUMN discarded_at TEXT; +UPDATE mail_outbox SET kind = CASE + WHEN idem_key LIKE 'reset:%' THEN 'password_reset' + WHEN idem_key LIKE 'verify:%' THEN 'verification' + WHEN idem_key LIKE 'invite:%' THEN 'invite' + WHEN idem_key LIKE 'notif:%' THEN 'notification' + WHEN idem_key LIKE 'test:%' THEN 'test' + ELSE 'other' END; +CREATE INDEX mail_outbox_user_kind ON mail_outbox (user_id, kind, created_at); diff --git a/crates/forge-core/migrations/0041_accent.sql b/crates/forge-core/migrations/0041_accent.sql new file mode 100644 index 0000000..41b6315 --- /dev/null +++ b/crates/forge-core/migrations/0041_accent.sql @@ -0,0 +1,4 @@ +-- Accent colour per user: the id of a palette in forge-web's accent_palette.rs. The web layer +-- decides which ids exist, so there is no CHECK list here. Applied by store/migrate.rs. + +ALTER TABLE users ADD COLUMN accent TEXT NOT NULL DEFAULT 'sage'; diff --git a/crates/forge-core/src/authz.rs b/crates/forge-core/src/authz.rs index f64e62f..b164377 100644 --- a/crates/forge-core/src/authz.rs +++ b/crates/forge-core/src/authz.rs @@ -123,10 +123,12 @@ mod tests { is_admin, created_at: String::new(), about: String::new(), + display_name: None, timezone: "UTC".into(), avatar_hash: None, theme: "auto".into(), language: "auto".into(), + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), kind: AccountKind::User, email_notifications: true, } diff --git a/crates/forge-core/src/mail.rs b/crates/forge-core/src/mail.rs index 906f6c5..f8983d8 100644 --- a/crates/forge-core/src/mail.rs +++ b/crates/forge-core/src/mail.rs @@ -116,6 +116,85 @@ impl fmt::Debug for MailPassword { } } +/// What a message is for. The queue page shows it, and the account page reads the latest one. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MailKind { + Verification, + PasswordReset, + Invite, + Notification, + Test, + Other, +} + +impl MailKind { + pub const ALL: [MailKind; 6] = [ + MailKind::Verification, + MailKind::PasswordReset, + MailKind::Invite, + MailKind::Notification, + MailKind::Test, + MailKind::Other, + ]; + + pub fn as_str(self) -> &'static str { + match self { + MailKind::Verification => "verification", + MailKind::PasswordReset => "password_reset", + MailKind::Invite => "invite", + MailKind::Notification => "notification", + MailKind::Test => "test", + MailKind::Other => "other", + } + } + + pub fn parse(s: &str) -> Option { + MailKind::ALL.into_iter().find(|kind| kind.as_str() == s) + } +} + +/// Where a queued message stands at one moment. Derived from the outbox row, never stored. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MailState { + /// Waiting for its first try. + Queued, + /// A try failed; the next one is scheduled. + Retrying, + /// Leased by a worker pass and being sent now. + Sending, + Sent, + /// The last try failed (or the error was permanent). Nothing more is scheduled. + Failed, + /// A failed message an admin gave up on by hand. + Discarded, +} + +impl MailState { + pub const ALL: [MailState; 6] = [ + MailState::Queued, + MailState::Retrying, + MailState::Sending, + MailState::Sent, + MailState::Failed, + MailState::Discarded, + ]; + + pub fn as_str(self) -> &'static str { + match self { + MailState::Queued => "queued", + MailState::Retrying => "retrying", + MailState::Sending => "sending", + MailState::Sent => "sent", + MailState::Failed => "failed", + MailState::Discarded => "discarded", + } + } + + pub fn parse(s: &str) -> Option { + MailState::ALL.into_iter().find(|state| state.as_str() == s) + } +} + /// One message to send. Its Debug output omits the body, which can carry one-time links. #[derive(Clone, PartialEq, Eq)] pub struct OutgoingMail { @@ -126,6 +205,9 @@ pub struct OutgoingMail { pub message_id: Option, /// `In-Reply-To` and `References` headers, in `<...>` form. pub in_reply_to: Option, + pub kind: MailKind, + /// The account the message is about. `None` for mail with no account yet. + pub user_id: Option, } impl fmt::Debug for OutgoingMail { @@ -133,6 +215,7 @@ impl fmt::Debug for OutgoingMail { f.debug_struct("OutgoingMail") .field("to", &self.to) .field("subject", &self.subject) + .field("kind", &self.kind) .field("body", &"") .finish() } @@ -148,11 +231,16 @@ pub struct OutboxEntry { pub body: String, pub message_id: Option, pub in_reply_to: Option, + pub kind: MailKind, + pub user_id: Option, pub created_at: String, /// Tries made so far. pub attempts: u32, pub next_attempt_at: Option, + /// Set while a worker pass holds the row. Past this stamp the lease is void. + pub lease_until: Option, pub sent_at: Option, + pub discarded_at: Option, pub last_error: Option, } @@ -162,6 +250,7 @@ impl fmt::Debug for OutboxEntry { .field("id", &self.id) .field("to_addr", &self.to_addr) .field("subject", &self.subject) + .field("kind", &self.kind) .field("body", &"") .field("attempts", &self.attempts) .field("next_attempt_at", &self.next_attempt_at) @@ -171,6 +260,17 @@ impl fmt::Debug for OutboxEntry { } } +/// The latest message of one kind for one account, as the account page shows it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MailStatus { + pub state: MailState, + pub created_at: String, + /// Tries made so far, failed ones included. + pub attempts: u32, + pub sent_at: Option, + pub last_error: Option, +} + /// Where a message stands. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OutboxStatus { @@ -199,6 +299,23 @@ impl OutboxEntry { OutboxStatus::GaveUp } } + + /// The state of the row at `now` (an RFC 3339-style stamp, compared as text). + pub fn state_at(&self, now: &str) -> MailState { + if self.sent_at.is_some() { + MailState::Sent + } else if self.discarded_at.is_some() { + MailState::Discarded + } else if self.lease_until.as_deref().is_some_and(|until| until > now) { + MailState::Sending + } else if self.next_attempt_at.is_none() { + MailState::Failed + } else if self.attempts == 0 { + MailState::Queued + } else { + MailState::Retrying + } + } } /// Why a send failed. A transient failure is retried on the schedule; a permanent one gives up now. @@ -299,6 +416,8 @@ mod tests { body: "https://forge.test/reset/SECRET-TOKEN".into(), message_id: None, in_reply_to: None, + kind: MailKind::PasswordReset, + user_id: None, }; assert!(!format!("{mail:?}").contains("SECRET-TOKEN")); } @@ -341,6 +460,78 @@ mod tests { assert!(validate_settings(&bad_from).is_err()); } + fn row(attempts: u32) -> OutboxEntry { + OutboxEntry { + id: "1".into(), + idem_key: "k".into(), + to_addr: "a@example.com".into(), + subject: "s".into(), + body: "b".into(), + message_id: None, + in_reply_to: None, + kind: MailKind::Notification, + user_id: None, + created_at: "2026-10-15T12:00:00Z".into(), + attempts, + next_attempt_at: Some("2026-10-15T12:00:00Z".into()), + lease_until: None, + sent_at: None, + discarded_at: None, + last_error: None, + } + } + + #[test] + fn kinds_and_states_round_trip_their_names() { + for kind in MailKind::ALL { + assert_eq!(MailKind::parse(kind.as_str()), Some(kind)); + } + assert_eq!(MailKind::parse("spam"), None); + for state in MailState::ALL { + assert_eq!(MailState::parse(state.as_str()), Some(state)); + } + assert_eq!(MailState::parse("gave up"), None); + } + + #[test] + fn a_row_moves_from_queued_to_sending_to_retrying_to_failed() { + let now = "2026-10-15T12:00:00Z"; + let mut entry = row(0); + assert_eq!(entry.state_at(now), MailState::Queued); + + entry.lease_until = Some("2026-10-15T12:05:00Z".into()); + assert_eq!( + entry.state_at(now), + MailState::Sending, + "leased and not yet expired" + ); + entry.lease_until = Some("2026-10-15T11:59:00Z".into()); + assert_eq!( + entry.state_at(now), + MailState::Queued, + "an expired lease is void" + ); + entry.lease_until = None; + + entry.attempts = 1; + entry.last_error = Some("timeout".into()); + assert_eq!(entry.state_at(now), MailState::Retrying); + + entry.next_attempt_at = None; + assert_eq!(entry.state_at(now), MailState::Failed); + } + + #[test] + fn sent_wins_over_everything_and_discard_only_applies_to_unsent() { + let now = "2026-10-15T12:00:00Z"; + let mut entry = row(2); + entry.next_attempt_at = None; + entry.discarded_at = Some(now.into()); + assert_eq!(entry.state_at(now), MailState::Discarded); + entry.sent_at = Some(now.into()); + assert_eq!(entry.state_at(now), MailState::Sent); + } + #[test] fn status_follows_sent_at_and_next_attempt() { let mut entry = OutboxEntry { @@ -351,10 +542,14 @@ mod tests { body: "b".into(), message_id: None, in_reply_to: None, + kind: MailKind::Other, + user_id: None, created_at: "t".into(), attempts: 0, next_attempt_at: Some("t".into()), + lease_until: None, sent_at: None, + discarded_at: None, last_error: None, }; assert_eq!(entry.status(), OutboxStatus::Queued); diff --git a/crates/forge-core/src/model.rs b/crates/forge-core/src/model.rs index b9eb52a..b96bf4b 100644 --- a/crates/forge-core/src/model.rs +++ b/crates/forge-core/src/model.rs @@ -37,6 +37,8 @@ pub struct User { pub created_at: String, /// Raw markdown, at most 2000 chars. pub about: String, + /// Optional heading shown on the profile instead of the username. `None` when unset. + pub display_name: Option, /// IANA name, e.g. "Europe/Istanbul"; "UTC" by default. pub timezone: String, /// Hash of the current avatar, or `None` when the user has none. Filled by the user queries. @@ -45,6 +47,8 @@ pub struct User { pub theme: String, /// Language code, e.g. "en"; "auto" uses the instance default. pub language: String, + /// Accent colour: the id of a palette in forge-web's `accent_palette.rs`. "sage" is the default. + pub accent: String, /// `User` for a person, `Org` for an organization. pub kind: AccountKind, /// Whether notifications are also sent by email (needs a verified email and instance mail). @@ -125,6 +129,7 @@ impl std::fmt::Debug for User { .field("avatar_hash", &self.avatar_hash) .field("theme", &self.theme) .field("language", &self.language) + .field("accent", &self.accent) .field("kind", &self.kind) .finish() } @@ -208,10 +213,12 @@ mod tests { is_admin: true, created_at: "now".into(), about: String::new(), + display_name: None, timezone: "UTC".into(), avatar_hash: None, theme: "auto".into(), language: "auto".into(), + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), kind: AccountKind::User, email_notifications: true, }; diff --git a/crates/forge-core/src/store/account_tokens.rs b/crates/forge-core/src/store/account_tokens.rs index 606bd41..2c8947b 100644 --- a/crates/forge-core/src/store/account_tokens.rs +++ b/crates/forge-core/src/store/account_tokens.rs @@ -100,7 +100,7 @@ impl Store { &conn, "SELECT id, username, email, password_hash, is_admin, created_at, about, timezone, \ (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ - theme, language, kind, email_notifications FROM users WHERE LOWER(email) = LOWER(?1) \ + theme, language, kind, email_notifications, display_name, accent FROM users WHERE LOWER(email) = LOWER(?1) \ AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1", (email.to_owned(),), map_user, @@ -298,10 +298,12 @@ impl Store { is_admin: false, created_at: now.clone(), about: String::new(), + display_name: None, timezone: "UTC".to_owned(), avatar_hash: None, theme: "light".into(), language: "auto".into(), + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), kind: AccountKind::User, email_notifications: true, }; diff --git a/crates/forge-core/src/store/mail.rs b/crates/forge-core/src/store/mail.rs index cb1af78..10ca446 100644 --- a/crates/forge-core/src/store/mail.rs +++ b/crates/forge-core/src/store/mail.rs @@ -10,15 +10,34 @@ use super::{ }; use crate::error::{Error, Result}; use crate::mail::{ - MailPassword, MailSettings, MailSettingsUpdate, OutboxEntry, OutgoingMail, Security, - validate_settings, + MailKind, MailPassword, MailSettings, MailSettingsUpdate, MailState, MailStatus, OutboxEntry, + OutgoingMail, Security, validate_settings, }; use crate::secret; const SETTINGS_COLS: &str = "host, port, security, username, from_addr, from_name, enabled, \ password_sealed IS NOT NULL, updated_at"; const OUTBOX_COLS: &str = "id, idem_key, to_addr, subject, body_text, created_at, attempts, \ - next_attempt_at, sent_at, last_error, message_id, in_reply_to"; + next_attempt_at, sent_at, last_error, message_id, in_reply_to, kind, \ + user_id, lease_until, discarded_at"; + +/// The SQL condition that selects the rows in `state`. It takes `?1`, the current stamp. +fn state_clause(state: MailState) -> &'static str { + match state { + MailState::Sent => "sent_at IS NOT NULL", + MailState::Discarded => "sent_at IS NULL AND discarded_at IS NOT NULL", + MailState::Sending => "sent_at IS NULL AND discarded_at IS NULL AND lease_until > ?1", + MailState::Failed => "sent_at IS NULL AND discarded_at IS NULL AND next_attempt_at IS NULL", + MailState::Queued => { + "sent_at IS NULL AND discarded_at IS NULL AND next_attempt_at IS NOT NULL \ + AND attempts = 0 AND (lease_until IS NULL OR lease_until <= ?1)" + } + MailState::Retrying => { + "sent_at IS NULL AND discarded_at IS NULL AND next_attempt_at IS NOT NULL \ + AND attempts > 0 AND (lease_until IS NULL OR lease_until <= ?1)" + } + } +} fn map_settings(row: &Row) -> Result { let port = col_int(row, 1)?; @@ -41,6 +60,7 @@ fn map_settings(row: &Row) -> Result { fn map_outbox(row: &Row) -> Result { let attempts = col_int(row, 6)?; + let kind = col_text(row, 12)?; Ok(OutboxEntry { id: col_text(row, 0)?, idem_key: col_text(row, 1)?, @@ -55,6 +75,11 @@ fn map_outbox(row: &Row) -> Result { last_error: col_opt_text(row, 9)?, message_id: col_opt_text(row, 10)?, in_reply_to: col_opt_text(row, 11)?, + kind: MailKind::parse(&kind) + .ok_or_else(|| Error::Database(format!("unknown mail kind {kind}")))?, + user_id: col_opt_text(row, 13)?, + lease_until: col_opt_text(row, 14)?, + discarded_at: col_opt_text(row, 15)?, }) } @@ -163,8 +188,8 @@ impl Store { let inserted = conn .execute( "INSERT INTO mail_outbox (id, idem_key, to_addr, subject, body_text, created_at, \ - attempts, next_attempt_at, message_id, in_reply_to) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, ?6, ?7, ?8) \ + attempts, next_attempt_at, message_id, in_reply_to, kind, user_id) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, ?6, ?7, ?8, ?9, ?10) \ ON CONFLICT (idem_key) DO NOTHING", ( new_id(), @@ -175,6 +200,8 @@ impl Store { now, mail.message_id.clone().map_or(Value::Null, Value::Text), mail.in_reply_to.clone().map_or(Value::Null, Value::Text), + mail.kind.as_str().to_owned(), + mail.user_id.clone().map_or(Value::Null, Value::Text), ), ) .await @@ -265,6 +292,120 @@ impl Store { .map(Option::flatten) } + /// Outbox rows in `state` (or every row when `None`), newest first. `now` decides the + /// states that depend on the clock (sending, and the queued and retrying split). + pub async fn list_mail( + &self, + state: Option, + now: &str, + limit: u32, + ) -> Result> { + let conn = self.read_conn().await; + let filter = state.map_or("1 = 1", state_clause); + fetch_all( + &conn, + &format!( + "SELECT {OUTBOX_COLS} FROM mail_outbox WHERE {filter} \ + ORDER BY created_at DESC, id DESC LIMIT ?2" + ), + (now.to_owned(), i64::from(limit)), + map_outbox, + ) + .await + } + + /// How many outbox rows stand in each state at `now`, in `MailState::ALL` order. + pub async fn mail_state_counts(&self, now: &str) -> Result> { + let conn = self.read_conn().await; + let mut counts = Vec::with_capacity(MailState::ALL.len()); + for state in MailState::ALL { + let clause = state_clause(state); + let sql = format!("SELECT COUNT(*) FROM mail_outbox WHERE {clause}"); + // A clause without `?1` must be bound with no parameters at all. + let n = if clause.contains("?1") { + fetch_opt(&conn, &sql, (now.to_owned(),), |row| col_int(row, 0)).await? + } else { + fetch_opt(&conn, &sql, (), |row| col_int(row, 0)).await? + } + .unwrap_or(0); + counts.push((state, u32::try_from(n).unwrap_or(u32::MAX))); + } + Ok(counts) + } + + /// Gives a failed message a fresh set of tries, due at `now`. Returns `false` when the row is + /// not failed (it was sent, discarded, or is still scheduled). + pub async fn retry_mail(&self, id: &str, now: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE mail_outbox SET attempts = 0, next_attempt_at = ?2, lease_until = NULL \ + WHERE id = ?1 AND sent_at IS NULL AND discarded_at IS NULL \ + AND next_attempt_at IS NULL", + (id.to_owned(), now.to_owned()), + ) + .await + .map_err(db_err)?; + Ok(changed > 0) + } + + /// Gives up on a failed message for good, keeping its row and last error. Returns `false` + /// when the row is not failed. + pub async fn discard_mail(&self, id: &str, now: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE mail_outbox SET discarded_at = ?2 WHERE id = ?1 AND sent_at IS NULL \ + AND discarded_at IS NULL AND next_attempt_at IS NULL", + (id.to_owned(), now.to_owned()), + ) + .await + .map_err(db_err)?; + Ok(changed > 0) + } + + /// Clears the leases of unsent rows and returns how many were cleared. Run once at boot: a + /// lease left by a process that stopped mid-pass would hold its row until the lease ran out, + /// and the row is due again as soon as it is released. + pub async fn release_mail_leases(&self) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE mail_outbox SET lease_until = NULL \ + WHERE sent_at IS NULL AND lease_until IS NOT NULL", + (), + ) + .await + .map_err(db_err) + } + + /// The newest message of `kind` sent about `user_id`, with its state now. `None` when no such + /// message was queued. + pub async fn latest_mail_for( + &self, + user_id: &str, + kind: MailKind, + ) -> Result> { + let now = crate::time::now_stamp(); + let conn = self.read_conn().await; + let entry = fetch_opt( + &conn, + &format!( + "SELECT {OUTBOX_COLS} FROM mail_outbox WHERE user_id = ?1 AND kind = ?2 \ + ORDER BY created_at DESC, id DESC LIMIT 1" + ), + (user_id.to_owned(), kind.as_str().to_owned()), + map_outbox, + ) + .await?; + Ok(entry.map(|entry| MailStatus { + state: entry.state_at(&now), + created_at: entry.created_at, + attempts: entry.attempts, + sent_at: entry.sent_at, + last_error: entry.last_error, + })) + } + /// The newest outbox rows, newest first. pub async fn recent_mail(&self, limit: u32) -> Result> { let conn = self.read_conn().await; @@ -306,6 +447,8 @@ mod tests { body: "Body".into(), message_id: None, in_reply_to: None, + kind: MailKind::Other, + user_id: None, } } @@ -538,4 +681,218 @@ mod tests { // Without a password, no key is needed. assert!(store.update_mail_settings(&settings(None)).await.is_ok()); } + + #[tokio::test] + async fn the_queue_filters_and_counts_by_state() { + use crate::mail::MailState; + let (_dir, store) = store_with_key().await; + let now = now_stamp(); + for (key, to) in [ + ("sent", "s@example.com"), + ("failed", "f@example.com"), + ("retry", "r@example.com"), + ("queued", "q@example.com"), + ("dropped", "d@example.com"), + ] { + store.enqueue_mail(key, &mail(to)).await.expect("queued"); + } + let rows = store.recent_mail(10).await.expect("rows"); + let id = |to: &str| { + rows.iter() + .find(|r| r.to_addr == to) + .expect("row") + .id + .clone() + }; + store + .mark_mail_sent(&id("s@example.com"), &now) + .await + .expect("sent"); + store + .mark_mail_failed(&id("f@example.com"), "550 no such user", None) + .await + .expect("failed"); + store + .mark_mail_failed( + &id("r@example.com"), + "timeout", + Some(&stamp_after(Duration::from_secs(3600))), + ) + .await + .expect("retrying"); + store + .mark_mail_failed(&id("d@example.com"), "550", None) + .await + .expect("failed"); + assert!( + store + .discard_mail(&id("d@example.com"), &now) + .await + .expect("discard") + ); + assert!( + !store + .discard_mail(&id("q@example.com"), &now) + .await + .expect("discard"), + "only failed mail can be discarded" + ); + + let counts = store.mail_state_counts(&now).await.expect("counts"); + let count = |state: MailState| counts.iter().find(|(s, _)| *s == state).expect("state").1; + assert_eq!(count(MailState::Queued), 1); + assert_eq!(count(MailState::Retrying), 1); + assert_eq!(count(MailState::Sending), 0); + assert_eq!(count(MailState::Sent), 1); + assert_eq!(count(MailState::Failed), 1); + assert_eq!(count(MailState::Discarded), 1); + + let failed = store + .list_mail(Some(MailState::Failed), &now, 10) + .await + .expect("failed list"); + assert_eq!(failed.len(), 1); + assert_eq!(failed[0].to_addr, "f@example.com"); + assert_eq!(failed[0].last_error.as_deref(), Some("550 no such user")); + assert_eq!(store.list_mail(None, &now, 10).await.expect("all").len(), 5); + } + + #[tokio::test] + async fn a_failed_message_can_be_retried_once_and_then_it_is_queued() { + use crate::mail::MailState; + let (_dir, store) = store_with_key().await; + let now = now_stamp(); + store + .enqueue_mail("k", &mail("a@example.com")) + .await + .expect("queued"); + let id = store.recent_mail(1).await.expect("row").remove(0).id; + store + .mark_mail_failed(&id, "550", None) + .await + .expect("failed"); + + assert!(store.retry_mail(&id, &now).await.expect("retry")); + assert!( + !store.retry_mail(&id, &now).await.expect("again"), + "a queued message is not failed, so it is not retried twice" + ); + let queued = store + .list_mail(Some(MailState::Queued), &now, 10) + .await + .expect("queued list"); + assert_eq!(queued.len(), 1, "a retry starts over with no tries spent"); + assert_eq!(queued[0].attempts, 0); + } + + #[tokio::test] + async fn a_lease_left_by_a_dead_pass_is_released_at_boot() { + use crate::mail::MailState; + let (_dir, store) = store_with_key().await; + store + .enqueue_mail("k", &mail("a@example.com")) + .await + .expect("queued"); + let now = now_stamp(); + let held_until = stamp_after(Duration::from_secs(300)); + assert_eq!( + store + .lease_mail(&now, &held_until, 10) + .await + .expect("lease") + .len(), + 1 + ); + assert!( + store + .lease_mail(&now, &held_until, 10) + .await + .expect("again") + .is_empty(), + "a leased row is not handed out twice" + ); + assert_eq!( + store + .list_mail(Some(MailState::Sending), &now, 10) + .await + .expect("sending") + .len(), + 1 + ); + + assert_eq!(store.release_mail_leases().await.expect("release"), 1); + assert_eq!( + store + .list_mail(Some(MailState::Queued), &now, 10) + .await + .expect("queued") + .len(), + 1, + "a released row is queued again" + ); + assert_eq!( + store + .lease_mail(&now, &held_until, 10) + .await + .expect("lease") + .len(), + 1 + ); + } + + #[tokio::test] + async fn the_latest_mail_of_a_kind_is_read_per_account() { + use crate::mail::{MailKind, MailState}; + let (_dir, store) = store_with_key().await; + assert!( + store + .latest_mail_for("u1", MailKind::Verification) + .await + .expect("none yet") + .is_none() + ); + let mut verify = mail("a@example.com"); + verify.kind = MailKind::Verification; + verify.user_id = Some("u1".into()); + store + .enqueue_mail("verify:1", &verify) + .await + .expect("queued"); + let status = store + .latest_mail_for("u1", MailKind::Verification) + .await + .expect("status") + .expect("one"); + assert_eq!(status.state, MailState::Queued); + assert!(status.sent_at.is_none()); + + let id = store.recent_mail(1).await.expect("row").remove(0).id; + store + .mark_mail_failed(&id, "550 no", None) + .await + .expect("failed"); + let status = store + .latest_mail_for("u1", MailKind::Verification) + .await + .expect("status") + .expect("one"); + assert_eq!(status.state, MailState::Failed); + assert_eq!(status.last_error.as_deref(), Some("550 no")); + + assert!( + store + .latest_mail_for("u1", MailKind::PasswordReset) + .await + .expect("other kind") + .is_none(), + "a kind with no mail is not the verification mail" + ); + assert!( + store + .latest_mail_for("u2", MailKind::Verification) + .await + .expect("other user") + .is_none() + ); + } } diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index f291c4e..ea0fbf5 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -56,6 +56,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ include_str!("../../migrations/0036_default_light_theme.sql"), ), (37, include_str!("../../migrations/0037_profile_pins.sql")), + (38, include_str!("../../migrations/0038_display_name.sql")), + (39, include_str!("../../migrations/0039_totp_device.sql")), + (40, include_str!("../../migrations/0040_mail_queue.sql")), + (41, include_str!("../../migrations/0041_accent.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index ab82129..cd352a9 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -54,6 +54,28 @@ use crate::time::now_stamp; const BUSY_TIMEOUT: Duration = Duration::from_millis(5000); /// Longest accepted `about` text, in characters. pub const MAX_ABOUT_CHARS: usize = 2000; +/// Longest accepted display name, in characters. +pub const MAX_DISPLAY_NAME_CHARS: usize = 80; + +/// Checks a display name. Surrounding whitespace is trimmed; an empty result means "no name" and +/// gives `None`. Control characters are rejected; any other Unicode text is allowed. +pub fn validate_display_name(input: &str) -> Result> { + let name = input.trim(); + if name.is_empty() { + return Ok(None); + } + if name.chars().count() > MAX_DISPLAY_NAME_CHARS { + return Err(Error::Invalid(format!( + "display name is longer than {MAX_DISPLAY_NAME_CHARS} characters" + ))); + } + if name.chars().any(char::is_control) { + return Err(Error::Invalid( + "display name must not contain control characters".into(), + )); + } + Ok(Some(name.to_string())) +} /// Async and `Clone`. /// @@ -88,7 +110,7 @@ struct Inner { const USER_COLS: &str = "id, username, email, password_hash, is_admin, created_at, about, timezone, \ (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ - theme, language, kind, email_notifications"; + theme, language, kind, email_notifications, display_name, accent"; const SESSION_COLS: &str = "id, user_id, csrf_token, created_at, expires_at, last_seen, user_agent"; const SSH_KEY_COLS: &str = "id, user_id, title, algorithm, key_blob, fingerprint, created_at, last_used_at"; @@ -173,10 +195,12 @@ impl Store { is_admin, created_at: now_stamp(), about: String::new(), + display_name: None, timezone: "UTC".to_string(), avatar_hash: None, theme: "light".into(), language: "auto".into(), + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), kind: AccountKind::User, email_notifications: true, }; @@ -215,10 +239,12 @@ impl Store { is_admin: true, created_at: now_stamp(), about: String::new(), + display_name: None, timezone: "UTC".to_string(), avatar_hash: None, theme: "light".into(), language: "auto".into(), + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), kind: AccountKind::User, email_notifications: true, }; @@ -776,6 +802,27 @@ impl Store { Ok(()) } + /// Sets the display name. `name` goes through `validate_display_name`; an empty name clears + /// it (stored as NULL). A rejected name writes nothing. + pub async fn set_display_name(&self, user_id: &str, name: &str) -> Result<()> { + let name = match validate_display_name(name)? { + Some(name) => Value::Text(name), + None => Value::Null, + }; + let conn = self.inner.conn.lock().await; + let n = conn + .execute( + "UPDATE users SET display_name = ?2 WHERE id = ?1", + vec![Value::Text(user_id.to_owned()), name], + ) + .await + .map_err(db_err)?; + if n == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest. pub async fn set_avatar(&self, user_id: &str, png: &[u8], hash: &str) -> Result<()> { let conn = self.inner.conn.lock().await; @@ -990,6 +1037,8 @@ fn map_user(row: &Row) -> Result { language: col_text(row, 10)?, kind: account_kind(&col_text(row, 11)?)?, email_notifications: col_bool(row, 12)?, + display_name: col_opt_text(row, 13)?, + accent: col_text(row, 14)?, }) } @@ -1421,6 +1470,12 @@ pub struct TotpState { pub enabled: bool, /// The last time step whose code was accepted (replay guard). pub last_step: u64, + /// The device name the user gave at enrollment. `None` means the default name. + pub name: Option, + /// When two-factor was turned on. `None` before that, and for rows from before migration 39. + pub created_at: Option, + /// When a TOTP code last passed. `None` until the first one. + pub last_used_at: Option, } /// Checks the basic shape of an email address: one `@`, a non-empty local part and domain, @@ -1463,8 +1518,8 @@ impl Store { let conn = self.inner.conn.lock().await; let n = conn .execute( - "UPDATE users SET password_hash = ?2 WHERE id = ?1", - (user_id.to_string(), password_hash.to_string()), + "UPDATE users SET password_hash = ?2, password_changed_at = ?3 WHERE id = ?1", + (user_id.to_string(), password_hash.to_string(), now_stamp()), ) .await .map_err(db_err)?; @@ -1494,7 +1549,8 @@ impl Store { let conn = self.read_conn().await; fetch_opt( &conn, - "SELECT totp_secret_sealed, totp_enabled, totp_last_step FROM users WHERE id = ?1 LIMIT 1", + "SELECT totp_secret_sealed, totp_enabled, totp_last_step, totp_name, totp_created_at, \ + totp_last_used_at FROM users WHERE id = ?1 LIMIT 1", (user_id.to_string(),), |row| { let sealed_secret = match row.get_value(0).map_err(db_err)? { @@ -1509,6 +1565,9 @@ impl Store { sealed_secret, enabled: col_bool(row, 1)?, last_step: u64::try_from(col_int(row, 2)?).unwrap_or(0), + name: col_opt_text(row, 3)?, + created_at: col_opt_text(row, 4)?, + last_used_at: col_opt_text(row, 5)?, }) }, ) @@ -1521,7 +1580,8 @@ impl Store { let conn = self.inner.conn.lock().await; let n = conn .execute( - "UPDATE users SET totp_secret_sealed = ?2, totp_enabled = 0, totp_last_step = 0 \ + "UPDATE users SET totp_secret_sealed = ?2, totp_enabled = 0, totp_last_step = 0, \ + totp_name = NULL, totp_created_at = NULL, totp_last_used_at = NULL \ WHERE id = ?1", (user_id.to_string(), sealed.as_bytes().to_vec()), ) @@ -1546,12 +1606,14 @@ impl Store { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let uid = user_id.to_string(); + let now = now_stamp(); let outcome: Result<()> = async { let n = tx .execute( - "UPDATE users SET totp_enabled = 1, totp_last_step = ?2 \ + "UPDATE users SET totp_enabled = 1, totp_last_step = ?2, \ + totp_created_at = ?3, totp_last_used_at = ?3 \ WHERE id = ?1 AND totp_secret_sealed IS NOT NULL", - (uid.clone(), step), + (uid.clone(), step, now), ) .await .map_err(db_err)?; @@ -1583,7 +1645,8 @@ impl Store { let uid = user_id.to_string(); let outcome: Result<()> = async { tx.execute( - "UPDATE users SET totp_secret_sealed = NULL, totp_enabled = 0, totp_last_step = 0 \ + "UPDATE users SET totp_secret_sealed = NULL, totp_enabled = 0, totp_last_step = 0, \ + totp_name = NULL, totp_created_at = NULL, totp_last_used_at = NULL \ WHERE id = ?1", (uid.clone(),), ) @@ -1608,14 +1671,44 @@ impl Store { let conn = self.inner.conn.lock().await; let n = conn .execute( - "UPDATE users SET totp_last_step = ?2 WHERE id = ?1 AND totp_last_step < ?2", - (user_id.to_string(), step), + "UPDATE users SET totp_last_step = ?2, totp_last_used_at = ?3 \ + WHERE id = ?1 AND totp_last_step < ?2", + (user_id.to_string(), step, now_stamp()), ) .await .map_err(db_err)?; Ok(n > 0) } + /// Sets the device name shown on the security page. `None` restores the default name. + pub async fn set_totp_name(&self, user_id: &str, name: Option<&str>) -> Result<()> { + let conn = self.inner.conn.lock().await; + let value = match name { + Some(name) => Value::Text(name.to_owned()), + None => Value::Null, + }; + conn.execute( + "UPDATE users SET totp_name = ?2 WHERE id = ?1", + (user_id.to_string(), value), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// When the password last changed, or `None` when no change was recorded since migration 39. + pub async fn password_changed_at(&self, user_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT password_changed_at FROM users WHERE id = ?1 LIMIT 1", + (user_id.to_string(),), + |row| col_opt_text(row, 0), + ) + .await + .map(Option::flatten) + } + /// Marks an unused recovery code as used. Returns false when no unused code has this hash. pub async fn consume_recovery_code(&self, user_id: &str, code_hash: &str) -> Result { let conn = self.inner.conn.lock().await; @@ -1734,6 +1827,67 @@ mod tests { assert_eq!(still.timezone, "Europe/Istanbul"); } + #[test] + fn display_name_validation() { + assert_eq!(validate_display_name(" ").unwrap(), None); + assert_eq!(validate_display_name("").unwrap(), None); + assert_eq!( + validate_display_name(" Ahmet Kaan Gümüş ").unwrap(), + Some("Ahmet Kaan Gümüş".to_string()) + ); + // The limit counts characters: 80 two-byte letters fit, 81 do not. + assert!(validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS)).is_ok()); + assert!(matches!( + validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS + 1)), + Err(Error::Invalid(_)) + )); + assert!(matches!( + validate_display_name("two\nlines"), + Err(Error::Invalid(_)) + )); + assert!(matches!( + validate_display_name("tab\there"), + Err(Error::Invalid(_)) + )); + assert!(matches!( + validate_display_name("nul\0byte"), + Err(Error::Invalid(_)) + )); + } + + #[tokio::test] + async fn display_name_round_trips_and_validates() { + let dir = tempfile::tempdir().unwrap(); + let (store, user) = store_with_user(&dir).await; + assert_eq!(user.display_name, None); + + store + .set_display_name(&user.id, " Ahmet Kaan Gümüş ") + .await + .unwrap(); + let fetched = store.user_by_id(&user.id).await.unwrap().unwrap(); + assert_eq!(fetched.display_name.as_deref(), Some("Ahmet Kaan Gümüş")); + + // Blank input clears the name back to NULL. + store.set_display_name(&user.id, " ").await.unwrap(); + let cleared = store.user_by_id(&user.id).await.unwrap().unwrap(); + assert_eq!(cleared.display_name, None); + + // A rejected name leaves the stored value alone. + store.set_display_name(&user.id, "Kept").await.unwrap(); + let long = "x".repeat(MAX_DISPLAY_NAME_CHARS + 1); + assert!(matches!( + store.set_display_name(&user.id, &long).await, + Err(Error::Invalid(_)) + )); + assert!(matches!( + store.set_display_name("nobody", "ok").await, + Err(Error::NotFound) + )); + let still = store.user_by_id(&user.id).await.unwrap().unwrap(); + assert_eq!(still.display_name.as_deref(), Some("Kept")); + } + #[tokio::test] async fn avatar_upsert_hash_delete() { let dir = tempfile::tempdir().unwrap(); @@ -2015,7 +2169,7 @@ impl Store { WHERE collaborators.repo_id = ?1 ORDER BY users.username_folded" ), (repo_id.to_string(),), - |row| Ok((map_user(row)?, parse_role(&col_text(row, 13)?)?)), + |row| Ok((map_user(row)?, parse_role(&col_text(row, 15)?)?)), ) .await } @@ -2452,6 +2606,75 @@ mod security_tests { assert!(!store.totp_state(&user.id).await.unwrap().unwrap().enabled); } + #[tokio::test] + async fn totp_device_tracks_added_last_used_and_name() { + let (store, user, _dir) = store_with_user().await; + assert_eq!(store.password_changed_at(&user.id).await.unwrap(), None); + store.set_totp_secret(&user.id, "v1:sealed").await.unwrap(); + let pending = store.totp_state(&user.id).await.unwrap().unwrap(); + assert_eq!((pending.created_at, pending.last_used_at), (None, None)); + + store + .enable_totp(&user.id, 100, &[recovery_hash("aaaa-bbbb")]) + .await + .unwrap(); + let on = store.totp_state(&user.id).await.unwrap().unwrap(); + let added = on.created_at.clone().expect("created_at set on enable"); + assert_eq!(on.last_used_at.as_deref(), Some(added.as_str())); + assert_eq!(on.name, None); + + store + .set_totp_name(&user.id, Some("Work phone")) + .await + .unwrap(); + assert_eq!( + store + .totp_state(&user.id) + .await + .unwrap() + .unwrap() + .name + .as_deref(), + Some("Work phone") + ); + + // Stamps have nanosecond precision and sort as text, so a later use compares greater. + std::thread::sleep(std::time::Duration::from_millis(5)); + assert!(store.accept_totp_step(&user.id, 101).await.unwrap()); + let used = store.totp_state(&user.id).await.unwrap().unwrap(); + assert!(used.last_used_at.as_deref().unwrap() > added.as_str()); + assert_eq!(used.created_at.as_deref(), Some(added.as_str())); + + // A replayed step is refused and leaves the last use alone. + std::thread::sleep(std::time::Duration::from_millis(5)); + assert!(!store.accept_totp_step(&user.id, 101).await.unwrap()); + assert_eq!( + store + .totp_state(&user.id) + .await + .unwrap() + .unwrap() + .last_used_at, + used.last_used_at + ); + + store.set_totp_name(&user.id, None).await.unwrap(); + assert_eq!( + store.totp_state(&user.id).await.unwrap().unwrap().name, + None + ); + + store.disable_totp(&user.id).await.unwrap(); + let off = store.totp_state(&user.id).await.unwrap().unwrap(); + assert_eq!( + (off.name, off.created_at, off.last_used_at), + (None, None, None) + ); + + store.set_password_hash(&user.id, "new-hash").await.unwrap(); + assert!(store.password_changed_at(&user.id).await.unwrap().is_some()); + } + fn recovery_hash(code: &str) -> String { crate::totp::recovery_code_hash(code) } diff --git a/crates/forge-core/src/store/orgs.rs b/crates/forge-core/src/store/orgs.rs index c3f2589..6d68af2 100644 --- a/crates/forge-core/src/store/orgs.rs +++ b/crates/forge-core/src/store/orgs.rs @@ -277,7 +277,7 @@ impl Store { ORDER BY (org_role = 'owner') DESC, username_folded" ), (org_id.to_string(),), - |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 13)?)?)), + |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 15)?)?)), ) .await } @@ -397,7 +397,7 @@ impl Store { (SELECT org_id FROM org_members WHERE user_id = ?1) ORDER BY username_folded" ), (user_id.to_string(),), - |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 13)?)?)), + |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 15)?)?)), ) .await } diff --git a/crates/forge-core/src/store/ui_prefs.rs b/crates/forge-core/src/store/ui_prefs.rs index 8c8ffb2..e8ad2e5 100644 --- a/crates/forge-core/src/store/ui_prefs.rs +++ b/crates/forge-core/src/store/ui_prefs.rs @@ -1,6 +1,7 @@ -//! Per-user UI preferences: the colour theme and the language. Both are stored as text in -//! `users` (migration 0030). The web layer decides which values it offers; the store only -//! checks that a value is well formed, so a new language needs no store change. +//! Per-user UI preferences: the colour theme, the language and the accent colour. All are stored +//! as text in `users` (migrations 0030 and 0041). The web layer decides which values it offers; +//! the store only checks that a value is well formed, so a new language or accent needs no store +//! change. use super::{Store, db_err}; use crate::error::{Error, Result}; @@ -11,9 +12,16 @@ pub const THEMES: &[&str] = &["auto", "light", "dark"]; /// The value meaning "follow the default", for both theme and language. pub const AUTO: &str = "auto"; +/// The accent colour a new user gets. It must match the default palette in forge-web's +/// `accent_palette.rs`, which a test there checks. +pub const DEFAULT_ACCENT: &str = "sage"; + /// Longest accepted language code, in bytes. const MAX_LANGUAGE_LEN: usize = 16; +/// Longest accepted accent id, in bytes. +const MAX_ACCENT_LEN: usize = 24; + /// True for `auto` or a BCP 47 style tag such as `en`, `tr` or `pt-BR`. pub fn valid_language(code: &str) -> bool { if code == AUTO { @@ -30,6 +38,15 @@ pub fn valid_language(code: &str) -> bool { && parts.all(|p| (1..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphanumeric())) } +/// True for a short lowercase slug such as `sage` or `rose-2`: 1 to 24 ASCII letters, digits or +/// hyphens. Whether forge offers the id is the web layer's call. +pub fn valid_accent(id: &str) -> bool { + (1..=MAX_ACCENT_LEN).contains(&id.len()) + && id + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + impl Store { /// Sets the user's theme and language. Anything malformed is rejected and nothing is written. pub async fn set_ui_prefs(&self, user_id: &str, theme: &str, language: &str) -> Result<()> { @@ -53,6 +70,25 @@ impl Store { Ok(()) } + /// Sets the user's accent colour id. A malformed id is rejected and nothing is written. + pub async fn set_accent(&self, user_id: &str, accent: &str) -> Result<()> { + if !valid_accent(accent) { + return Err(Error::Invalid(format!("accent {accent:?}"))); + } + let conn = self.inner.conn.lock().await; + let n = conn + .execute( + "UPDATE users SET accent = ?2 WHERE id = ?1", + (user_id.to_string(), accent.to_string()), + ) + .await + .map_err(db_err)?; + if n == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + /// Turns the email copy of notifications on or off for one user (migration 0035). pub async fn set_email_notifications(&self, user_id: &str, on: bool) -> Result<()> { let conn = self.inner.conn.lock().await; @@ -87,6 +123,42 @@ mod tests { assert!(!valid_language(&"a".repeat(MAX_LANGUAGE_LEN + 1))); } + #[test] + fn accent_ids() { + let longest = "a".repeat(MAX_ACCENT_LEN); + let too_long = "a".repeat(MAX_ACCENT_LEN + 1); + for ok in ["sage", "rose-2", "a", longest.as_str()] { + assert!(valid_accent(ok), "{ok}"); + } + for bad in ["", "Sage", "sage_2", "../x", "a b", too_long.as_str()] { + assert!(!valid_accent(bad), "{bad}"); + } + } + + #[tokio::test] + async fn accent_persists_and_bad_values_change_nothing() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let user = store + .create_user("tahinli", None, "hash", false) + .await + .unwrap(); + assert_eq!(user.accent, DEFAULT_ACCENT); + + store.set_accent(&user.id, "ocean").await.unwrap(); + assert_eq!( + store.user_by_id(&user.id).await.unwrap().unwrap().accent, + "ocean" + ); + + assert!(store.set_accent(&user.id, "Ocean").await.is_err()); + assert!(store.set_accent(&user.id, "../x").await.is_err()); + assert_eq!( + store.user_by_id(&user.id).await.unwrap().unwrap().accent, + "ocean" + ); + } + #[tokio::test] async fn prefs_persist_and_bad_values_change_nothing() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/forge-core/src/store/user_delete.rs b/crates/forge-core/src/store/user_delete.rs index afd4f49..9a4bffe 100644 --- a/crates/forge-core/src/store/user_delete.rs +++ b/crates/forge-core/src/store/user_delete.rs @@ -161,10 +161,12 @@ impl Store { is_admin: false, created_at: now_stamp(), about: String::new(), + display_name: None, timezone: "UTC".to_string(), avatar_hash: None, theme: "light".into(), language: "auto".into(), + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), kind: AccountKind::User, email_notifications: true, }; @@ -525,7 +527,13 @@ mod tests { .await .unwrap(); fx.store - .add_ssh_key(&fx.tahinli.id, "laptop", "ssh-ed25519", b"blob-1", "SHA256:x") + .add_ssh_key( + &fx.tahinli.id, + "laptop", + "ssh-ed25519", + b"blob-1", + "SHA256:x", + ) .await .unwrap(); fx.store diff --git a/crates/forge-core/src/time.rs b/crates/forge-core/src/time.rs index 56a4e51..6a440e7 100644 --- a/crates/forge-core/src/time.rs +++ b/crates/forge-core/src/time.rs @@ -40,10 +40,25 @@ pub fn stamp_ago(ago: Duration) -> String { format_stamp(OffsetDateTime::now_utc().saturating_sub(delta)) } +/// Unix seconds for a stamp written by [`now_stamp`]. `None` when the text is not a stamp. +pub fn stamp_to_unix(stamp: &str) -> Option { + OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339) + .ok() + .map(OffsetDateTime::unix_timestamp) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn stamp_to_unix_reads_what_now_stamp_writes() { + let stamp = "2026-10-18T10:00:00.000000000Z"; + assert_eq!(stamp_to_unix(stamp), Some(1_792_317_600)); + assert!(stamp_to_unix(&now_stamp()).is_some()); + assert_eq!(stamp_to_unix("yesterday"), None); + } + fn is_valid_stamp(s: &str) -> bool { let b = s.as_bytes(); b.len() == 30 diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 0d2b85a..e871c97 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -127,7 +127,7 @@ function adopt(doc, keepFields, dd) { document.title = doc.title; - ['lang', 'data-theme', 'data-ui'].forEach(function (name) { + ['lang', 'data-theme', 'data-accent', 'data-ui'].forEach(function (name) { if (doc.documentElement.hasAttribute(name)) { root.setAttribute(name, doc.documentElement.getAttribute(name)); } else { root.removeAttribute(name); } }); diff --git a/crates/forge-web/build.rs b/crates/forge-web/build.rs index 64b6a7e..771c318 100644 --- a/crates/forge-web/build.rs +++ b/crates/forge-web/build.rs @@ -1,21 +1,98 @@ //! Compiles style/main.scss into OUT_DIR and emits FORGE_BUILD_SHA for the binary. Each static //! asset also gets a content hash (FORGE_MAIN_CSS_V, FORGE_NAV_JS_V) that the page links use as //! their cache-busting query, so an unchanged file keeps its URL and a changed one gets a new one. +//! +//! The accent colours come from `src/accent_palette.rs`, the same data the app reads. This script +//! turns it into `_accents.scss` in OUT_DIR, which main.scss imports. use std::{env, fs, path::PathBuf}; use hex::encode; use sha2::{Digest, Sha256}; +#[path = "src/accent_palette.rs"] +#[allow(dead_code)] +mod accent_palette; + +use accent_palette::{DEFAULT, PALETTES, Palette, TOKEN_VARS, Tokens}; + /// First 12 hex characters of the SHA-256 of `bytes`. fn content_version(bytes: &[u8]) -> String { encode(Sha256::digest(bytes))[..12].to_string() } +/// One `--token: value;` line per token, indented for a rule body. +fn declarations(tokens: &Tokens) -> String { + TOKEN_VARS + .iter() + .map(|token| format!(" {}: {};\n", token.name, (token.value)(tokens))) + .collect() +} + +/// Appends `selector { … }` with the palette's tokens for one theme. `indent` is 0 or 2. +fn rule(css: &mut String, indent: &str, selector: &str, tokens: &Tokens) { + css.push_str(&format!("{indent}{selector} {{\n")); + for line in declarations(tokens).lines() { + css.push_str(&format!("{indent}{line}\n")); + } + css.push_str(&format!("{indent}}}\n")); +} + +/// The rules for one palette. The default palette sits on bare `:root`, as it always has. Every +/// other palette is scoped to `[data-accent]`, which is more specific, so it wins over the +/// default in all three theme states: light, dark by `data-theme`, and dark by the OS. +fn palette_rules(css: &mut String, palette: &Palette) { + let base = if palette.id == DEFAULT { + ":root".to_string() + } else { + format!(":root[data-accent=\"{}\"]", palette.id) + }; + let os_dark = format!("{base}:not([data-theme=\"light\"])"); + let forced_dark = format!("{base}[data-theme=\"dark\"]"); + rule(css, "", &base, &palette.light); + css.push_str("@media (prefers-color-scheme: dark) {\n"); + rule(css, " ", &os_dark, &palette.dark); + css.push_str("}\n"); + rule(css, "", &forced_dark, &palette.dark); +} + +/// The swatch chip for one palette in the settings picker: its accent, light or dark. +fn swatch_rules(css: &mut String, palette: &Palette) { + let swatch = format!(".accent-swatch[data-accent-swatch=\"{}\"]", palette.id); + css.push_str(&format!( + "{swatch} {{ background: {}; }}\n", + palette.light.accent + )); + css.push_str(&format!( + "@media (prefers-color-scheme: dark) {{\n :root:not([data-theme=\"light\"]) {swatch} {{ background: {}; }}\n}}\n", + palette.dark.accent + )); + css.push_str(&format!( + ":root[data-theme=\"dark\"] {swatch} {{ background: {}; }}\n", + palette.dark.accent + )); +} + +/// The whole generated stylesheet: the palettes, then the swatch chips. +fn accents_scss() -> String { + let mut css = String::from( + "/* Generated by crates/forge-web/build.rs from src/accent_palette.rs. Edit that file. */\n", + ); + assert_eq!(PALETTES[0].id, DEFAULT, "the default palette comes first"); + for palette in PALETTES { + palette_rules(&mut css, palette); + } + for palette in PALETTES { + swatch_rules(&mut css, palette); + } + css +} + fn main() { println!("cargo:rerun-if-env-changed=FORGE_BUILD_SHA"); println!("cargo:rerun-if-changed=../../style"); println!("cargo:rerun-if-changed=assets/nav.js"); + println!("cargo:rerun-if-changed=src/accent_palette.rs"); let sha = env::var("FORGE_BUILD_SHA").unwrap_or_else(|_| "dev".to_string()); println!("cargo:rustc-env=FORGE_BUILD_SHA={sha}"); @@ -23,9 +100,11 @@ fn main() { let manifest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo")); let out = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is set by cargo")); + fs::write(out.join("_accents.scss"), accents_scss()) + .expect("writing generated accent stylesheet to OUT_DIR"); let css = grass::from_path( manifest.join("../../style/main.scss"), - &grass::Options::default(), + &grass::Options::default().load_path(&out), ) .unwrap_or_else(|e| panic!("compiling style/main.scss: {e}")); println!( diff --git a/crates/forge-web/src/accent.rs b/crates/forge-web/src/accent.rs new file mode 100644 index 0000000..eb351be --- /dev/null +++ b/crates/forge-web/src/accent.rs @@ -0,0 +1,155 @@ +//! Accent colour: which palette a viewer sees. The colours live in `accent_palette.rs`, which +//! `build.rs` also turns into the stylesheet. This module only resolves stored ids and checks +//! which ids forge offers. + +use crate::accent_palette::{DEFAULT, PALETTES, Palette}; + +/// The palette for a stored id. An unknown or removed id falls back to the default. +pub fn resolve(stored: &str) -> &'static Palette { + PALETTES + .iter() + .find(|p| p.id == stored) + .unwrap_or_else(default_palette) +} + +/// True when forge offers this id. +pub fn is_offered(id: &str) -> bool { + PALETTES.iter().any(|p| p.id == id) +} + +/// Every offered id, in the order the picker lists them. +pub fn ids() -> impl Iterator { + PALETTES.iter().map(|p| p.id) +} + +fn default_palette() -> &'static Palette { + PALETTES + .iter() + .find(|p| p.id == DEFAULT) + .expect("the default accent is one of the palettes") +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use super::*; + use crate::accent_palette::{TOKEN_VARS, Tokens}; + + /// The neutral backgrounds of style/main.scss, in each theme. + const LIGHT_BG: &str = "#F6F8F5"; + const LIGHT_SURFACE: &str = "#FFFFFF"; + const DARK_BG: &str = "#121613"; + const DARK_SURFACE: &str = "#191E1A"; + + /// WCAG relative luminance of a `#RRGGBB` colour. + fn luminance(hex: &str) -> f64 { + let channel = |i: usize| { + let v = f64::from(u8::from_str_radix(&hex[i..i + 2], 16).expect("hex")) / 255.0; + if v <= 0.03928 { + v / 12.92 + } else { + ((v + 0.055) / 1.055).powf(2.4) + } + }; + 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5) + } + + /// WCAG contrast ratio between two colours. + fn contrast(a: &str, b: &str) -> f64 { + let (x, y) = (luminance(a), luminance(b)); + (x.max(y) + 0.05) / (x.min(y) + 0.05) + } + + fn is_hex_colour(value: &str) -> bool { + value.len() == 7 + && value.starts_with('#') + && value[1..].bytes().all(|b| b.is_ascii_hexdigit()) + } + + #[test] + fn ids_are_slugs_unique_and_the_default_comes_first() { + assert_eq!(PALETTES[0].id, DEFAULT); + assert_eq!(DEFAULT, forge_core::store::ui_prefs::DEFAULT_ACCENT); + let mut seen = HashSet::new(); + for p in PALETTES { + assert!( + forge_core::store::ui_prefs::valid_accent(p.id), + "{} is not a slug", + p.id + ); + assert!(seen.insert(p.id), "{} is listed twice", p.id); + } + } + + #[test] + fn every_token_is_a_hex_colour() { + for p in PALETTES { + for token in TOKEN_VARS { + for t in [&p.light, &p.dark] { + assert!(is_hex_colour((token.value)(t)), "{} {}", p.id, token.name); + } + } + } + } + + #[test] + fn unknown_and_removed_ids_fall_back_to_the_default() { + assert_eq!(resolve("ocean").id, "ocean"); + assert_eq!(resolve("removed-palette").id, DEFAULT); + assert_eq!(resolve("").id, DEFAULT); + assert!(is_offered("plum")); + assert!(!is_offered("removed-palette")); + } + + #[test] + fn every_palette_meets_the_contrast_targets() { + for p in PALETTES { + let themes = [ + ("light", &p.light, LIGHT_BG, LIGHT_SURFACE), + ("dark", &p.dark, DARK_BG, DARK_SURFACE), + ]; + for (theme, t, bg, surface) in themes { + let check = |what: &str, ratio: f64, min: f64| { + assert!(ratio >= min, "{} {theme} {what}: {ratio:.2} < {min}", p.id); + }; + check( + "accent_text on accent", + contrast(t.accent_text, t.accent), + 4.5, + ); + check("accent_ink on bg", contrast(t.accent_ink, bg), 4.5); + check( + "accent_ink on surface", + contrast(t.accent_ink, surface), + 4.5, + ); + check( + "accent_ink on accent_soft", + contrast(t.accent_ink, t.accent_soft), + 4.5, + ); + check( + "public_text on public_bg", + contrast(t.public_text, t.public_bg), + 4.5, + ); + check("focus on bg", contrast(t.focus, bg), 3.0); + } + } + } + + #[test] + fn heatmap_steps_grow_in_lightness_towards_the_strong_end() { + fn steps(t: &Tokens) -> [f64; 5] { + [t.h0, t.h1, t.h2, t.h3, t.h4].map(luminance) + } + for p in PALETTES { + // Light theme: each step is darker than the one before. Dark theme: each is lighter. + let light = steps(&p.light); + assert!(light.windows(2).all(|w| w[0] > w[1]), "{} light", p.id); + let dark = steps(&p.dark); + assert!(dark.windows(2).all(|w| w[0] < w[1]), "{} dark", p.id); + } + } +} diff --git a/crates/forge-web/src/accent_palette.rs b/crates/forge-web/src/accent_palette.rs new file mode 100644 index 0000000..924ad57 --- /dev/null +++ b/crates/forge-web/src/accent_palette.rs @@ -0,0 +1,338 @@ +//! Accent palettes: the one place where the accent colours are defined. Nothing else holds +//! these values. `build.rs` reads this file to generate the accent stylesheet, and the app +//! reads it to resolve a stored id and to list the settings picker. Keep it pure data: no `use`, +//! no crate items, no external crates. + +/// The colour tokens one palette sets in one theme. The values are CSS colours; `TOKEN_VARS` +/// names the custom property each field becomes. +pub struct Tokens { + pub accent: &'static str, + pub accent_ink: &'static str, + pub accent_soft: &'static str, + pub accent_text: &'static str, + pub focus: &'static str, + pub public_bg: &'static str, + pub public_text: &'static str, + pub note: &'static str, + pub hunk_bg: &'static str, + pub hunk_text: &'static str, + pub h0: &'static str, + pub h1: &'static str, + pub h2: &'static str, + pub h3: &'static str, + pub h4: &'static str, +} + +/// One accent colour: its id (the stored value and the `data-accent` attribute), and the tokens +/// used in light and dark themes. +pub struct Palette { + pub id: &'static str, + pub light: Tokens, + pub dark: Tokens, +} + +/// The palette used when none is stored, and for anonymous visitors. It must be `PALETTES[0]`. +pub const DEFAULT: &str = "sage"; + +/// One token: the custom property it becomes and the field of `Tokens` that holds its value. +pub struct TokenVar { + pub name: &'static str, + pub value: fn(&Tokens) -> &'static str, +} + +/// Every token a palette sets. +pub const TOKEN_VARS: &[TokenVar] = &[ + TokenVar { + name: "--accent", + value: |t| t.accent, + }, + TokenVar { + name: "--accent-ink", + value: |t| t.accent_ink, + }, + TokenVar { + name: "--accent-soft", + value: |t| t.accent_soft, + }, + TokenVar { + name: "--accent-text", + value: |t| t.accent_text, + }, + TokenVar { + name: "--focus", + value: |t| t.focus, + }, + TokenVar { + name: "--public-bg", + value: |t| t.public_bg, + }, + TokenVar { + name: "--public-text", + value: |t| t.public_text, + }, + TokenVar { + name: "--note", + value: |t| t.note, + }, + TokenVar { + name: "--hunk-bg", + value: |t| t.hunk_bg, + }, + TokenVar { + name: "--hunk-text", + value: |t| t.hunk_text, + }, + TokenVar { + name: "--h0", + value: |t| t.h0, + }, + TokenVar { + name: "--h1", + value: |t| t.h1, + }, + TokenVar { + name: "--h2", + value: |t| t.h2, + }, + TokenVar { + name: "--h3", + value: |t| t.h3, + }, + TokenVar { + name: "--h4", + value: |t| t.h4, + }, +]; + +/// Every accent colour on offer, in the order the picker lists them. Heatmap steps run from +/// `h0` (nearly the background) to `h4` (strongest). +pub const PALETTES: &[Palette] = &[ + // Sage: the original forge colour. + Palette { + id: "sage", + light: Tokens { + accent: "#5E7D63", + accent_ink: "#4A6750", + accent_soft: "#E4ECE3", + accent_text: "#FFFFFF", + focus: "#4A6750", + public_bg: "#E4ECE3", + public_text: "#4A6750", + note: "#4A6750", + hunk_bg: "#EDF1EB", + hunk_text: "#3F5F46", + h0: "#E6ECE4", + h1: "#C6D9C8", + h2: "#9DBDA2", + h3: "#6F9676", + h4: "#3F5F46", + }, + dark: Tokens { + accent: "#9DBEA2", + accent_ink: "#B5D2B9", + accent_soft: "#233026", + accent_text: "#0F1510", + focus: "#9DBEA2", + public_bg: "#233026", + public_text: "#B5D2B9", + note: "#B5D2B9", + hunk_bg: "#1E2620", + hunk_text: "#9DBEA2", + h0: "#1F2722", + h1: "#2D3D31", + h2: "#41604A", + h3: "#628A6C", + h4: "#9DBEA2", + }, + }, + // Blue, clear and cool. + Palette { + id: "ocean", + light: Tokens { + accent: "#467799", + accent_ink: "#336180", + accent_soft: "#DEECF6", + accent_text: "#FFFFFF", + focus: "#336180", + public_bg: "#DEECF6", + public_text: "#336180", + note: "#336180", + hunk_bg: "#E9F1F7", + hunk_text: "#2B5977", + h0: "#DFECF5", + h1: "#BED7EA", + h2: "#99BEDA", + h3: "#6692B1", + h4: "#2C5D7E", + }, + dark: Tokens { + accent: "#86B9DD", + accent_ink: "#9FCBEA", + accent_soft: "#1C2F3C", + accent_text: "#061118", + focus: "#86B9DD", + public_bg: "#1C2F3C", + public_text: "#9FCBEA", + note: "#9FCBEA", + hunk_bg: "#1A252E", + hunk_text: "#86B9DD", + h0: "#1B262F", + h1: "#243B4C", + h2: "#375C76", + h3: "#5685A5", + h4: "#88BBDF", + }, + }, + // Violet with a soft, muted edge. + Palette { + id: "plum", + light: Tokens { + accent: "#7B699C", + accent_ink: "#645482", + accent_soft: "#EBE7F5", + accent_text: "#FFFFFF", + focus: "#645482", + public_bg: "#EBE7F5", + public_text: "#645482", + note: "#645482", + hunk_bg: "#F0EEF7", + hunk_text: "#5C4B79", + h0: "#ECE7F6", + h1: "#D7CEEA", + h2: "#BEB1DA", + h3: "#9382B2", + h4: "#5F4D7E", + }, + dark: Tokens { + accent: "#BBA9E0", + accent_ink: "#CBBCEB", + accent_soft: "#2F283C", + accent_text: "#110D18", + focus: "#BBA9E0", + public_bg: "#2F283C", + public_text: "#CBBCEB", + note: "#CBBCEB", + hunk_bg: "#25212E", + hunk_text: "#BBA9E0", + h0: "#26222F", + h1: "#3C334C", + h2: "#5D4F76", + h3: "#8674A6", + h4: "#BBA9E0", + }, + }, + // Dusty pink, warm and quiet. + Palette { + id: "rose", + light: Tokens { + accent: "#A25E6F", + accent_ink: "#864958", + accent_soft: "#F6E4E8", + accent_text: "#FFFFFF", + focus: "#864958", + public_bg: "#F6E4E8", + public_text: "#864958", + note: "#864958", + hunk_bg: "#F7ECEE", + hunk_text: "#7D4050", + h0: "#F8E4E8", + h1: "#EEC7CF", + h2: "#DFA7B3", + h3: "#B67785", + h4: "#814151", + }, + dark: Tokens { + accent: "#E79DAD", + accent_ink: "#F3B2C0", + accent_soft: "#3E242A", + accent_text: "#190A0E", + focus: "#E79DAD", + public_bg: "#3E242A", + public_text: "#F3B2C0", + note: "#F3B2C0", + hunk_bg: "#2F1E22", + hunk_text: "#E79DAD", + h0: "#301F23", + h1: "#4E2D35", + h2: "#794652", + h3: "#AA6978", + h4: "#E69CAC", + }, + }, + // Clay brown, warmer and earthier than the warning amber. + Palette { + id: "ochre", + light: Tokens { + accent: "#93684B", + accent_ink: "#7A5338", + accent_soft: "#F5E6DD", + accent_text: "#FFFFFF", + focus: "#7A5338", + public_bg: "#F5E6DD", + public_text: "#7A5338", + note: "#7A5338", + hunk_bg: "#F6EEE8", + hunk_text: "#724B30", + h0: "#F4E7DF", + h1: "#E6CEBE", + h2: "#D4B199", + h3: "#AB8267", + h4: "#764D30", + }, + dark: Tokens { + accent: "#D8A98A", + accent_ink: "#E4BCA1", + accent_soft: "#39281D", + accent_text: "#170D07", + focus: "#D8A98A", + public_bg: "#39281D", + public_text: "#E4BCA1", + note: "#E4BCA1", + hunk_bg: "#2C211A", + hunk_text: "#D8A98A", + h0: "#2D221B", + h1: "#483325", + h2: "#704F39", + h3: "#9E7458", + h4: "#D8A989", + }, + }, + // Blue-grey graphite, nearly neutral. + Palette { + id: "slate", + light: Tokens { + accent: "#657383", + accent_ink: "#505E6C", + accent_soft: "#E0EBF7", + accent_text: "#FFFFFF", + focus: "#505E6C", + public_bg: "#E0EBF7", + public_text: "#505E6C", + note: "#505E6C", + hunk_bg: "#EAF0F7", + hunk_text: "#485563", + h0: "#E6EAEF", + h1: "#CCD4DD", + h2: "#AFBAC7", + h3: "#808E9C", + h4: "#4C5A69", + }, + dark: Tokens { + accent: "#A4B4C4", + accent_ink: "#B8C6D5", + accent_soft: "#272D33", + accent_text: "#0C1013", + focus: "#A4B4C4", + public_bg: "#272D33", + public_text: "#B8C6D5", + note: "#B8C6D5", + hunk_bg: "#212428", + hunk_text: "#A4B4C4", + h0: "#222529", + h1: "#323941", + h2: "#4E5965", + h3: "#728090", + h4: "#A6B6C7", + }, + }, +]; diff --git a/crates/forge-web/src/i18n/accents.rs b/crates/forge-web/src/i18n/accents.rs new file mode 100644 index 0000000..edb0ace --- /dev/null +++ b/crates/forge-web/src/i18n/accents.rs @@ -0,0 +1,39 @@ +//! Names of the accent colours on the appearance page, keyed by palette id. Adding a palette +//! without a name here fails `every_palette_has_a_name`. + +use super::Lang; + +/// The display name of a palette. An id with no name returns an empty string, which the test +/// rules out for every offered palette. +pub fn accent_name(lang: Lang, id: &str) -> &'static str { + match (id, lang) { + ("sage", Lang::En) => "Sage", + ("sage", Lang::Tr) => "Adaçayı", + ("ocean", Lang::En) => "Ocean", + ("ocean", Lang::Tr) => "Okyanus", + ("plum", Lang::En) => "Plum", + ("plum", Lang::Tr) => "Erik", + ("rose", Lang::En) => "Rose", + ("rose", Lang::Tr) => "Gül", + ("ochre", Lang::En) => "Ochre", + ("ochre", Lang::Tr) => "Toprak", + ("slate", Lang::En) => "Slate", + ("slate", Lang::Tr) => "Arduvaz", + _ => "", + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::accent; + + #[test] + fn every_palette_has_a_name() { + for id in accent::ids() { + for lang in [Lang::En, Lang::Tr] { + assert!(!accent_name(lang, id).is_empty(), "{id} has no name"); + } + } + } +} diff --git a/crates/forge-web/src/i18n/admin.rs b/crates/forge-web/src/i18n/admin.rs index 0fd5edb..684075e 100644 --- a/crates/forge-web/src/i18n/admin.rs +++ b/crates/forge-web/src/i18n/admin.rs @@ -1,7 +1,7 @@ //! Strings for the admin pages: users, replication, backups, mail, CI runners and the audit log. //! See `docs` in `super` for the pattern. -use forge_core::mail::OutboxStatus; +use forge_core::mail::{MailKind, MailState}; use forge_core::store::backup_runs::{RunKind, RunTrigger}; use super::Lang; @@ -68,6 +68,19 @@ pub enum K { Mail, MailHost, MailIntro, + MailTabSettings, + MailTabQueue, + MailFilterAll, + MailRetryNow, + MailDiscard, + MailRetried, + MailNotFailed, + MailDiscarded, + MailSentAt, + MailTransportNote, + MailTransportInUse, + MailQueueIntro, + MailNothingMatches, MailPort, MailSettingsSaved, MovedToGhost, @@ -77,11 +90,9 @@ pub enum K { NoRunnersYet, NoRunnerWithId, NoRunsYet, - NothingQueued, Older, OwnLogIntro, PasswordStoredHint, - RecentMessages, RecentRuns, ReconcileNow, ReconcileStarted, @@ -293,6 +304,44 @@ pub fn t(lang: Lang, key: K) -> &'static str { (LastSuccess, Tr) => "Son başarı", (Mail, En) => "Mail", (Mail, Tr) => "E-posta", + (MailTabSettings, En) => "Settings", + (MailTabSettings, Tr) => "Ayarlar", + (MailTabQueue, En) => "Queue", + (MailTabQueue, Tr) => "Kuyruk", + (MailFilterAll, En) => "All", + (MailFilterAll, Tr) => "Tümü", + (MailRetryNow, En) => "Retry now", + (MailRetryNow, Tr) => "Şimdi yeniden dene", + (MailDiscard, En) => "Discard", + (MailDiscard, Tr) => "Vazgeç", + (MailRetried, En) => "The message is queued for another try.", + (MailRetried, Tr) => "Mesaj yeniden denenmek üzere kuyruğa alındı.", + (MailNotFailed, En) => { + "Only a failed message can be retried or discarded, and this one is not failed." + } + (MailNotFailed, Tr) => { + "Yalnızca başarısız bir mesaj yeniden denenebilir ya da vazgeçilebilir; bu mesaj başarısız değil." + } + (MailDiscarded, En) => "The message was discarded.", + (MailDiscarded, Tr) => "Mesajdan vazgeçildi.", + (MailSentAt, En) => "Sent", + (MailSentAt, Tr) => "Gönderildi", + (MailTransportNote, En) => { + "The SMTP account is stored in the database and applies to the next send, with no restart. The transport comes from forge.toml, in the [mail] section." + } + (MailTransportNote, Tr) => { + "SMTP hesabı veritabanında tutulur ve bir sonraki gönderimde, yeniden başlatmadan geçerli olur. Taşıma yöntemi forge.toml dosyasındaki [mail] bölümünden gelir." + } + (MailTransportInUse, En) => "Transport in use:", + (MailTransportInUse, Tr) => "Kullanılan taşıma:", + (MailQueueIntro, En) => { + "Every message goes through this queue. A failed try is retried on a backoff; a message that keeps failing is marked failed, and you can retry or discard it here." + } + (MailQueueIntro, Tr) => { + "Her ileti bu kuyruktan geçer. Başarısız gönderim, aralığı artan şekilde yeniden denenir; sürekli başarısız olan ileti başarısız işaretlenir ve burada yeniden denenebilir ya da vazgeçilebilir." + } + (MailNothingMatches, En) => "No message is in this state.", + (MailNothingMatches, Tr) => "Bu durumda ileti yok.", (MailHost, En) => "Host", (MailHost, Tr) => "Sunucu", (MailIntro, En) => { @@ -319,8 +368,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (NoRunnerWithId, Tr) => "Bu kimlikte bir çalıştırıcı yok. Hiçbir şey değiştirilmedi.", (NoRunsYet, En) => "No runs yet.", (NoRunsYet, Tr) => "Henüz çalıştırma yok.", - (NothingQueued, En) => "Nothing has been queued yet.", - (NothingQueued, Tr) => "Henüz kuyruğa alınmış bir şey yok.", (Older, En) => "Older", (Older, Tr) => "Daha eski", (OwnLogIntro, En) => { @@ -333,8 +380,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (PasswordStoredHint, Tr) => { "Bir parola kayıtlı. Mevcut parolayı korumak için bu alanı boş bırakın." } - (RecentMessages, En) => "Recent messages", - (RecentMessages, Tr) => "Son iletiler", (RecentRuns, En) => "Recent runs", (RecentRuns, Tr) => "Son çalıştırmalar", (ReconcileNow, En) => "Reconcile now", @@ -617,15 +662,39 @@ pub fn running_line(lang: Lang, kind: RunKind) -> String { } } -/// The outbox status of a message: "sent", "queued" or "gave up". -pub fn outbox_status(lang: Lang, status: OutboxStatus) -> &'static str { - match (status, lang) { - (OutboxStatus::Sent, Lang::En) => "sent", - (OutboxStatus::Sent, Lang::Tr) => "gönderildi", - (OutboxStatus::Queued, Lang::En) => "queued", - (OutboxStatus::Queued, Lang::Tr) => "kuyrukta", - (OutboxStatus::GaveUp, Lang::En) => "gave up", - (OutboxStatus::GaveUp, Lang::Tr) => "vazgeçildi", +/// The queue state of a message, as the queue page labels it. +pub fn mail_state(lang: Lang, state: MailState) -> &'static str { + match (state, lang) { + (MailState::Queued, Lang::En) => "queued", + (MailState::Queued, Lang::Tr) => "kuyrukta", + (MailState::Retrying, Lang::En) => "retrying", + (MailState::Retrying, Lang::Tr) => "yeniden denenecek", + (MailState::Sending, Lang::En) => "sending", + (MailState::Sending, Lang::Tr) => "gönderiliyor", + (MailState::Sent, Lang::En) => "sent", + (MailState::Sent, Lang::Tr) => "gönderildi", + (MailState::Failed, Lang::En) => "failed", + (MailState::Failed, Lang::Tr) => "başarısız", + (MailState::Discarded, Lang::En) => "discarded", + (MailState::Discarded, Lang::Tr) => "vazgeçildi", + } +} + +/// The kind of a message, as the queue page labels it. +pub fn mail_kind(lang: Lang, kind: MailKind) -> &'static str { + match (kind, lang) { + (MailKind::Verification, Lang::En) => "verification", + (MailKind::Verification, Lang::Tr) => "doğrulama", + (MailKind::PasswordReset, Lang::En) => "password reset", + (MailKind::PasswordReset, Lang::Tr) => "şifre sıfırlama", + (MailKind::Invite, Lang::En) => "invite", + (MailKind::Invite, Lang::Tr) => "davet", + (MailKind::Notification, Lang::En) => "notification", + (MailKind::Notification, Lang::Tr) => "bildirim", + (MailKind::Test, Lang::En) => "test", + (MailKind::Test, Lang::Tr) => "test", + (MailKind::Other, Lang::En) => "other", + (MailKind::Other, Lang::Tr) => "diğer", } } @@ -710,6 +779,19 @@ mod tests { K::Mail, K::MailHost, K::MailIntro, + K::MailTabSettings, + K::MailTabQueue, + K::MailFilterAll, + K::MailRetryNow, + K::MailDiscard, + K::MailRetried, + K::MailNotFailed, + K::MailDiscarded, + K::MailSentAt, + K::MailTransportNote, + K::MailTransportInUse, + K::MailQueueIntro, + K::MailNothingMatches, K::MailPort, K::MailSettingsSaved, K::MovedToGhost, @@ -719,11 +801,9 @@ mod tests { K::NoRunnersYet, K::NoRunnerWithId, K::NoRunsYet, - K::NothingQueued, K::Older, K::OwnLogIntro, K::PasswordStoredHint, - K::RecentMessages, K::RecentRuns, K::ReconcileNow, K::ReconcileStarted, diff --git a/crates/forge-web/src/i18n/misc.rs b/crates/forge-web/src/i18n/misc.rs index 771d7f0..c3e38a7 100644 --- a/crates/forge-web/src/i18n/misc.rs +++ b/crates/forge-web/src/i18n/misc.rs @@ -27,6 +27,9 @@ pub enum K { AppearanceSaved, ChooseTheme, ChooseLanguage, + AccentLabel, + AccentHelp, + ChooseAccent, // Notifications: row kinds. KindOpenIssue, KindClosedIssue, @@ -165,6 +168,9 @@ const ALL: &[K] = &[ K::AppearanceSaved, K::ChooseTheme, K::ChooseLanguage, + K::AccentLabel, + K::AccentHelp, + K::ChooseAccent, K::KindOpenIssue, K::KindClosedIssue, K::KindOpenPull, @@ -311,6 +317,12 @@ pub fn t(lang: Lang, key: K) -> &'static str { (ChooseTheme, Tr) => "Listeden bir tema seçin.", (ChooseLanguage, En) => "Choose a language from the list.", (ChooseLanguage, Tr) => "Listeden bir dil seçin.", + (AccentLabel, En) => "Accent colour", + (AccentLabel, Tr) => "Vurgu rengi", + (AccentHelp, En) => "Used for buttons, links and the activity heatmap.", + (AccentHelp, Tr) => "Düğmeler, bağlantılar ve etkinlik ısı haritası için kullanılır.", + (ChooseAccent, En) => "Choose an accent colour from the list.", + (ChooseAccent, Tr) => "Listeden bir vurgu rengi seçin.", (KindOpenIssue, En) => "Open issue", (KindOpenIssue, Tr) => "Açık sorun", (KindClosedIssue, En) => "Closed issue", diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index 382d1f4..0ae075e 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -17,6 +17,7 @@ use topcoat::router::request::headers; use forge_core::User; +pub mod accents; pub mod admin; pub mod code; pub mod community; @@ -184,6 +185,9 @@ pub enum Key { AboutHint, Timezone, ErrChooseImage, + DisplayName, + DisplayNameHint, + ErrDisplayNameControl, // Account security. OkPasswordChanged, @@ -320,6 +324,23 @@ pub enum Key { EmailNotifyUnverified, EmailNotifyServerOff, EmailNotifySaved, + AuthenticatorApp, + PillOn, + PillOff, + PillVerified, + PillUnverified, + EmailNotVerified, + EmailNoAddress, + EmailMailQueued, + EmailMailFailed, + ChangeAction, + SetUpAction, + SetupInProgress, + DeviceName, + DeviceNameHint, + ErrDeviceName, + CodesRunningLow, + DangerZone, } /// Every key, for the exhaustiveness test. Keep it in step with the enum. @@ -385,6 +406,9 @@ pub const ALL: &[Key] = &[ Key::AboutHint, Key::Timezone, Key::ErrChooseImage, + Key::DisplayName, + Key::DisplayNameHint, + Key::ErrDisplayNameControl, Key::OkPasswordChanged, Key::OkEmailSaved, Key::OkTwoFactorOn, @@ -508,6 +532,23 @@ pub const ALL: &[Key] = &[ Key::EmailNotifyUnverified, Key::EmailNotifyServerOff, Key::EmailNotifySaved, + Key::AuthenticatorApp, + Key::PillOn, + Key::PillOff, + Key::PillVerified, + Key::PillUnverified, + Key::EmailNotVerified, + Key::EmailNoAddress, + Key::EmailMailQueued, + Key::EmailMailFailed, + Key::ChangeAction, + Key::SetUpAction, + Key::SetupInProgress, + Key::DeviceName, + Key::DeviceNameHint, + Key::ErrDeviceName, + Key::CodesRunningLow, + Key::DangerZone, ]; /// The phrase a key names, in a user's language. @@ -666,6 +707,14 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (Timezone, Tr) => "Saat dilimi", (ErrChooseImage, En) => "Choose an image to upload.", (ErrChooseImage, Tr) => "Yüklemek için bir görsel seçin.", + (DisplayName, En) => "Name", + (DisplayName, Tr) => "Ad", + (DisplayNameHint, En) => "Optional. Shown on your profile.", + (DisplayNameHint, Tr) => "İsteğe bağlı. Profilinizde gösterilir.", + (ErrDisplayNameControl, En) => { + "The name must not contain line breaks or control characters." + } + (ErrDisplayNameControl, Tr) => "Ad satır sonu ya da denetim karakteri içermemeli.", (OkPasswordChanged, En) => "Password changed. Your other sessions were signed out.", (OkPasswordChanged, Tr) => "Parola değiştirildi. Diğer oturumlarınız kapatıldı.", @@ -1006,6 +1055,44 @@ pub fn t(lang: Lang, key: Key) -> &'static str { "Bu sunucuda e-posta kapalı, bu yüzden bildirim e-postası gönderilmiyor." } (EmailNotifySaved, Tr) => "Bildirim ayarları kaydedildi.", + (AuthenticatorApp, En) => "Authenticator app", + (AuthenticatorApp, Tr) => "Kimlik doğrulama uygulaması", + (PillOn, En) => "On", + (PillOn, Tr) => "Açık", + (PillOff, En) => "Off", + (PillOff, Tr) => "Kapalı", + (PillVerified, En) => "Verified", + (PillVerified, Tr) => "Doğrulandı", + (PillUnverified, En) => "Unverified", + (PillUnverified, Tr) => "Doğrulanmadı", + (EmailNotVerified, En) => "Not verified", + (EmailNotVerified, Tr) => "Doğrulanmadı", + (EmailNoAddress, En) => "No email address", + (EmailNoAddress, Tr) => "E-posta adresi yok", + (EmailMailQueued, En) => "verification mail queued", + (EmailMailQueued, Tr) => "doğrulama iletisi kuyrukta", + (EmailMailFailed, En) => "verification mail failed", + (EmailMailFailed, Tr) => "doğrulama iletisi başarısız", + (ChangeAction, En) => "Change", + (ChangeAction, Tr) => "Değiştir", + (SetUpAction, En) => "Set up", + (SetUpAction, Tr) => "Kur", + (SetupInProgress, En) => "Setup in progress", + (SetupInProgress, Tr) => "Kurulum sürüyor", + (DeviceName, En) => "Device name (optional)", + (DeviceName, Tr) => "Cihaz adı (isteğe bağlı)", + (DeviceNameHint, En) => "Shown in your list of devices. Leave empty for the default name.", + (DeviceNameHint, Tr) => { + "Cihaz listenizde görünür. Boş bırakırsanız varsayılan ad kullanılır." + } + (ErrDeviceName, En) => { + "Use at most 40 characters for the device name, without line breaks." + } + (ErrDeviceName, Tr) => "Cihaz adı en fazla 40 karakter olabilir ve satır sonu içeremez.", + (CodesRunningLow, En) => "Running low. Generate new codes soon.", + (CodesRunningLow, Tr) => "Azaldı. Yakında yeni kodlar oluşturun.", + (DangerZone, En) => "Danger zone", + (DangerZone, Tr) => "Tehlikeli bölge", } } @@ -1146,13 +1233,68 @@ pub fn unsupported_key_type(lang: Lang, algorithm: &str) -> String { } } -/// "Two-factor authentication is on. Unused recovery codes: 7." -pub fn two_factor_on_line(lang: Lang, unused: u64) -> String { +/// "Last changed 3 days ago", with the relative time already rendered. +pub fn last_changed_line(lang: Lang, when: &str) -> String { match lang { - Lang::En => format!("Two-factor authentication is on. Unused recovery codes: {unused}."), - Lang::Tr => format!( - "İki faktörlü kimlik doğrulama açık. Kullanılmamış kurtarma kodu sayısı: {unused}." - ), + Lang::En => format!("Last changed {when}"), + Lang::Tr => format!("Son değişiklik: {when}"), + } +} + +/// The state of the latest verification mail on the Email row, such as "verification mail sent +/// 5 minutes ago". `sent_ago` is the relative time of the send, when known. +pub fn email_mail_line( + lang: Lang, + state: forge_core::mail::MailState, + attempts: u32, + sent_ago: Option<&str>, +) -> String { + use forge_core::mail::MailState; + match (state, lang) { + (MailState::Queued | MailState::Sending, _) => t(lang, Key::EmailMailQueued).to_owned(), + (MailState::Failed | MailState::Discarded, _) => t(lang, Key::EmailMailFailed).to_owned(), + (MailState::Retrying, Lang::En) => { + format!("verification mail retrying (attempt {})", attempts + 1) + } + (MailState::Retrying, Lang::Tr) => { + format!( + "doğrulama iletisi yeniden denenecek (deneme {})", + attempts + 1 + ) + } + (MailState::Sent, Lang::En) => match sent_ago { + Some(ago) => format!("verification mail sent {ago}"), + None => "verification mail sent".to_owned(), + }, + (MailState::Sent, Lang::Tr) => match sent_ago { + Some(ago) => format!("doğrulama iletisi {ago} gönderildi"), + None => "doğrulama iletisi gönderildi".to_owned(), + }, + } +} + +/// The device's "Added 2026-10-18 · Last used 5 minutes ago" line. A part without a stamp is +/// left out. +pub fn device_line(lang: Lang, added: Option<&str>, used: Option<&str>) -> String { + let (added_word, used_word) = match lang { + Lang::En => ("Added", "Last used"), + Lang::Tr => ("Eklendi", "Son kullanım"), + }; + let mut parts = Vec::new(); + if let Some(day) = added { + parts.push(format!("{added_word} {day}")); + } + if let Some(when) = used { + parts.push(format!("{used_word} {when}")); + } + parts.join(" · ") +} + +/// "7 of 10 recovery codes unused". +pub fn codes_left_line(lang: Lang, unused: u64, total: u64) -> String { + match lang { + Lang::En => format!("{unused} of {total} recovery codes unused"), + Lang::Tr => format!("{total} kurtarma kodundan {unused} tanesi kullanılmamış"), } } @@ -1164,6 +1306,14 @@ pub fn about_too_long(lang: Lang, max: usize) -> String { } } +/// The message for a display name longer than `max` characters. +pub fn display_name_too_long(lang: Lang, max: usize) -> String { + match lang { + Lang::En => format!("The name must be at most {max} characters."), + Lang::Tr => format!("Ad en fazla {max} karakter olabilir."), + } +} + /// The message for a password shorter than `min` characters. pub fn password_too_short(lang: Lang, min: usize) -> String { match lang { diff --git a/crates/forge-web/src/i18n/releases_ci.rs b/crates/forge-web/src/i18n/releases_ci.rs index fe43b17..6b3b8c1 100644 --- a/crates/forge-web/src/i18n/releases_ci.rs +++ b/crates/forge-web/src/i18n/releases_ci.rs @@ -30,14 +30,7 @@ pub enum K { Runs, NoRunsYet, NoRunsHint, - Jobs, - JobGraph, NoJobs, - ColState, - ColJob, - ColDuration, - ColRunner, - ColMessage, Newer, Older, DeletedUser, @@ -50,6 +43,9 @@ pub enum K { FullLog, LogTruncated, Artifacts, + Timeline, + Waiting, + LastLogLines, // CI status badge, on the run list. BadgeHeading, @@ -173,22 +169,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (NoRunsHint, Tr) => { ".forge/ci.toml dosyası ekleyin, ardından bir commit gönderin ya da bir çalıştırma başlatın." } - (Jobs, En) => "Jobs", - (Jobs, Tr) => "İşler", - (JobGraph, En) => "Job graph", - (JobGraph, Tr) => "İş grafiği", (NoJobs, En) => "No jobs.", (NoJobs, Tr) => "İş yok.", - (ColState, En) => "State", - (ColState, Tr) => "Durum", - (ColJob, En) => "Job", - (ColJob, Tr) => "İş", - (ColDuration, En) => "Duration", - (ColDuration, Tr) => "Süre", - (ColRunner, En) => "Runner", - (ColRunner, Tr) => "Çalıştırıcı", - (ColMessage, En) => "Message", - (ColMessage, Tr) => "Mesaj", (Newer, En) => "Newer", (Newer, Tr) => "Daha yeni", (Older, En) => "Older", @@ -215,6 +197,12 @@ pub fn t(lang: Lang, key: K) -> &'static str { } (Artifacts, En) => "Artifacts", (Artifacts, Tr) => "Yapıtlar", + (Timeline, En) => "Timeline", + (Timeline, Tr) => "Zaman çizelgesi", + (Waiting, En) => "waiting", + (Waiting, Tr) => "bekliyor", + (LastLogLines, En) => "last log lines", + (LastLogLines, Tr) => "son günlük satırları", (BadgeHeading, En) => "Status badge", (BadgeHeading, Tr) => "Durum rozeti", (BadgeHelp, En) => { @@ -378,6 +366,22 @@ pub fn page_label(lang: Lang, page: u32) -> String { } } +/// "scale: 0 — 80 min", the scale of the run list in minutes. +pub fn scale_label(lang: Lang, span: &str) -> String { + match lang { + Lang::En => format!("scale: 0 \u{2014} {span}"), + Lang::Tr => format!("ölçek: 0 \u{2014} {span}"), + } +} + +/// "needs test", for the names of the jobs a job needs. +pub fn needs_label(lang: Lang, names: &str) -> String { + match lang { + Lang::En => format!("needs {names}"), + Lang::Tr => format!("{names} gerekli"), + } +} + /// "1m 5s". pub fn duration_minutes(lang: Lang, minutes: i64, secs: i64) -> String { match lang { @@ -461,14 +465,7 @@ mod tests { K::Runs, K::NoRunsYet, K::NoRunsHint, - K::Jobs, - K::JobGraph, K::NoJobs, - K::ColState, - K::ColJob, - K::ColDuration, - K::ColRunner, - K::ColMessage, K::Newer, K::Older, K::DeletedUser, @@ -481,6 +478,9 @@ mod tests { K::FullLog, K::LogTruncated, K::Artifacts, + K::Timeline, + K::Waiting, + K::LastLogLines, K::BadgeHeading, K::BadgeHelp, K::BadgeSnippet, diff --git a/crates/forge-web/src/mail/account.rs b/crates/forge-web/src/mail/account.rs index ff43b6d..400b91a 100644 --- a/crates/forge-web/src/mail/account.rs +++ b/crates/forge-web/src/mail/account.rs @@ -3,6 +3,7 @@ //! queues nothing twice. The token itself appears only in the link. use forge_core::User; +use forge_core::mail::MailKind; use forge_core::token::hash_token; use super::{enqueue, templates}; @@ -25,6 +26,8 @@ pub async fn send_reset(state: &AppState, user: &User) -> forge_core::Result<()> enqueue( state, &format!("reset:{}", hash_token(&token)), + MailKind::PasswordReset, + Some(&user.id), address, &subject, &body, @@ -41,6 +44,8 @@ pub async fn send_verify(state: &AppState, user: &User, address: &str) -> forge_ enqueue( state, &format!("verify:{}", hash_token(&token)), + MailKind::Verification, + Some(&user.id), address, &subject, &body, @@ -62,6 +67,8 @@ pub async fn send_invite( enqueue( state, &format!("invite:{}", hash_token(&token)), + MailKind::Invite, + None, address, &subject, &body, diff --git a/crates/forge-web/src/mail/live.rs b/crates/forge-web/src/mail/live.rs new file mode 100644 index 0000000..8f7438d --- /dev/null +++ b/crates/forge-web/src/mail/live.rs @@ -0,0 +1,41 @@ +//! The change signal of the mail queue. Each change to the outbox (a message queued, a try's +//! outcome, a retry, a discard) bumps one counter, and every open queue page wakes on it through +//! its event stream. The counter carries no data: a subscriber reads the queue again when it +//! wakes. Nothing polls. The signal is process-wide, like the mail worker's waker. + +use std::sync::OnceLock; + +use tokio::sync::watch; + +static CHANGES: OnceLock> = OnceLock::new(); + +fn sender() -> &'static watch::Sender { + CHANGES.get_or_init(|| watch::channel(0).0) +} + +/// Subscribes to queue changes. Only a bump after this call wakes the receiver. +pub fn subscribe() -> watch::Receiver { + sender().subscribe() +} + +/// Counts one change of the queue. Nobody has to be listening. +pub fn bump() { + sender().send_modify(|generation| *generation = generation.wrapping_add(1)); +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[tokio::test] + async fn a_bump_wakes_a_subscriber_that_was_subscribed_before_it() { + let mut rx = subscribe(); + bump(); + tokio::time::timeout(Duration::from_secs(1), rx.changed()) + .await + .expect("woken in time") + .expect("the signal is open"); + } +} diff --git a/crates/forge-web/src/mail/mod.rs b/crates/forge-web/src/mail/mod.rs index 64f82a5..ceca17e 100644 --- a/crates/forge-web/src/mail/mod.rs +++ b/crates/forge-web/src/mail/mod.rs @@ -3,6 +3,7 @@ //! Nothing sends mail inside a request. pub mod account; +pub mod live; pub mod log; pub mod smtp; pub mod templates; @@ -11,7 +12,7 @@ pub mod worker; use std::future::Future; use std::pin::Pin; -use forge_core::mail::{MailError, OutgoingMail}; +use forge_core::mail::{MailError, MailKind, OutgoingMail}; use crate::state::AppState; @@ -27,11 +28,14 @@ pub trait Mailer: Send + Sync { fn send<'a>(&'a self, mail: &'a OutgoingMail) -> SendFuture<'a>; } -/// Queues one message, keyed by `idem_key`. Returns `false` when that key was already queued, so -/// the caller can retry without sending twice. The worker is woken to pick it up. +/// Queues one message of `kind` about the account `user_id` (if any), keyed by `idem_key`. Returns +/// `false` when that key was already queued, so the caller can retry without sending twice. The +/// worker is woken to pick it up. pub async fn enqueue( state: &AppState, idem_key: &str, + kind: MailKind, + user_id: Option<&str>, to: &str, subject: &str, body: &str, @@ -42,6 +46,8 @@ pub async fn enqueue( body: body.to_owned(), message_id: None, in_reply_to: None, + kind, + user_id: user_id.map(str::to_owned), }; enqueue_message(state, idem_key, &mail).await } @@ -55,6 +61,7 @@ pub async fn enqueue_message( let queued = state.store.enqueue_mail(idem_key, mail).await?; if queued { state.mail_waker.notify_one(); + live::bump(); } Ok(queued) } diff --git a/crates/forge-web/src/mail/smtp.rs b/crates/forge-web/src/mail/smtp.rs index 89ea557..48d9372 100644 --- a/crates/forge-web/src/mail/smtp.rs +++ b/crates/forge-web/src/mail/smtp.rs @@ -106,6 +106,7 @@ fn build_transport( #[cfg(test)] mod tests { + use forge_core::mail::MailKind; use super::*; fn settings() -> MailSettings { @@ -135,6 +136,8 @@ mod tests { body: "hello".into(), message_id: Some("".into()), in_reply_to: Some("".into()), + kind: MailKind::Notification, + user_id: None, }; let text = rendered(&mail); assert!(text.contains("Message-ID: "), "{text}"); @@ -153,6 +156,8 @@ mod tests { body: "b".into(), message_id: None, in_reply_to: None, + kind: MailKind::Other, + user_id: None, }; let text = rendered(&mail); assert!(!text.contains("In-Reply-To"), "{text}"); diff --git a/crates/forge-web/src/mail/worker.rs b/crates/forge-web/src/mail/worker.rs index f0787da..84107e9 100644 --- a/crates/forge-web/src/mail/worker.rs +++ b/crates/forge-web/src/mail/worker.rs @@ -11,6 +11,7 @@ use forge_core::time::{now_stamp, stamp_after}; use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; +use crate::mail::live; use crate::state::AppState; /// The longest the worker sleeps. It guards against a missed wake, not polling. @@ -27,7 +28,22 @@ pub fn spawn(state: AppState) { tokio::spawn(run(state)); } +/// Makes the outbox safe to resume after a restart: a row leased by a pass that died is released, +/// so it is sent on the first pass instead of after its lease runs out. A message whose send had +/// started but not finished may be sent again; that is the price of a queue that never loses mail. +pub async fn boot(state: &AppState) -> forge_core::Result { + let released = state.store.release_mail_leases().await?; + if released > 0 { + tracing::info!(released, "mail: released leases left by an earlier run"); + live::bump(); + } + Ok(released) +} + async fn run(state: AppState) { + if let Err(e) = boot(&state).await { + tracing::error!(error = %e, "mail: could not release leases at boot"); + } loop { let nap = match tick(&state).await { Ok(nap) => nap, @@ -67,6 +83,8 @@ async fn deliver(state: &AppState, entry: &OutboxEntry) { body: entry.body.clone(), message_id: entry.message_id.clone(), in_reply_to: entry.in_reply_to.clone(), + kind: entry.kind, + user_id: entry.user_id.clone(), }; let recorded = match state.mailer.send(&mail).await { Ok(()) => state.store.mark_mail_sent(&entry.id, &now_stamp()).await, @@ -91,6 +109,7 @@ async fn deliver(state: &AppState, entry: &OutboxEntry) { if let Err(e) = recorded { tracing::error!(id = %entry.id, error = %e, "mail: could not record the outcome"); } + live::bump(); } /// How long the worker sleeps: until `next_due` (an RFC 3339 stamp), clamped to @@ -107,7 +126,7 @@ pub fn sleep_for(next_due: Option<&str>, now: OffsetDateTime) -> Duration { mod tests { use std::sync::Arc; - use forge_core::mail::{MailSettingsUpdate, OutboxStatus, Security}; + use forge_core::mail::{MailKind, MailSettingsUpdate, OutboxStatus, Security}; use forge_core::time::{now_stamp, stamp_after}; use super::*; @@ -151,18 +170,41 @@ mod tests { assert_eq!(sleep_for(Some("soon"), now), BACKSTOP); } + #[tokio::test] + async fn a_row_leased_before_a_restart_is_sent_by_the_first_pass_after_boot() { + let dir = tempfile::tempdir().expect("tempdir"); + let (state, fake) = enabled_state(dir.path()).await; + enqueue(&state, "stuck", MailKind::Notification, None, "a@example.com", "Hi", "body") + .await + .expect("queued"); + // A pass that took the row and died before it finished: the lease is still set. + let held = state + .store + .lease_mail(&now_stamp(), &stamp_after(LEASE), BATCH) + .await + .expect("lease"); + assert_eq!(held.len(), 1); + assert!(fake.sent().is_empty()); + + assert_eq!(boot(&state).await.expect("boot"), 1); + tick(&state).await.expect("pass"); + assert_eq!(fake.sent().len(), 1, "the released row goes out without waiting"); + let row = state.store.recent_mail(10).await.expect("rows").remove(0); + assert_eq!(row.status(), OutboxStatus::Sent); + } + #[tokio::test] async fn a_queued_message_is_sent_once() { let dir = tempfile::tempdir().expect("tempdir"); let (state, fake) = enabled_state(dir.path()).await; assert!( - enqueue(&state, "reset:1", "a@example.com", "Hi", "body") + enqueue(&state, "reset:1", MailKind::PasswordReset, None, "a@example.com", "Hi", "body") .await .expect("queued") ); // A second enqueue with the same key is a no-op. assert!( - !enqueue(&state, "reset:1", "a@example.com", "Hi", "body") + !enqueue(&state, "reset:1", MailKind::PasswordReset, None, "a@example.com", "Hi", "body") .await .expect("again") ); @@ -195,7 +237,7 @@ mod tests { }) .await .expect("off"); - enqueue(&state, "k", "a@example.com", "Hi", "body") + enqueue(&state, "k", MailKind::Other, None, "a@example.com", "Hi", "body") .await .expect("queued"); assert_eq!(tick(&state).await.expect("pass"), BACKSTOP); @@ -209,10 +251,10 @@ mod tests { async fn a_transient_failure_is_retried_later_and_a_permanent_one_gives_up() { let dir = tempfile::tempdir().expect("tempdir"); let (state, fake) = enabled_state(dir.path()).await; - enqueue(&state, "retry", "a@example.com", "Hi", "body") + enqueue(&state, "retry", MailKind::Other, None, "a@example.com", "Hi", "body") .await .expect("queued"); - enqueue(&state, "bounce", "b@example.com", "Hi", "body") + enqueue(&state, "bounce", MailKind::Other, None, "b@example.com", "Hi", "body") .await .expect("queued"); fake.fail_next(MailError::Transient("timeout".into())); @@ -241,7 +283,7 @@ mod tests { async fn the_last_try_gives_up_and_an_earlier_one_reschedules() { let dir = tempfile::tempdir().expect("tempdir"); let (state, fake) = enabled_state(dir.path()).await; - enqueue(&state, "stubborn", "a@example.com", "Hi", "body") + enqueue(&state, "stubborn", MailKind::Other, None, "a@example.com", "Hi", "body") .await .expect("queued"); let row = state.store.recent_mail(10).await.expect("rows").remove(0); diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index c5fa7fe..a6ce3da 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -6,6 +6,9 @@ #![recursion_limit = "256"] +mod accent; +#[allow(dead_code)] // build.rs uses the whole file; the app reads only part of it. +mod accent_palette; mod access; mod admin_cli; mod admin_client; diff --git a/crates/forge-web/src/notify.rs b/crates/forge-web/src/notify.rs index 6557eb5..2809e48 100644 --- a/crates/forge-web/src/notify.rs +++ b/crates/forge-web/src/notify.rs @@ -6,7 +6,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use forge_core::mail::OutgoingMail; +use forge_core::mail::{MailKind, OutgoingMail}; use forge_core::notifications::{Reason, SubState, WatchLevel}; use forge_core::store::orgs::OrgMemberRole; use forge_core::{Action, Issue, Repo, Result, User, authorize}; @@ -533,6 +533,8 @@ async fn queue_email( body, message_id: Some(message_id), in_reply_to, + kind: MailKind::Notification, + user_id: Some(user_id.to_owned()), }; let idem_key = format!("notif:{}:{user_id}", plan.event_id); mail::enqueue_message(state, &idem_key, &outgoing).await?; diff --git a/crates/forge-web/src/pages/admin_mail.rs b/crates/forge-web/src/pages/admin_mail.rs index 42ca265..b386781 100644 --- a/crates/forge-web/src/pages/admin_mail.rs +++ b/crates/forge-web/src/pages/admin_mail.rs @@ -1,17 +1,24 @@ //! Page: outgoing mail (`/admin/mail`). Instance admins only; anyone else gets 404. //! -//! The form stores the SMTP server, sender and password (the password is write-only: a blank field -//! keeps the stored one). "Send test mail" queues one message to the admin's own address. The -//! list shows the newest 50 outbox rows with their status and last error, never the body. +//! Two tabs. Settings: the SMTP server, sender and password (the password is write-only: a blank +//! field keeps the stored one) and "Send test mail" to the admin's own address. Queue: every +//! message in the outbox with its state, kind, tries and last error, filtered by state. A failed +//! message can be retried or discarded there. The queue's wrapper carries `data-live`, so each +//! queue change re-renders it through `/admin/mail/events` with no reload and no polling. //! Saving the settings and queuing a test are audited. -use forge_core::mail::{MailSettings, MailSettingsUpdate, OutboxEntry, Security}; +use forge_core::config::MailTransport; +use forge_core::mail::{MailKind, MailSettings, MailSettingsUpdate, MailState, OutboxEntry, Security}; +use forge_core::time::now_stamp; use forge_core::tz::format_in_tz; use forge_core::{AuditAction, Error}; +use futures_util::{Stream, stream}; use serde::Deserialize; +use tokio::sync::watch; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; +use topcoat::router::content::sse::Event; use topcoat::router::error::{forbidden, see_other}; use topcoat::router::response::Response; use topcoat::router::{page, query_params, route}; @@ -21,28 +28,58 @@ use crate::audit::{self, Actor, Target}; use crate::auth::check_csrf; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; -use crate::mail::{enqueue, templates}; +use crate::mail::{enqueue, live, templates}; use crate::pages::admin_users::admin_only; +use crate::pages::ci_runs::{changed_event, events_response}; use crate::pages::issues_list::stamp_unix; use crate::state::AppState; use crate::views::{enc, shell}; -/// Rows shown in the outbox list. -const LIST_LIMIT: u32 = 50; +/// Rows shown in the queue at most. +const LIST_LIMIT: u32 = 100; #[query_params(error = bad_request)] pub(crate) struct NoticeQuery { notice: Option, + tab: Option, + state: Option, } -/// One outbox row, already formatted. There is no body field on purpose. -struct MailRow { +/// The two tabs of the page. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Tab { + Settings, + Queue, +} + +/// One queue row, already formatted. There is no body field on purpose. +struct QueueRow { + id: String, to: String, subject: String, - status: &'static str, + kind: &'static str, + state: &'static str, + state_class: &'static str, attempts: u32, error: String, created: String, + sent: String, + failed: bool, +} + +/// One state filter: the link, its label and how many rows it covers. +struct FilterChip { + href: String, + label: &'static str, + count: u32, + class: &'static str, +} + +/// The queue tab: the filter chips, the rows and the state the filter is on, for the forms. +struct QueueData { + chips: Vec, + rows: Vec, + filter_param: String, } /// Everything the page shows. The password is never in here. @@ -55,29 +92,105 @@ struct PageData { from_name: String, enabled: bool, has_password: bool, - rows: Vec, + transport: &'static str, + tab: Tab, + queue: Option, +} + +/// The CSS class of a state pill. The pills reuse the CI state colours. +fn state_class(state: MailState) -> &'static str { + match state { + MailState::Sent => "ci-state ci-success", + MailState::Sending => "ci-state ci-running", + MailState::Queued => "ci-state ci-queued", + MailState::Retrying => "ci-state ci-blocked", + MailState::Failed => "ci-state ci-failure", + MailState::Discarded => "ci-state ci-skipped", + } } -fn row_view(entry: &OutboxEntry, tz: &str, lang: Lang) -> MailRow { - MailRow { +fn transport_name(transport: MailTransport) -> &'static str { + match transport { + MailTransport::Smtp => "smtp", + MailTransport::Log => "log", + } +} + +fn tab_class(on: bool) -> &'static str { + if on { "subnav-link current" } else { "subnav-link" } +} + +fn row_view(entry: &OutboxEntry, now: &str, tz: &str, lang: Lang) -> QueueRow { + let state = entry.state_at(now); + QueueRow { + id: entry.id.clone(), to: entry.to_addr.clone(), subject: entry.subject.clone(), - status: g::outbox_status(lang, entry.status()), + kind: g::mail_kind(lang, entry.kind), + state: g::mail_state(lang, state), + state_class: state_class(state), attempts: entry.attempts, error: entry.last_error.clone().unwrap_or_default(), created: format_in_tz(stamp_unix(&entry.created_at), tz), + sent: entry + .sent_at + .as_deref() + .map(|sent| format_in_tz(stamp_unix(sent), tz)) + .unwrap_or_default(), + failed: state == MailState::Failed, } } -async fn page_data(state: &AppState, tz: &str, lang: Lang) -> forge_core::Result { - let settings: MailSettings = state.store.mail_settings().await?; +/// The queue tab's data. `filter` of `None` lists every state. +async fn queue_data( + state: &AppState, + tz: &str, + lang: Lang, + filter: Option, +) -> forge_core::Result { + let now = now_stamp(); + let counts = state.store.mail_state_counts(&now).await?; + let total: u32 = counts.iter().map(|(_, n)| *n).sum(); + let mut chips = vec![FilterChip { + href: "/admin/mail?tab=queue".to_owned(), + label: g::t(lang, K::MailFilterAll), + count: total, + class: tab_class(filter.is_none()), + }]; + for (kind, count) in counts { + chips.push(FilterChip { + href: format!("/admin/mail?tab=queue&state={}", kind.as_str()), + label: g::mail_state(lang, kind), + count, + class: tab_class(filter == Some(kind)), + }); + } let rows = state .store - .recent_mail(LIST_LIMIT) + .list_mail(filter, &now, LIST_LIMIT) .await? .iter() - .map(|entry| row_view(entry, tz, lang)) + .map(|entry| row_view(entry, &now, tz, lang)) .collect(); + Ok(QueueData { + chips, + rows, + filter_param: filter.map_or_else(String::new, |s| s.as_str().to_owned()), + }) +} + +async fn page_data( + state: &AppState, + tz: &str, + lang: Lang, + tab: Tab, + filter: Option, +) -> forge_core::Result { + let settings: MailSettings = state.store.mail_settings().await?; + let queue = match tab { + Tab::Queue => Some(queue_data(state, tz, lang, filter).await?), + Tab::Settings => None, + }; Ok(PageData { host: settings.host, port: settings.port.to_string(), @@ -87,7 +200,9 @@ async fn page_data(state: &AppState, tz: &str, lang: Lang) -> forge_core::Result from_name: settings.from_name, enabled: settings.enabled, has_password: settings.has_password, - rows, + transport: transport_name(state.config.mail.transport), + tab, + queue, }) } @@ -106,79 +221,120 @@ async fn mail_view( } else { g::t(lang, K::NoPasswordStored) }; + let settings_on = data.tab == Tab::Settings; + let settings_class = tab_class(settings_on); + let queue_class = tab_class(!settings_on); + let filter_param = data.queue.as_ref().map(|q| q.filter_param.clone()).unwrap_or_default(); Ok(view! {

(g::t(lang, K::Mail))

(g::t(lang, K::MailIntro))

+ if let Some(message) = notice {

(message.as_str())

} -
-

(g::t(lang, K::SmtpServer))

-
- - - - - - -

(password_hint)

- - - -
- -
-
-
- -
- + if settings_on { +
+

(g::t(lang, K::SmtpServer))

+

(g::t(lang, K::MailTransportNote))

+

(g::t(lang, K::MailTransportInUse)) " " (data.transport)

+ + + + + + + +

(password_hint)

+ + + +
+ +
+ +
+ +
+ +
+
+
+ } else if let Some(queue) = data.queue { +
+

(g::t(lang, K::MailQueueIntro))

+
+ for chip in queue.chips.into_iter() { + (chip.label) " " (chip.count) + }
- -
-
-

(g::t(lang, K::RecentMessages))

- if data.rows.is_empty() { -

(g::t(lang, K::NothingQueued))

- } else { -
- - - - - - - - - - - - - for row in data.rows.into_iter() { - - - - - - - - - } - -
(g::t(lang, K::TableQueued))(g::t(lang, K::TableTo))(g::t(lang, K::TableSubject))(g::t(lang, K::TableStatus))(g::t(lang, K::TableTries))(g::t(lang, K::TableLastError))
(row.created.as_str())(row.to.as_str())(row.subject.as_str())(row.status)(row.attempts)(row.error.as_str())
+
+ if queue.rows.is_empty() { +

(g::t(lang, K::MailNothingMatches))

+ } else { +
+ + + + + + + + + + + + + + + + for row in queue.rows.into_iter() { + + + + + + + + + + + + } + +
(g::t(lang, K::TableQueued))(g::t(lang, K::TableTo))(g::t(lang, K::TableKind))(g::t(lang, K::TableSubject))(g::t(lang, K::TableState))(g::t(lang, K::TableTries))(g::t(lang, K::MailSentAt))(g::t(lang, K::TableLastError))
(row.created.as_str())(row.to.as_str())(row.kind)(row.subject.as_str())(row.state)(row.attempts)(row.sent.as_str())(row.error.as_str()) + if row.failed { +
+ + + + +
+
+ + + + +
+ } +
+
+ }
- } -
+
+ } }) } @@ -188,7 +344,13 @@ async fn mail_page(cx: &Cx) -> Result { let query = query_params::(cx)?; let state = app_context::(cx); let lang = i18n::lang(cx, Some(&viewer.0)); - let data = page_data(state, viewer.0.timezone.as_str(), lang).await?; + let tab = if query.tab.as_deref() == Some("queue") { + Tab::Queue + } else { + Tab::Settings + }; + let filter = query.state.as_deref().and_then(MailState::parse); + let data = page_data(state, viewer.0.timezone.as_str(), lang, tab, filter).await?; let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::Mail); Ok(view! { @@ -196,6 +358,24 @@ async fn mail_page(cx: &Cx) -> Result { }) } +/// The live `changed` stream of the queue. One event per queue change. Nothing is sent on connect: +/// the page was just rendered. +fn queue_changes(wake: watch::Receiver) -> impl Stream> + Send + 'static { + stream::unfold(wake, |mut wake| async move { + wake.changed().await.ok()?; + Some((changed_event("queue".to_owned()), wake)) + }) +} + +/// The queue's change stream. Admins only. +#[route(GET "/admin/mail/events")] +async fn mail_events(cx: &Cx) -> Result { + admin_only(cx).await?; + // Subscribed before the response is sent, so a change after this point is sent. + let wake = live::subscribe(); + events_response(cx, queue_changes(wake)) +} + #[derive(Deserialize, Default)] struct SettingsForm { #[serde(default)] @@ -283,6 +463,7 @@ async fn save_settings( ) .await; state.mail_waker.notify_one(); + live::bump(); Ok(()) } @@ -327,7 +508,16 @@ async fn queue_test( }; let (subject, body) = templates::test_mail(); let key = format!("test:{}", ulid::Ulid::generate()); - enqueue(state, &key, address, &subject, &body).await?; + enqueue( + state, + &key, + MailKind::Test, + Some(&user.id), + address, + &subject, + &body, + ) + .await?; audit::record( &state.store, Some(cx), @@ -344,6 +534,70 @@ async fn queue_test( Ok(()) } +#[derive(Clone, Copy)] +enum QueueAction { + Retry, + Discard, +} + +#[derive(Deserialize, Default)] +struct QueueForm { + #[serde(default)] + csrf: String, + #[serde(default)] + id: String, + /// The filter the admin was on, so the redirect lands back on it. + #[serde(default)] + state: String, +} + +#[route(POST "/admin/mail/queue/retry")] +async fn queue_retry(cx: &Cx, Form(form): Form) -> Result { + queue_action(cx, form, QueueAction::Retry).await +} + +#[route(POST "/admin/mail/queue/discard")] +async fn queue_discard(cx: &Cx, Form(form): Form) -> Result { + queue_action(cx, form, QueueAction::Discard).await +} + +/// Retries or discards one failed message. Anything else is refused with a notice and changes +/// nothing. Either way the worker is woken and the queue's watchers are told. +async fn queue_action(cx: &Cx, form: QueueForm, action: QueueAction) -> Result { + let viewer = admin_only(cx).await?; + if !check_csrf(&viewer.1, &form.csrf) { + return Err(forbidden().into()); + } + let lang = i18n::lang(cx, Some(&viewer.0)); + let state = app_context::(cx); + let now = now_stamp(); + let (done, notice) = match action { + QueueAction::Retry => { + let done = state.store.retry_mail(&form.id, &now).await?; + if done { + state.mail_waker.notify_one(); + } + (done, K::MailRetried) + } + QueueAction::Discard => ( + state.store.discard_mail(&form.id, &now).await?, + K::MailDiscarded, + ), + }; + let notice = if done { notice } else { K::MailNotFailed }; + if done { + live::bump(); + } + let filter = MailState::parse(&form.state).map_or_else(String::new, |s| { + format!("&state={}", s.as_str()) + }); + let location = format!( + "/admin/mail?tab=queue{filter}¬ice={}", + enc(g::t(lang, notice)) + ); + Err(see_other(&location).into()) +} + #[cfg(test)] mod tests { use super::*; @@ -585,4 +839,178 @@ mod tests { assert!(body.contains("Bağlantı noktası"), "Turkish port label"); assert!(!body.contains("SMTP server"), "no English heading left"); } + + fn outgoing(to: &str, subject: &str, body: &str, kind: MailKind) -> forge_core::mail::OutgoingMail { + forge_core::mail::OutgoingMail { + to: to.into(), + subject: subject.into(), + body: body.into(), + message_id: None, + in_reply_to: None, + kind, + user_id: None, + } + } + + #[tokio::test] + async fn the_queue_tab_is_live_filters_by_state_and_never_renders_a_body() { + let fx = fixture().await; + let reset = outgoing( + "a@example.com", + "Reset your password", + "https://forge.test/reset/SECRET-LINK", + MailKind::PasswordReset, + ); + fx.state.store.enqueue_mail("reset:1", &reset).await.expect("queued"); + let later = outgoing("b@example.com", "Queued one", "body", MailKind::Notification); + fx.state.store.enqueue_mail("notif:2", &later).await.expect("queued"); + let failed_id = fx + .state + .store + .recent_mail(10) + .await + .expect("rows") + .into_iter() + .find(|r| r.to_addr == "a@example.com") + .expect("reset row") + .id; + fx.state + .store + .mark_mail_failed(&failed_id, "550 no such user", None) + .await + .expect("failed"); + + let (status, body) = send(&fx.router, "GET", "/admin/mail?tab=queue", Some(ADMIN_TOKEN), None).await; + assert_eq!(status, 200); + assert!(body.contains("data-live=\"/admin/mail/events\""), "the queue is live"); + assert!(body.contains("Reset your password") && body.contains("Queued one")); + assert!(body.contains("550 no such user"), "the last error shows"); + assert!(!body.contains("SECRET-LINK"), "a body is never rendered"); + assert!(body.contains("Retry now") && body.contains("/admin/mail/queue/retry")); + + let (_, failed_only) = send(&fx.router, "GET", "/admin/mail?tab=queue&state=failed", Some(ADMIN_TOKEN), None).await; + assert!(failed_only.contains("Reset your password")); + assert!(!failed_only.contains("Queued one"), "the filter hides queued mail"); + + let (_, settings) = send(&fx.router, "GET", "/admin/mail", Some(ADMIN_TOKEN), None).await; + assert!(!settings.contains("data-live="), "only the queue is live"); + assert!(!settings.contains("Reset your password"), "the queue is on its own tab"); + } + + #[tokio::test] + async fn the_queue_events_and_its_actions_are_admin_only() { + let fx = fixture().await; + for (method, uri) in [ + ("GET", "/admin/mail/events"), + ("POST", "/admin/mail/queue/retry"), + ("POST", "/admin/mail/queue/discard"), + ] { + let (anon, _) = send(&fx.router, method, uri, None, Some(format!("csrf={CSRF}&id=x"))).await; + assert_eq!(anon, 404, "{method} {uri} for anonymous"); + let (user, _) = send(&fx.router, method, uri, Some(USER_TOKEN), Some(format!("csrf={CSRF}&id=x"))).await; + assert_eq!(user, 404, "{method} {uri} for a plain user"); + } + } + + #[tokio::test] + async fn an_admin_gets_the_queue_event_stream() { + let fx = fixture().await; + let request = Request::builder() + .method("GET") + .uri("/admin/mail/events") + .header("cookie", format!("__Host-{SESSION_COOKIE}={ADMIN_TOKEN}")) + .body(Body::empty()) + .expect("request"); + let res = fx.router.handle(request).await; + assert_eq!(res.status().as_u16(), 200); + let kind = res + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .to_owned(); + assert!(kind.starts_with("text/event-stream"), "{kind}"); + } + + #[tokio::test] + async fn an_admin_retries_and_discards_failed_mail_and_nothing_else() { + let fx = fixture().await; + for key in ["k1", "k2"] { + let mail = outgoing("a@example.com", "Hi", "b", MailKind::Notification); + fx.state.store.enqueue_mail(key, &mail).await.expect("queued"); + } + let ids: Vec = fx + .state + .store + .recent_mail(10) + .await + .expect("rows") + .into_iter() + .map(|r| r.id) + .collect(); + for id in &ids { + fx.state.store.mark_mail_failed(id, "550", None).await.expect("failed"); + } + + let (status, _) = send( + &fx.router, + "POST", + "/admin/mail/queue/retry", + Some(ADMIN_TOKEN), + Some(format!("csrf={CSRF}&id={}&state=failed", ids[0])), + ) + .await; + assert_eq!(status, 303); + let now = now_stamp(); + let queued = fx + .state + .store + .list_mail(Some(MailState::Queued), &now, 10) + .await + .expect("queued"); + assert_eq!(queued.len(), 1); + assert_eq!(queued[0].id, ids[0]); + + let (status, _) = send( + &fx.router, + "POST", + "/admin/mail/queue/discard", + Some(ADMIN_TOKEN), + Some(format!("csrf={CSRF}&id={}", ids[1])), + ) + .await; + assert_eq!(status, 303); + let discarded = fx + .state + .store + .list_mail(Some(MailState::Discarded), &now, 10) + .await + .expect("discarded"); + assert_eq!(discarded.len(), 1); + assert_eq!(discarded[0].id, ids[1]); + + // A queued message cannot be retried, and a bad token changes nothing. + let (status, _) = send( + &fx.router, + "POST", + "/admin/mail/queue/retry", + Some(ADMIN_TOKEN), + Some(format!("csrf={CSRF}&id={}", ids[0])), + ) + .await; + assert_eq!(status, 303, "refused with a notice, not an error"); + assert_eq!( + fx.state.store.list_mail(Some(MailState::Queued), &now, 10).await.expect("queued").len(), + 1 + ); + let (status, _) = send( + &fx.router, + "POST", + "/admin/mail/queue/discard", + Some(ADMIN_TOKEN), + Some(format!("csrf=wrong&id={}", ids[0])), + ) + .await; + assert_eq!(status, 403); + } } diff --git a/crates/forge-web/src/pages/ci_badge.rs b/crates/forge-web/src/pages/ci_badge.rs index f19d21f..4a1bd1d 100644 --- a/crates/forge-web/src/pages/ci_badge.rs +++ b/crates/forge-web/src/pages/ci_badge.rs @@ -3,7 +3,7 @@ //! SVG is a flat shields-style image, rendered here with no outside assets. //! //! The label, the left half, is `?label=` if given, else the job name when `&job=` is given, else -//! the `name` of the run's `.forge/ci.toml`, else "ci". +//! the `name` of the run's `.forge/ci.toml`, else "build". //! //! Access is the repo's read access: a private repo a viewer cannot read is a 404, like every other //! repo page. A repo with no run on the branch still answers 200 with "no status". @@ -26,7 +26,7 @@ path_param!(repo); /// Longest label shown, in characters. A longer job name is cut here. const MAX_LABEL_CHARS: usize = 64; /// The label when neither `?label=`, a job, nor a workflow name gives one. -const DEFAULT_LABEL: &str = "ci"; +const DEFAULT_LABEL: &str = "build"; /// Height of the badge in pixels. const HEIGHT: u32 = 20; /// Padding on each side of a text, in pixels. @@ -297,7 +297,7 @@ mod tests { (BadgeStatus::NoStatus, "#9f9f9f", "no status"), ]; for (status, color, word) in cases { - let svg = render_badge("ci", status); + let svg = render_badge("build", status); assert!(svg.contains(&format!("fill=\"{color}\"")), "{word}"); assert!(svg.contains(&format!(">{word}")), "{word}"); assert!(svg.contains("fill=\"#555\"")); @@ -324,10 +324,10 @@ mod tests { #[test] fn width_grows_with_text() { assert!(text_box("no status") > text_box("ok")); - let svg = render_badge("ci", BadgeStatus::Passing); + let svg = render_badge("build", BadgeStatus::Passing); assert!(svg.contains(&format!( "width=\"{}\"", - text_box("ci") + text_box("passing") + text_box("build") + text_box("passing") ))); } } diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index 5fc0e87..9d9c0fd 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -1,23 +1,26 @@ -//! Pages: CI runs (`/{owner}/{repo}/ci` and `/{owner}/{repo}/ci/runs/{number}`). Anyone who can read -//! the repo sees its runs, their jobs and the config error of a run. Starting a manual run, cancelling, -//! re-running and approving need Write, and the buttons are shown only to writers. Anyone else gets a -//! 404 for a private repo and a refusal for a change. Every change notifies the job waker and syncs -//! the commit status of each job it changed. A run or job page that is not finished stays live: it -//! opens a `changed` event stream (`.../events`) and re-renders itself on each event, with no reload -//! and no timer. The run list stays live on page 1 the same way, through `/{owner}/{repo}/ci/events`, -//! which fires on every run created or changed in the repo. +//! Pages: CI runs (`/{owner}/{repo}/ci` and `/{owner}/{repo}/ci/runs/{number}`). Both render one split +//! view: the repo's runs on the left, the selected run on the right with its to-scale timeline, its jobs +//! and the last lines of its log. Anyone who can read the repo sees its runs, their jobs and the config +//! error of a run. Starting a manual run, cancelling, re-running and approving need Write, and the +//! buttons are shown only to writers. Anyone else gets a 404 for a private repo and a refusal for a +//! change. Every change notifies the job waker and syncs the commit status of each job it changed. A run +//! or job page that is not finished stays live. The split view is live on page 1 of the list through +//! `/{owner}/{repo}/ci/events`, which fires on every run created or changed in the repo, and a run or job +//! page opens its own `changed` stream (`.../events`) when it is not finished. use std::collections::HashMap; use std::future::Future; +use std::path::Path; use std::time::Duration; -use forge_core::ci::{CiJob, CiRun, RunState}; +use forge_core::ci::{CiJob, CiRun, JobState, RunState}; use forge_core::{Action, Denied, Store, User, authorize}; use forge_git::browse::{RefInfo, RefKind, read_commit}; use futures_util::{Stream, stream}; use serde::Deserialize; use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; +use tokio::io::{AsyncReadExt, AsyncSeekExt, SeekFrom}; use tokio::sync::watch; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -30,6 +33,7 @@ use topcoat::router::{HeaderValue, page, path_param, route}; use topcoat::view::{View, component, view}; use crate::auth::{current_user, require_csrf}; +use crate::ci::log_path; use crate::i18n::{ self, Lang, releases_ci::{self as g, K}, @@ -38,7 +42,7 @@ use crate::pages::refs::load_refs; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; use crate::state::AppState; -use crate::views::{alert, enc, now_unix, relative_time, shell, short_oid}; +use crate::views::{alert, enc, human_size, now_unix, relative_time, shell, short_oid}; path_param!(owner); path_param!(repo); @@ -130,7 +134,7 @@ pub fn job_href(title: &str, job_id: &str) -> String { fn badge_info(state: &AppState, title: &str, default_branch: &str) -> BadgeInfo { let base = state.config.base_url.trim_end_matches('/'); let image = format!("/{}/badge.svg?branch={}", enc(title), enc(default_branch)); - let snippet = format!("[![CI]({base}{image})]({base}{})", ci_href(&enc(title))); + let snippet = format!("[![build]({base}{image})]({base}{})", ci_href(&enc(title))); BadgeInfo { image, snippet } } @@ -279,21 +283,14 @@ async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> Resul Ok(()) } -/// One run in the list, with its values already shown as text. `state_key` is the raw state word -/// that picks the row's icon. +/// One run in the list. `bar` is its duration bar on the page's shared scale. struct RunRow { href: String, - number: i64, + current: &'static str, title: String, - state: String, - state_key: String, - trigger: String, - branch: String, - commit_href: String, - commit: String, - actor: String, + bar: Vec, duration: String, - when: String, + meta: String, } /// The run-list form that starts a manual run. @@ -309,58 +306,552 @@ struct BadgeInfo { snippet: String, } -/// A job row on the run page. -struct JobRow { - href: String, - name: String, - state: String, - state_class: String, - duration: String, - runner: String, - message: String, +/// The left column: the header menus, the scale, the rows and the pager. +struct ListView { + manual: Option, + badge: BadgeInfo, + total: u64, + scale: String, + rows: Vec, + newer_href: Option, + older_href: Option, + page_label: String, } -/// Layout of the job graph in SVG units. The `.ci-graph-*` rules in main.scss use the same sizes. -const GRAPH_PAD: i64 = 16; -const GRAPH_CARD_W: i64 = 200; -const GRAPH_CARD_H: i64 = 56; -const GRAPH_COL_GAP: i64 = 48; -const GRAPH_ROW_GAP: i64 = 16; - -/// One job card of the graph. `class` is the card's class with its status word. -struct GraphCard { - class: String, +/// One job line under the timeline. Its link goes to the job page. +struct JobLine { href: String, name: String, - state: String, + dot: String, + /// The image and the artifacts with their sizes, joined with a middle dot. + detail: String, + runner: String, duration: String, } -/// The job graph of a run: the cards by stage column, and the connector paths between them. -struct JobGraph { - width: String, - height: String, - columns: Vec>, - paths: Vec, +/// The last lines of the log of the job the run page points at. +struct LogBlock { + caption: String, + text: String, } -/// The run page's header values. -struct RunView { +/// The right column: the selected run, its timeline, its jobs and the log tail. +struct RunDetail { number: i64, title: String, - commit_href: String, - duration: String, state: String, state_class: String, trigger: String, - git_ref: String, + branch: String, + commit_href: String, commit: String, actor: String, when: String, + duration: String, config_error: Option, action_base: String, can_approve: bool, can_cancel: bool, + writer_csrf: Option, + gantt: Option, + jobs: Vec, + log: Option, +} + +/// A box in an SVG, with its class and its position and size in the SVG's units. +struct Rect { + class: String, + x: String, + y: String, + w: String, + h: String, +} + +impl Rect { + fn new(class: impl Into, x: i64, y: i64, w: i64, h: i64) -> Rect { + Rect { + class: class.into(), + x: x.to_string(), + y: y.to_string(), + w: w.to_string(), + h: h.to_string(), + } + } +} + +/// A text label of the timeline. +struct Label { + class: &'static str, + x: String, + y: String, + anchor: &'static str, + text: String, +} + +/// The timeline of a run: its SVG viewBox, its boxes, its connectors and its labels, in draw order. +struct Gantt { + view_box: String, + rects: Vec, + links: Vec, + labels: Vec