diff --git a/Cargo.lock b/Cargo.lock index cae0023..985e9a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1803,8 +1803,10 @@ version = "0.1.0" dependencies = [ "async-trait", "calamine", + "futures-util", "grass", "http", + "http-body-util", "izlek-core", "lettre", "serde", diff --git a/crates/izlek-core/migrations/0002_sender_check.sql b/crates/izlek-core/migrations/0002_sender_check.sql new file mode 100644 index 0000000..5f7008d --- /dev/null +++ b/crates/izlek-core/migrations/0002_sender_check.sql @@ -0,0 +1,15 @@ +-- Whether the mail server let us in, which is a different fact from whether a +-- mail was delivered. +-- +-- `smtp_test_*` records a real message going out to a real inbox. This records +-- a handshake: connect, negotiate TLS, say hello, authenticate, hang up. It +-- proves the host, the port, the encryption and the credentials, and it proves +-- nothing about whether the from-address is one this account may send as — a +-- server that accepts the login can still refuse the envelope. Kept apart so +-- neither can be read as the other. +-- +-- Cleared whenever the sender is edited, for the same reason the test result +-- is: it was about settings that no longer exist. +ALTER TABLE workspace ADD COLUMN smtp_check_at TEXT; +ALTER TABLE workspace ADD COLUMN smtp_check_ms INTEGER; +ALTER TABLE workspace ADD COLUMN smtp_check_error TEXT; diff --git a/crates/izlek-core/src/config.rs b/crates/izlek-core/src/config.rs index 914c0ba..3807d70 100644 --- a/crates/izlek-core/src/config.rs +++ b/crates/izlek-core/src/config.rs @@ -51,6 +51,10 @@ database = "izlek.db" # this is the only thing that decides where İzlek binds. It is also the # address mail links fall back to, until an admin sets one in Settings. listen = "127.0.0.1:7654" +# How long a live-update connection is held before the browser is asked to +# reconnect, in seconds. The reconnect is what re-checks the session, so a +# revoked sign-in stops receiving within this long. +live_seconds = 300 "#; /// The default `listen` when the file is silent about it. A file missing this @@ -63,18 +67,38 @@ listen = "127.0.0.1:7654" /// range, so the kernel never hands it to an outgoing connection either. const DEFAULT_LISTEN: &str = "127.0.0.1:7654"; +/// How long one live-update connection lasts before the server ends it and the +/// browser opens another. Five minutes is a compromise: a stream is +/// authenticated once, when it opens, so a session revoked mid-stream keeps +/// hearing until the next reconnect — and a reconnect costs one request, so +/// doing it every few seconds to shorten that window would be worse than the +/// window. Long enough to be cheap, short enough that a revoked session goes +/// quiet while the person who revoked it is still watching. +const DEFAULT_LIVE_SECONDS: u64 = 300; + /// Every optional key, with the comment and default a file missing it is /// completed with. `database` is not here: it has no default worth guessing, /// so its absence stops the boot instead. -const OPTIONAL_KEYS: &[(&str, &str)] = &[( - "listen", - concat!( - "# The address the server listens on. Environment variables are ignored —\n", - "# this is the only thing that decides where İzlek binds. It is also the\n", - "# address mail links fall back to, until an admin sets one in Settings.\n", - "listen = \"127.0.0.1:7654\"\n" +const OPTIONAL_KEYS: &[(&str, &str)] = &[ + ( + "listen", + concat!( + "# The address the server listens on. Environment variables are ignored —\n", + "# this is the only thing that decides where İzlek binds. It is also the\n", + "# address mail links fall back to, until an admin sets one in Settings.\n", + "listen = \"127.0.0.1:7654\"\n" + ), ), -)]; + ( + "live_seconds", + concat!( + "# How long a live-update connection is held before the browser is asked to\n", + "# reconnect, in seconds. The reconnect is what re-checks the session, so a\n", + "# revoked sign-in stops receiving within this long.\n", + "live_seconds = 300\n" + ), + ), +]; /// The shape of `config/izlek.toml`, before the values are checked. Anything /// else the file says lands in `other`, which is read for its key names only @@ -83,6 +107,7 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[( struct Toml { database: Option, listen: Option, + live_seconds: Option, #[serde(flatten)] other: std::collections::BTreeMap, } @@ -98,6 +123,10 @@ pub struct Config { /// Keys the file sets that nothing here reads, in the order the file /// gives them. Named at startup so a typo is visible. pub ignored: Vec, + /// How long one live-update connection is held open before the browser is + /// asked to reconnect. The reconnect re-authenticates, which is how a + /// session revoked mid-stream stops being fed. + pub live_seconds: u64, /// Whether `config/izlek.toml` did not exist and was just written with the /// development defaults this boot. pub defaulted: bool, @@ -197,9 +226,22 @@ impl Config { why: format!("{listen:?} is not a host:port address — {err}"), })?; + // Zero would mean a stream that ends the moment it opens, which is a + // reconnect loop rather than a live feed; the key is refused rather + // than quietly corrected, because a deployment that meant to say + // "never expire" should find out here and not at three in the morning. + let live_seconds = toml.live_seconds.unwrap_or(DEFAULT_LIVE_SECONDS); + if live_seconds == 0 { + return Err(ConfigError::Invalid { + key: "live_seconds", + why: "0 would close every live connection as soon as it opened".to_string(), + }); + } + Ok(Config { database: absolute(dir, Path::new(&database)), listen, + live_seconds, ignored: toml.other.into_keys().collect(), defaulted, }) @@ -393,14 +435,40 @@ mod tests { fn completion_leaves_a_key_that_is_already_there() { let dir = scratch(); std::fs::create_dir_all(dir.join("config")).unwrap(); - let mine = "database = \"izlek.db\"\nlisten = \"0.0.0.0:8080\"\n"; + let mine = + "database = \"izlek.db\"\nlisten = \"0.0.0.0:8080\"\nlive_seconds = 30\n"; std::fs::write(dir.join(FILE_NAME), mine).unwrap(); let config = Config::load_from(&dir).unwrap(); assert_eq!(config.listen, "0.0.0.0:8080".parse().unwrap()); + assert_eq!(config.live_seconds, 30); assert_eq!(std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(), mine); let _ = std::fs::remove_dir_all(&dir); } + /// A live connection that expires instantly is a reconnect loop, so the + /// key is refused rather than silently corrected. + #[test] + fn a_zero_live_window_stops_the_boot_naming_the_key() { + let problem = Config::parse( + "database = \"izlek.db\"\nlive_seconds = 0\n", + Path::new("."), + false, + ) + .unwrap_err(); + assert!( + matches!(problem, ConfigError::Invalid { key: "live_seconds", .. }), + "{problem:?}" + ); + } + + /// A file that never mentions the key still boots, on the default. + #[test] + fn a_file_without_a_live_window_takes_the_default() { + let config = + Config::parse("database = \"izlek.db\"\n", Path::new("."), false).unwrap(); + assert_eq!(config.live_seconds, 300); + } + #[test] fn an_empty_string_is_not_a_value() { let problem = Config::parse("database = \" \"\n", Path::new("."), false).unwrap_err(); diff --git a/crates/izlek-core/src/detail.rs b/crates/izlek-core/src/detail.rs index 02b1dd6..d8c159e 100644 --- a/crates/izlek-core/src/detail.rs +++ b/crates/izlek-core/src/detail.rs @@ -365,6 +365,25 @@ pub fn moment_label_in(at: OffsetDateTime, offset: UtcOffset) -> String { ) } +/// The same label, down to the second. +/// +/// Minutes are the right grain for something that already happened — a comment +/// was left at 16:42 and nobody cares which second. They are the wrong grain +/// for a moment that has not arrived yet: a retry shown as "16:42" that fires +/// at 16:42:47 looks forty-seven seconds broken to whoever is watching the +/// clock, and a promise about the future has to be readable against the future +/// it promises. +pub fn moment_label_with_seconds_in(at: OffsetDateTime, offset: UtcOffset) -> String { + let at = at.to_offset(offset); + format!( + "{} {:02}:{:02}:{:02}", + day_label(at.date()), + at.hour(), + at.minute(), + at.second() + ) +} + /// Parses a stored `User::timezone` value — `"UTC"` or `"UTC+03:00"` / /// `"UTC-05:00"` — into the offset it names. There is no tz-database here /// (see the settings vocabulary decision), only fixed offsets, so anything diff --git a/crates/izlek-core/src/lib.rs b/crates/izlek-core/src/lib.rs index c6d165c..0c6c923 100644 --- a/crates/izlek-core/src/lib.rs +++ b/crates/izlek-core/src/lib.rs @@ -17,6 +17,8 @@ pub mod accounts; #[cfg(feature = "server")] pub mod auth; #[cfg(feature = "server")] +pub mod live; +#[cfg(feature = "server")] pub mod config; #[cfg(feature = "server")] pub mod mail; @@ -32,6 +34,8 @@ pub use config::{Config, ConfigError}; #[cfg(feature = "server")] pub use detail::{DetailReads, load as load_detail}; #[cfg(feature = "server")] +pub use live::{Change, Topic}; +#[cfg(feature = "server")] pub use mail::{Engine as MailEngine, MailError, Mailer, Outgoing}; #[cfg(feature = "server")] pub use store::{Store, StoreError, TursoStore}; diff --git a/crates/izlek-core/src/live.rs b/crates/izlek-core/src/live.rs new file mode 100644 index 0000000..0e2d05f --- /dev/null +++ b/crates/izlek-core/src/live.rs @@ -0,0 +1,77 @@ +//! Committed-write announcements. +//! +//! A write that committed publishes one [`Change`] per surface it touches, +//! and the change carries a topic — never data. That is deliberate: a +//! channel that carried rows would need a role check per message, and one +//! forgotten filter would leak. A topic cannot leak anything; the woken +//! client re-fetches through the ordinary route, and the existing role gate +//! answers there. +//! +//! [`Change::seq`] is a process-local counter, so a client that sees 41 and +//! then 43 knows it missed one and can resync instead of rendering a mix of +//! before and after. + +use std::sync::atomic::{AtomicU64, Ordering}; + +/// The surface a committed write touched. One write may touch several: a +/// comment is a task's detail and the activity log at once. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Topic { + /// The board: task create, move, delete, save, columns. + Board, + /// One task's detail: comments, subtasks, links, attachments, + /// assignees, deadline. + Task(String), + /// Users, roles, invites, sessions, photos, profile. + Members, + /// The mail queue: `mail_send` rows. + Queue, + /// Mail rules and the decisions they made. + Rules, + /// Workspace settings, sender, limits, public URL. + Settings, + /// The activity and event log. + Activity, +} + +impl Topic { + /// The name the wire uses for this topic: the SSE `event:` field, and + /// the key the role filter decides on. + pub fn kind(&self) -> &'static str { + match self { + Topic::Board => "board", + Topic::Task(_) => "task", + Topic::Members => "members", + Topic::Queue => "queue", + Topic::Rules => "rules", + Topic::Settings => "settings", + Topic::Activity => "activity", + } + } + + /// The task this topic is about, when it is about one. + pub fn id(&self) -> Option<&str> { + match self { + Topic::Task(id) => Some(id), + _ => None, + } + } +} + +/// One committed write: which surface changed, and where this change sits +/// in the store's sequence. Everything a client needs to know to refresh — +/// and nothing about what changed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Change { + pub topic: Topic, + pub seq: u64, +} + +static SEQ: AtomicU64 = AtomicU64::new(0); + +/// The next sequence number, starting at 1. Process-local on purpose: the +/// sequence exists to catch a dropped event inside one stream, not to order +/// two servers. +pub fn next_seq() -> u64 { + SEQ.fetch_add(1, Ordering::Relaxed) + 1 +} diff --git a/crates/izlek-core/src/mail.rs b/crates/izlek-core/src/mail.rs index ea9e359..0a7bda3 100644 --- a/crates/izlek-core/src/mail.rs +++ b/crates/izlek-core/src/mail.rs @@ -92,6 +92,16 @@ pub struct Outgoing { #[async_trait] pub trait Mailer: Send + Sync { async fn send(&self, mail: &Outgoing) -> Result<(), MailError>; + + /// Asks the mail server whether it would have us, without sending anything + /// to anybody: connect, negotiate TLS, say hello, authenticate, hang up. + /// + /// The default answers yes. That is right for a mailer with no server + /// behind it — the ones the tests hold, which accept everything — and the + /// real SMTP sender overrides it with the handshake. + async fn check(&self) -> Result<(), MailError> { + Ok(()) + } } /// How many times a retryable failure is tried before it is given up on and @@ -171,6 +181,18 @@ impl Engine { )) } + /// Asks the mail server whether it would take mail from us, without + /// sending any. Hands back how long the handshake took, the way + /// [`Engine::send_test`] does, so an admin can see a server that answers + /// slowly as well as one that refuses. + pub async fn check_sender(&self) -> std::result::Result { + let started = std::time::Instant::now(); + self.mailer.check().await?; + Ok(Duration::milliseconds( + started.elapsed().as_millis().min(i64::MAX as u128) as i64, + )) + } + /// Everything one crossing owes. Called after the move has committed, never /// inside it. pub async fn on_transition(&self, transition: &Transition) -> crate::store::Result { diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index 431024c..22b23cb 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -68,6 +68,10 @@ pub struct Workspace { /// How the last "send test mail to myself" went, if one has been pressed /// since the sender was last edited. pub sender_test: Option, + /// How the last handshake with the mail server went, if one has happened + /// since the sender was last edited. See [`SenderCheck`] on why this is + /// not the same thing as `sender_test`. + pub sender_check: Option, pub attachment_limit_bytes: u64, pub photo_limit_bytes: u64, pub allowed_file_types: Vec, @@ -128,6 +132,26 @@ pub struct SenderTest { pub error: Option, } +/// How the last handshake with the mail server went. +/// +/// Not the same fact as [`SenderTest`], and kept apart on purpose. A test sends +/// a real message to a real inbox and proves delivery. A check connects, +/// negotiates TLS, says hello, authenticates and hangs up — it proves the host, +/// the port, the encryption and the password without sending anything to +/// anybody. What it cannot prove is that the from-address is one this account +/// is allowed to send as, which is the usual reason a login that works is +/// followed by mail that bounces. +/// +/// `error` is `None` when the server let us in, and otherwise holds what the +/// server said, because "535 authentication failed" is actionable and "it did +/// not work" is not. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SenderCheck { + pub at: OffsetDateTime, + pub took_ms: u64, + pub error: Option, +} + #[derive(Debug, Clone, PartialEq)] pub struct NewSender { pub host: String, @@ -589,6 +613,16 @@ pub struct Recipient { /// trait a test can wrap and count. #[async_trait] pub trait Store: BoardReads + DetailReads + 'static { + + // -- live updates ------------------------------------------------------ + + /// A receiver of committed-write announcements. One [`Change`] per + /// write that committed, carrying the topic to re-fetch and no data: + /// the channel cannot say more than the reader may hear, because it + /// says nothing — the woken client re-fetches through the ordinary + /// role-gated route. Sending to zero subscribers is normal and silent, + /// and a slow subscriber's overflow is the client's cue to resync. + fn subscribe(&self) -> tokio::sync::broadcast::Receiver; // -- workspace --------------------------------------------------------- /// Claims an empty database: writes the workspace, its first account and @@ -619,6 +653,11 @@ pub trait Store: BoardReads + DetailReads + 'static { /// so what is stored is always about the settings that are stored. async fn record_sender_test(&self, workspace_id: &str, test: SenderTest) -> Result<()>; + /// Writes down how the last handshake went. Separate from + /// [`Store::record_sender_test`] so a login that worked can never be + /// rendered as a mail that arrived. + async fn record_sender_check(&self, workspace_id: &str, check: SenderCheck) -> Result<()>; + /// Reads the sender's password. Only the mailer calls this, and nothing it /// returns reaches a response body. async fn smtp_password(&self, workspace_id: &str) -> Result>; @@ -1030,6 +1069,13 @@ pub trait Store: BoardReads + DetailReads + 'static { /// Sends owed right now: claimed but never accepted, and due. async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result>; + /// When the next mail falls due, whether or not that is yet. + /// + /// The sweep asks this so it can sleep exactly that long instead of waking + /// on a fixed beat. A beat is what makes a retry promised for 16:42:47 go + /// out at 16:43: the row was due, and nothing was awake to notice. + async fn next_due_at(&self) -> Result>; + /// Every send a rule has made, newest first, for the admin's trail. async fn sends_for_rule(&self, rule_id: &str, limit: u32) -> Result>; diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index ae0bad5..216c4eb 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -18,9 +18,11 @@ use super::{ ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, CommentWritten, Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, MailSend, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState, - SenderTest, Session, SigninLink, Store, StoreError, TaskCreated, Trigger, User, Workspace, + SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, TaskCreated, Trigger, User, + Workspace, }; use crate::Role; +use crate::live::{Change, Topic}; use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition}; use crate::detail::{ ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, FileLine, @@ -35,6 +37,7 @@ use time::macros::format_description; /// second file is for the day there is data worth keeping. const MIGRATIONS: &[(i64, &str)] = &[ (1, include_str!("../../migrations/0001_init.sql")), + (2, include_str!("../../migrations/0002_sender_check.sql")), ]; /// The board a fresh workspace gets, and its columns. `Done` is the column @@ -57,9 +60,28 @@ pub struct TursoStore { /// exposed through the `Store` trait — callers keep passing and receiving /// plaintext, this field is the detail that makes the row not be one. key: secret::Key, + /// Where committed writes are announced. Held as the sender so the store + /// can hand out a receiver per subscriber; nothing is ever read from here + /// by the store itself. + live: tokio::sync::broadcast::Sender, } impl TursoStore { + /// Announces a committed write. Called only once the write is durable — + /// after commit for a transaction, and never on a path that returned an + /// error — because a subscriber's whole job is to re-read, and waking it + /// before the row lands makes it read the past. + /// + /// A send with no subscribers returns `Err`, which is the ordinary state + /// of a server nobody is looking at. It is dropped on purpose: an + /// announcement nobody is waiting for is not a problem, and logging it + /// would fill the log with the sound of an idle app. + fn announce(&self, topics: impl IntoIterator) { + for topic in topics { + let _ = self.live.send(Change { topic, seq: crate::live::next_seq() }); + } + } + /// Opens (creating if needed) the database at `path` and brings the schema /// up to date. `:memory:` gives a throwaway database for tests. pub async fn open(path: &str) -> Result { @@ -88,7 +110,13 @@ impl TursoStore { restrict_if_present(&sibling(path, "-shm"))?; } let key = load_key(path)?; - let store = Self { conn: tokio::sync::Mutex::new(conn), db, key }; + // 256 is deep enough that a client which pauses for a moment catches + // up without noticing, and shallow enough that one wedged subscriber + // cannot pin an unbounded backlog. Overflowing it is not a failure: + // the reader is told it lagged and resyncs, which is cheaper than the + // memory a larger buffer would cost to avoid saying so. + let (live, _) = tokio::sync::broadcast::channel(256); + let store = Self { conn: tokio::sync::Mutex::new(conn), db, key, live }; store.migrate().await?; store.encrypt_plaintext_passwords().await?; Ok(store) @@ -560,6 +588,14 @@ fn workspace_from(row: &Row) -> Result { }), None => None, }, + sender_check: match opt_stamp(row, 16)? { + Some(at) => Some(SenderCheck { + at, + took_ms: row.get::(17).map_err(backend)?.max(0) as u64, + error: opt_text(row, 18)?, + }), + None => None, + }, public_url: opt_text(row, 15)?, }) } @@ -571,7 +607,8 @@ const WORKSPACE_COLUMNS: &str = "id, name, created_at, attachment_limit_bytes, \ allowed_file_types, photo_limit_bytes, smtp_host, smtp_port, smtp_username, \ smtp_from_name, smtp_from_address, \ (smtp_password IS NOT NULL AND smtp_password <> ''), \ - smtp_test_at, smtp_test_ms, smtp_test_error, public_url"; + smtp_test_at, smtp_test_ms, smtp_test_error, public_url, \ + smtp_check_at, smtp_check_ms, smtp_check_error"; fn user_from(row: &Row) -> Result { Ok(User { @@ -624,6 +661,10 @@ fn fold_email(email: &str) -> String { #[async_trait] impl Store for TursoStore { + fn subscribe(&self) -> tokio::sync::broadcast::Receiver { + self.live.subscribe() + } + async fn claim_workspace( &self, workspace_name: &str, @@ -720,6 +761,9 @@ impl Store for TursoStore { }); } } + // First write in the database's life: settings, members and the + // board all begin here, so a subscriber on any of the three wakes. + self.announce([Topic::Settings, Topic::Members, Topic::Board]); let workspace = self.workspace().await?.ok_or(StoreError::NotFound)?; let admin = self.user(&admin_id).await?.ok_or(StoreError::NotFound)?; @@ -764,7 +808,8 @@ impl Store for TursoStore { "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \ smtp_password = COALESCE(?4, smtp_password), smtp_from_name = ?5, \ smtp_from_address = ?6, smtp_test_at = NULL, smtp_test_ms = NULL, \ - smtp_test_error = NULL WHERE id = ?7", + smtp_test_error = NULL, smtp_check_at = NULL, smtp_check_ms = NULL, \ + smtp_check_error = NULL WHERE id = ?7", params![ sender.host, sender.port as i64, @@ -777,6 +822,28 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + drop(conn); + self.announce([Topic::Settings]); + Ok(()) + } + + async fn record_sender_check(&self, workspace_id: &str, check: SenderCheck) -> Result<()> { + let conn = self.conn.lock().await; + conn + .execute( + "UPDATE workspace SET smtp_check_at = ?1, smtp_check_ms = ?2, \ + smtp_check_error = ?3 WHERE id = ?4", + params![ + stamp(check.at)?, + check.took_ms as i64, + check.error, + workspace_id + ], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([Topic::Settings]); Ok(()) } @@ -795,6 +862,8 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + drop(conn); + self.announce([Topic::Settings]); Ok(()) } @@ -828,6 +897,8 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + drop(conn); + self.announce([Topic::Settings]); Ok(()) } @@ -854,6 +925,8 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + drop(conn); + self.announce([Topic::Settings]); Ok(()) } @@ -892,6 +965,7 @@ impl Store for TursoStore { backend(e) } })?; + self.announce([Topic::Members]); self.user(&id).await?.ok_or(StoreError::NotFound) } @@ -955,6 +1029,8 @@ impl Store for TursoStore { if n == 0 { Err(StoreError::NotFound) } else { + drop(conn); + self.announce([Topic::Members]); Ok(()) } } @@ -971,6 +1047,8 @@ impl Store for TursoStore { if n == 0 { Err(StoreError::NotFound) } else { + drop(conn); + self.announce([Topic::Members]); Ok(()) } } @@ -987,6 +1065,8 @@ impl Store for TursoStore { if n == 0 { Err(StoreError::NotFound) } else { + drop(conn); + self.announce([Topic::Members]); Ok(()) } } @@ -1003,6 +1083,8 @@ impl Store for TursoStore { if n == 0 { Err(StoreError::NotFound) } else { + drop(conn); + self.announce([Topic::Members]); Ok(()) } } @@ -1046,6 +1128,8 @@ impl Store for TursoStore { if n == 0 { Err(StoreError::NotFound) } else { + drop(conn); + self.announce([Topic::Members]); Ok(()) } } @@ -1069,6 +1153,8 @@ impl Store for TursoStore { if n == 0 { Err(StoreError::NotFound) } else { + drop(conn); + self.announce([Topic::Members]); Ok(()) } } @@ -1085,6 +1171,8 @@ impl Store for TursoStore { if n == 0 { Err(StoreError::NotFound) } else { + drop(conn); + self.announce([Topic::Members]); Ok(()) } } @@ -1101,6 +1189,8 @@ impl Store for TursoStore { if n == 0 { Err(StoreError::NotFound) } else { + drop(conn); + self.announce([Topic::Members]); Ok(()) } } @@ -1128,6 +1218,7 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + self.announce([Topic::Members]); match self .one_row( "SELECT id, user_id, created_at, expires_at, used_at FROM signin_link WHERE id = ?1", @@ -1170,6 +1261,9 @@ impl Store for TursoStore { .await .map_err(backend)?; tx.commit().await.map_err(backend)?; + if n == 1 { + self.announce([Topic::Members]); + } Ok(n == 1) } @@ -1196,6 +1290,7 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + self.announce([Topic::Members]); let sql = format!("SELECT {SESSION_COLUMNS} FROM session WHERE id = ?1"); match self.one_row(&sql, params![id]).await? { Some(row) => session_from(&row), @@ -1233,21 +1328,30 @@ impl Store for TursoStore { if n == 0 { Err(StoreError::NotFound) } else { + drop(conn); + self.announce([Topic::Members]); Ok(()) } } async fn revoke_sessions_for_user(&self, user_id: &str, at: OffsetDateTime) -> Result { let conn = self.conn.lock().await; - conn + let n = conn .execute( "UPDATE session SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", params![stamp(at)?, user_id], ) .await - .map_err(backend) + .map_err(backend)?; + drop(conn); + self.announce([Topic::Members]); + Ok(n) } + // The three auth-attempt methods below announce nothing, alone among the + // writes here. They are rate-limit bookkeeping that no surface renders, and + // announcing them would wake every connected client on every failed + // sign-in — traffic in exchange for a screen that would look identical. async fn record_auth_attempt(&self, bucket: &str, at: OffsetDateTime) -> Result<()> { let conn = self.conn.lock().await; conn @@ -1317,6 +1421,8 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + drop(conn); + self.announce([Topic::Board]); Ok(Column { id, name: name.to_string(), @@ -1473,6 +1579,8 @@ impl Store for TursoStore { }; tx.commit().await.map_err(backend)?; + // Task birth touches the board, the task page and the feed at once. + self.announce([Topic::Board, Topic::Task(id.clone()), Topic::Activity]); let (task_key, position) = written; Ok(TaskCreated { row: TaskRow { @@ -1572,6 +1680,7 @@ impl Store for TursoStore { match outcome { Ok(Ok(())) => { tx.commit().await.map_err(backend)?; + self.announce([Topic::Board, Topic::Task(task_id.to_string())]); Ok(()) } Ok(Err(refused)) => { @@ -1614,25 +1723,33 @@ impl Store for TursoStore { async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()> { let conn = self.conn.lock().await; - conn + let n = conn .execute( "INSERT OR IGNORE INTO task_assignee (task_id, user_id) VALUES (?1, ?2)", params![task_id, user_id], ) .await .map_err(backend)?; + drop(conn); + if n > 0 { + self.announce([Topic::Task(task_id.to_string())]); + } Ok(()) } async fn unassign_task(&self, task_id: &str, user_id: &str) -> Result<()> { let conn = self.conn.lock().await; - conn + let n = conn .execute( "DELETE FROM task_assignee WHERE task_id = ?1 AND user_id = ?2", params![task_id, user_id], ) .await .map_err(backend)?; + drop(conn); + if n > 0 { + self.announce([Topic::Task(task_id.to_string())]); + } Ok(()) } @@ -1734,7 +1851,16 @@ impl Store for TursoStore { .await; match written { - Ok(true) => tx.commit().await.map_err(backend), + Ok(true) => { + tx.commit().await.map_err(backend)?; + // An edge is visible from both endpoints and on the board. + self.announce([ + Topic::Board, + Topic::Task(blocked_task_id.to_string()), + Topic::Task(blocking_task_id.to_string()), + ]); + Ok(()) + } Ok(false) => { let _ = tx.rollback().await; Err(StoreError::Cycle) @@ -1753,7 +1879,7 @@ impl Store for TursoStore { at: OffsetDateTime, ) -> Result<()> { let conn = self.conn.lock().await; - conn + let n = conn .execute( "UPDATE task_dependency SET cleared_at = ?3 \ WHERE blocked_task_id = ?1 AND blocking_task_id = ?2 AND cleared_at IS NULL", @@ -1761,6 +1887,14 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + drop(conn); + if n > 0 { + self.announce([ + Topic::Board, + Topic::Task(blocked_task_id.to_string()), + Topic::Task(blocking_task_id.to_string()), + ]); + } Ok(()) } @@ -1810,6 +1944,7 @@ impl Store for TursoStore { } tx.commit().await.map_err(backend)?; + self.announce([Topic::Task(task_id.to_string()), Topic::Activity]); Ok(CommentWritten { comment_id, activity_id, @@ -1839,6 +1974,8 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + drop(conn); + self.announce([Topic::Task(new.task_id.to_string())]); Ok(id) } @@ -1889,11 +2026,25 @@ impl Store for TursoStore { } async fn delete_attachment(&self, id: &str) -> Result { + // Which task loses the file has to be read before the row goes: after + // the delete there is nothing left to ask, and a detail panel that is + // never told still shows the attachment. + let owner = self + .one_row("SELECT task_id FROM attachment WHERE id = ?1", params![id]) + .await? + .map(|row| row.get::(0).map_err(backend)) + .transpose()?; let conn = self.conn.lock().await; let gone = conn .execute("DELETE FROM attachment WHERE id = ?1", params![id]) .await .map_err(backend)?; + drop(conn); + if gone > 0 + && let Some(task_id) = owner + { + self.announce([Topic::Task(task_id)]); + } Ok(gone > 0) } @@ -1969,7 +2120,16 @@ impl Store for TursoStore { .await; match written { - Ok(Some(ids)) => tx.commit().await.map(|_| ids).map_err(backend), + Ok(Some(ids)) => { + tx.commit().await.map_err(backend)?; + // An edit shows on the card face as well as in the panel. + self.announce([ + Topic::Board, + Topic::Task(task_id.to_string()), + Topic::Activity, + ]); + Ok(ids) + } Ok(None) => { let _ = tx.rollback().await; Err(StoreError::NotFound) @@ -2148,6 +2308,14 @@ impl Store for TursoStore { match written { Ok(Outcome::Wrote) => { tx.commit().await.map_err(backend)?; + // Past the commit, so a woken client re-reads the move rather + // than the state before it. The rolled-back arms below say + // nothing on purpose: nothing changed to re-read. + self.announce([ + Topic::Board, + Topic::Task(task_id.to_string()), + Topic::Activity, + ]); Ok(Moved::Recorded(Transition { id: transition_id, task_id: task_id.to_string(), @@ -2332,6 +2500,13 @@ impl Store for TursoStore { match written { Ok(Some(deletion)) => { tx.commit().await.map_err(backend)?; + // The card left the board and its detail panel is now a page + // about nothing — both need to hear, and only after commit. + self.announce([ + Topic::Board, + Topic::Task(task_id.to_string()), + Topic::Activity, + ]); Ok(deletion) } Ok(None) => { @@ -2444,6 +2619,9 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + drop(conn); + // Task-scoped: the task's own trail and the workspace feed both grew. + self.announce([Topic::Activity, Topic::Task(task_id.to_string())]); Ok(id) } @@ -2464,6 +2642,9 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + drop(conn); + // Workspace-wide, belonging to no task — the feed only. + self.announce([Topic::Activity]); Ok(id) } @@ -2501,6 +2682,7 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + self.announce([Topic::Rules]); let sql = format!("SELECT {RULE_COLUMNS} FROM mail_rule WHERE id = ?1"); match self.one_row(&sql, params![id]).await? { Some(row) => rule_from(&row), @@ -2552,6 +2734,8 @@ impl Store for TursoStore { if n == 0 { return Err(StoreError::NotFound); } + drop(conn); + self.announce([Topic::Rules]); Ok(()) } @@ -2646,6 +2830,8 @@ impl Store for TursoStore { if n == 0 { return Err(StoreError::NotFound); } + drop(conn); + self.announce([Topic::Rules]); Ok(()) } @@ -2660,6 +2846,9 @@ impl Store for TursoStore { if n == 0 { return Err(StoreError::NotFound); } + drop(conn); + // The rule's queued mail cascaded away with it, so the queue moved too. + self.announce([Topic::Rules, Topic::Queue]); Ok(()) } @@ -2720,6 +2909,8 @@ impl Store for TursoStore { if n == 0 { return Ok(None); } + // A mail joined the queue, so the queue panel is out of date. + self.announce([Topic::Queue]); let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); match self.one_row(&sql, params![id]).await? { Some(row) => send_from(&row).map(Some), @@ -2747,6 +2938,9 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + // Two surfaces at once: the invite is a queued mail, and an invited + // person shows up in the members list before they ever sign in. + self.announce([Topic::Queue, Topic::Members]); let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); match self.one_row(&sql, params![id]).await? { Some(row) => send_from(&row), @@ -2774,6 +2968,7 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + self.announce([Topic::Queue]); let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1"); match self.one_row(&sql, params![id]).await? { Some(row) => send_from(&row), @@ -2796,6 +2991,11 @@ impl Store for TursoStore { if n == 0 { return Err(StoreError::NotFound); } + // The connection guard goes first: announcing is a send on a channel + // whose subscribers may turn round and read this store, and holding + // the single connection while they do is how that deadlocks. + drop(conn); + self.announce([Topic::Queue]); Ok(()) } @@ -2831,6 +3031,10 @@ impl Store for TursoStore { if n == 0 { return Err(StoreError::NotFound); } + drop(conn); + // The attempt counter and the next-try time both just moved, and the + // queue panel renders both. + self.announce([Topic::Queue]); Ok(()) } @@ -2857,9 +3061,30 @@ impl Store for TursoStore { if n == 0 { return Err(StoreError::NotFound); } + drop(conn); + self.announce([Topic::Queue]); Ok(()) } + async fn next_due_at(&self) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT MIN(next_attempt_at) FROM mail_send WHERE next_attempt_at IS NOT NULL", + (), + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(None); + }; + // MIN over no rows is one row holding NULL, not an empty result. + match row.get_value(0).map_err(backend)? { + Value::Text(at) => parse_stamp(&at).map(Some), + _ => Ok(None), + } + } + async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result> { let conn = self.conn.lock().await; let sql = format!( @@ -2922,6 +3147,8 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + drop(conn); + self.announce([Topic::Queue]); Ok(()) } @@ -2948,6 +3175,9 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + drop(conn); + // A decision is what the rules page's decisions tab renders. + self.announce([Topic::Rules]); Ok(()) } diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index 5c3c072..091361f 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -101,14 +101,18 @@ async fn migrations_apply_once_and_survive_reopen() { let path = dir.join("izlek.db").to_string_lossy().into_owned(); let first = TursoStore::open(&path).await.unwrap(); - assert_eq!(first.schema_version().await.unwrap(), 1); + // Whatever the newest migration is — pinning the number here only means + // editing this line every time one is added, which tests the constant + // rather than the behaviour. + let applied = first.schema_version().await.unwrap(); + assert!(applied >= 1, "no migration applied at all"); claim(&first).await; drop(first); - // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and - // must not lose what the first open wrote. + // Re-opening must not re-run a migration (0001's CREATE TABLE would fail) + // and must not lose what the first open wrote. let second = TursoStore::open(&path).await.unwrap(); - assert_eq!(second.schema_version().await.unwrap(), 1); + assert_eq!(second.schema_version().await.unwrap(), applied); assert_eq!(second.workspace().await.unwrap().unwrap().name, "İzlek"); drop(second); let _ = std::fs::remove_dir_all(&dir); @@ -5715,3 +5719,252 @@ async fn a_stored_address_is_the_one_mail_links_point_at() { ); let _ = std::fs::remove_dir_all(&dir); } + +// -- live announcements ----------------------------------------------------- + +/// Drains whatever the store has announced so far into the set of topic names. +/// `try_recv` rather than `recv` on purpose: the point is what has ALREADY been +/// said by the time the write returned, not what might arrive later. +fn announced(rx: &mut tokio::sync::broadcast::Receiver) -> Vec { + let mut seen = Vec::new(); + while let Ok(change) = rx.try_recv() { + seen.push(change.topic.kind().to_string()); + } + seen +} + +/// Every family of write announces the surface it changed. This is the property +/// the whole live layer rests on: a surface nobody announces is a surface that +/// stays stale until the reader reloads by hand. +#[tokio::test] +async fn every_kind_of_write_announces_its_surface() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let board = store.board(&workspace).await.unwrap().unwrap(); + let column_id = column_named(store, &workspace, "Backlog").await; + let now = OffsetDateTime::now_utc(); + + let mut rx = store.subscribe(); + + // Board + Task + Activity. + store + .create_task(NewTask { + board_id: &board.id, + column_id: &column_id, + parent_id: None, + title: "Ship the exporter", + description: "", + deadline: None, + created_by: &admin, + }) + .await + .unwrap(); + // Members. + member(store, &workspace, "bo@izlek.sh", "Bo").await; + // Queue. + store + .queue_notice("bo@izlek.sh", "Subject", "Body", now) + .await + .unwrap(); + // Rules. + store + .create_mail_rule( + &board.id, + &Trigger::StatusBecomes(Some(column_id.clone())), + "Something moved", + Audience::Board, + now, + false, + ) + .await + .unwrap(); + // Settings. + store + .set_public_url(&workspace, Some("https://izlek.example")) + .await + .unwrap(); + // Activity with no task of its own. + store + .record_event( + Some(&admin), + &izlek_core::detail::ActivityKind::Other("settings".to_string()), + "", + now, + ) + .await + .unwrap(); + + let seen = announced(&mut rx); + for topic in ["board", "task", "members", "queue", "rules", "settings", "activity"] { + assert!( + seen.iter().any(|k| k == topic), + "no {topic} announcement; heard {seen:?}" + ); + } +} + +/// A write that failed says nothing. A client woken by a change that never +/// committed would re-read the state it already had — harmless once, and a +/// permanent background hum if every refused mail sent one. +#[tokio::test] +async fn a_write_that_failed_announces_nothing() { + let (scratch, _workspace, _admin) = workspace_with_admin().await; + let store = &scratch.store; + let mut rx = store.subscribe(); + + let missing = Ulid::new().to_string(); + assert!(matches!( + store + .record_send_accepted(&missing, OffsetDateTime::now_utc()) + .await, + Err(StoreError::NotFound) + )); + + assert!( + announced(&mut rx).is_empty(), + "a refused write announced a change" + ); +} + +/// Every write announces, and this is what keeps it true tomorrow. +/// +/// The live layer's whole promise — that no surface goes stale until somebody +/// reloads by hand — rests on one thing: a method that changes a row also says +/// so. That is not a property a running test can observe in general, because +/// the failure is a method nobody wrote a test for. So it is checked against +/// the source instead: every method of the `Store` impl that issues an INSERT, +/// UPDATE or DELETE must also announce, and a method that deliberately does +/// not has to say so here, by name, with a reason. +/// +/// A new write with no announcement fails this test rather than shipping a +/// screen that quietly stops updating. +#[test] +fn every_writing_method_announces_or_is_named_here() { + // Rate-limit bookkeeping. No surface renders an auth attempt, and + // announcing one would wake every connected client on every failed + // sign-in — traffic bought for a screen that would look identical. + const SILENT_ON_PURPOSE: &[&str] = &[ + "record_auth_attempt", + "clear_auth_attempts", + "prune_auth_attempts", + ]; + + let source = include_str!("../src/store/turso_store.rs"); + let start = source + .find("impl Store for TursoStore {") + .expect("the Store impl moved"); + // The impl ends at the first line that is a lone `}` in column zero. + let end = source[start..] + .find("\n}\n") + .map(|at| start + at) + .expect("unterminated impl block"); + let impl_block = &source[start..end]; + + let mut silent = Vec::new(); + let mut methods = impl_block.split("\n async fn ").skip(1).peekable(); + while let Some(chunk) = methods.next() { + let name = chunk + .split(['(', '<', ' ']) + .next() + .expect("a method with no name"); + let writes = chunk.contains("INSERT INTO") + || chunk.contains("UPDATE ") + || chunk.contains("DELETE FROM"); + if writes && !chunk.contains("announce(") && !SILENT_ON_PURPOSE.contains(&name) { + silent.push(name.to_string()); + } + } + + assert!( + silent.is_empty(), + "these methods change rows without announcing it, so the screens \ + showing those rows will go stale until someone reloads by hand: {silent:?}. \ + Either call `self.announce(..)` after the write commits, or add the \ + method to SILENT_ON_PURPOSE with the reason." + ); +} + +/// The sweep sleeps on this answer, so it has to be the earliest moment +/// anything is owed — not merely some moment, and not the newest. +#[tokio::test] +async fn the_next_due_moment_is_the_earliest_one() { + let (scratch, _workspace, _admin) = workspace_with_admin().await; + let store = &scratch.store; + + assert_eq!( + store.next_due_at().await.unwrap(), + None, + "an empty queue owes nothing" + ); + + let now = OffsetDateTime::now_utc(); + // Queued out of order on purpose: the answer is the earliest, not the first. + store + .queue_notice("late@izlek.sh", "Later", "body", now + Duration::hours(2)) + .await + .unwrap(); + store + .queue_notice("soon@izlek.sh", "Sooner", "body", now + Duration::minutes(5)) + .await + .unwrap(); + + let due = store.next_due_at().await.unwrap().expect("nothing owed"); + // Stored to the second, so compare at that grain. + assert!( + (due - (now + Duration::minutes(5))).abs() < Duration::seconds(1), + "expected the sooner of the two, got {due}" + ); +} + +/// A handshake and a delivered mail are different facts, kept in different +/// columns, and editing the sender invalidates both — they were about a server +/// that is no longer the one configured. +#[tokio::test] +async fn a_sender_check_is_recorded_apart_from_a_test_and_cleared_on_edit() { + let (scratch, workspace, _admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let sender = |host: &str| NewSender { + host: host.to_string(), + port: 465, + username: "izlek".into(), + password: Some("hunter2".into()), + from_name: "İzlek".into(), + from_address: "izlek@izlek.sh".into(), + }; + store.set_sender(&workspace, sender("smtp.one.test")).await.unwrap(); + + // A login that worked, and a mail that did not: both true at once, and + // neither may be rendered as the other. + store + .record_sender_check( + &workspace, + izlek_core::store::SenderCheck { at: now, took_ms: 120, error: None }, + ) + .await + .unwrap(); + store + .record_sender_test( + &workspace, + izlek_core::store::SenderTest { at: now, took_ms: 0, error: Some("550 not allowed".into()) }, + ) + .await + .unwrap(); + + let ws = store.workspace().await.unwrap().unwrap(); + let check = ws.sender_check.expect("no check recorded"); + assert_eq!(check.error, None, "the handshake succeeded"); + assert_eq!(check.took_ms, 120); + assert_eq!( + ws.sender_test.expect("no test recorded").error.as_deref(), + Some("550 not allowed"), + "the send still failed, and says why" + ); + + // Point it at a different server: what was known is now about nothing. + store.set_sender(&workspace, sender("smtp.two.test")).await.unwrap(); + let ws = store.workspace().await.unwrap().unwrap(); + assert!(ws.sender_check.is_none(), "a stale handshake survived an edit"); + assert!(ws.sender_test.is_none(), "a stale test survived an edit"); +} diff --git a/crates/izlek-web/Cargo.toml b/crates/izlek-web/Cargo.toml index f8f5fe5..48c718b 100644 --- a/crates/izlek-web/Cargo.toml +++ b/crates/izlek-web/Cargo.toml @@ -17,6 +17,7 @@ topcoat = { version = "0.6.2", default-features = false, features = [ "serve", "compression", "multipart", + "sse", ] } izlek-core = { workspace = true, features = ["server"] } serde.workspace = true @@ -25,6 +26,9 @@ time.workspace = true thiserror.workspace = true tokio = { workspace = true } async-trait = "0.1.92" +# The live stream is built with `futures_util::stream::unfold`; topcoat does +# not re-export the futures traits, so this is named directly. +futures-util = { version = "0.3", default-features = false } # TLS through rustls with the ring provider: no OpenSSL on the deployment box, # and no system certificate store to be missing inside a container. lettre = { version = "0.11.23", default-features = false, features = [ @@ -42,4 +46,7 @@ grass = "0.13" [dev-dependencies] http = "1.5" +# Reads an SSE body frame by frame, so a live-channel test can wait for the +# announcement it expects instead of for a clock. +http-body-util = "0.1" ulid = { workspace = true } diff --git a/crates/izlek-web/src/board.rs b/crates/izlek-web/src/board.rs index 9b8c0c2..3f9ac70 100644 --- a/crates/izlek-web/src/board.rs +++ b/crates/izlek-web/src/board.rs @@ -376,7 +376,9 @@ async fn render_card(
(card.title.clone())
- + // Overdue is a comparison against today, so a tab left open + // over midnight is wrong until something re-renders it. + (deadline) if let Some(parts) = subtasks.clone() { diff --git a/crates/izlek-web/src/detail.rs b/crates/izlek-web/src/detail.rs index bdeed00..fc243b0 100644 --- a/crates/izlek-web/src/detail.rs +++ b/crates/izlek-web/src/detail.rs @@ -1530,6 +1530,14 @@ async fn dep_row( } } +/// The version stamp a `/files/{id}` URL carries: the row's `uploaded_at`. +/// Uploads are insert-only — nothing in the store rewrites an attachment — +/// so the stamp is the one moment the bytes have ever changed, and a URL +/// that carries it can be cached as if it were the bytes themselves. +fn attachment_stamp(attachment: &izlek_core::store::Attachment) -> String { + (attachment.uploaded_at.unix_timestamp_nanos() / 1_000).to_string() +} + async fn file_chip( cx: &Cx, task_id: &str, @@ -1545,7 +1553,13 @@ async fn file_chip( let href = if crate::files::viewer_kind(&file.mime_type).is_some() { format!("/?task={task_id}&tab={}&file={}", Tab::Files.slug(), file.id) } else { - format!("/files/{}", file.id) + // The stamp rides on the row, which the chip's `FileLine` does not + // carry: one lookup per plain-download chip buys the same versioned + // URL the viewer streams from. + match accounts(cx).store().attachment(&file.id).await { + Ok(Some(row)) => format!("/files/{}?v={}", file.id, attachment_stamp(&row)), + _ => format!("/files/{}", file.id), + } }; view! { cx => @@ -2143,8 +2157,9 @@ pub async fn file_viewer_modal( // Closing a file returns to the panel exactly as it stood, tab and all: // a viewer is opened from a section, not from the task at large. let close_href = format!("/?task={task_id}&tab={}", tab.slug()); - let src = format!("/files/{file_id}"); - let download_href = format!("/files/{file_id}?dl=1"); + let stamp = attachment_stamp(&attachment); + let src = format!("/files/{file_id}?v={stamp}"); + let download_href = format!("/files/{file_id}?dl=1&v={stamp}"); let name = attachment.file_name.clone(); // A workbook is the one viewer whose bytes are read here rather than // handed to an element; every other kind streams from `/files/{id}` and diff --git a/crates/izlek-web/src/files.rs b/crates/izlek-web/src/files.rs index cd7f055..2a0b94c 100644 --- a/crates/izlek-web/src/files.rs +++ b/crates/izlek-web/src/files.rs @@ -479,6 +479,16 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> // without one. Sent on every response, not only media — harmless either // way and one less type to special-case. headers.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes")); + // An attachment's bytes are write-once — nothing in the store rewrites + // a row — so the id in the URL is already its own version, and the + // `?v=` stamp the render sites attach only makes that visible. A year + // of `immutable` costs nothing because the URL can never outlive its + // bytes; `private` keeps a shared proxy from handing one workspace's + // attachments to another. + headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static("private, max-age=31536000, immutable"), + ); let total = bytes.len() as u64; let range = request_headers(cx) diff --git a/crates/izlek-web/src/i18n.rs b/crates/izlek-web/src/i18n.rs index 38e96f9..3e615d6 100644 --- a/crates/izlek-web/src/i18n.rs +++ b/crates/izlek-web/src/i18n.rs @@ -122,6 +122,9 @@ pub enum Key { OutgoingMail, Connected, NotConfiguredChip, + Unchecked, + Refused, + CheckConnection, NotConnectedNote, SmtpHostLabel, PortLabel, @@ -523,6 +526,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (Connected, Tr) => "Bağlı", (NotConfiguredChip, En) => "Not configured", (NotConfiguredChip, Tr) => "Yapılandırılmadı", + (Unchecked, En) => "Unchecked", + (Unchecked, Tr) => "Denenmedi", + (Refused, En) => "Refused", + (Refused, Tr) => "Reddedildi", + (CheckConnection, En) => "Check connection", + (CheckConnection, Tr) => "Bağlantıyı dene", (NotConnectedNote, En) => "Not connected.", (NotConnectedNote, Tr) => "Bağlı değil.", (SmtpHostLabel, En) => "SMTP HOST", diff --git a/crates/izlek-web/src/layout.rs b/crates/izlek-web/src/layout.rs index 146754b..787c8c0 100644 --- a/crates/izlek-web/src/layout.rs +++ b/crates/izlek-web/src/layout.rs @@ -81,7 +81,11 @@ pub(crate) async fn avatar(cx: &Cx, person: &Person, extra: &str) -> Result { let class = format!("avatar avatar-tone-{tone} {extra}"); let name = person.display_name.clone(); if person.has_photo { - let src = format!("/photo/{}", person.id); + let src = format!( + "/photo/{}?v={}", + person.id, + crate::photo::photo_stamp(cx, &person.id) + ); view! { cx => (name.clone()) @@ -237,7 +241,111 @@ pub async fn soft_nav_script(cx: &Cx) -> Result { document.querySelectorAll('.comment-list').forEach(function (list) { list.scrollTop = list.scrollHeight; }); \ document.dispatchEvent(new Event('izlek:wire')); \ } \ - function swap(html, url, fresh, push) { \ + function keyOf(el) { \ + var form = el.form ? (el.form.getAttribute('action') || '') : ''; \ + return form + '|' + (el.name || '') + '|' + (el.type || '') + '|' + (el.tagName || ''); \ + } \ + function editable(el) { \ + return el.type !== 'hidden' && el.type !== 'password' && el.type !== 'file'; \ + } \ + function captureFields() { \ + var active = document.activeElement, out = []; \ + document.querySelectorAll('input, textarea, select').forEach(function (el) { \ + if (!editable(el)) { return; } \ + var moved; \ + if (el.type === 'checkbox' || el.type === 'radio') { moved = el.checked !== el.defaultChecked; } \ + else if (el.tagName === 'SELECT') { \ + var def = -1; \ + for (var j = 0; j < el.options.length; j++) { if (el.options[j].defaultSelected) { def = j; break; } } \ + if (def < 0) { def = 0; } \ + moved = el.selectedIndex !== def; \ + } else { moved = el.value !== el.defaultValue; } \ + var focused = el === active; \ + if (!moved && !focused) { return; } \ + var start = -1, end = -1; \ + try { if (el.selectionStart != null) { start = el.selectionStart; end = el.selectionEnd; } } catch (err) { } \ + out.push({ k: keyOf(el), v: el.value, c: el.checked, i: el.selectedIndex, f: focused, s: start, e: end }); \ + }); \ + return out; \ + } \ + function restoreFields(saved) { \ + if (!saved || !saved.length) { return; } \ + var fields = document.querySelectorAll('input, textarea, select'); \ + saved.forEach(function (was) { \ + var el = null; \ + for (var i = 0; i < fields.length; i++) { \ + if (keyOf(fields[i]) === was.k) { el = fields[i]; break; } \ + } \ + if (!el) { return; } \ + if (el.type === 'checkbox' || el.type === 'radio') { el.checked = was.c; } \ + else if (el.tagName === 'SELECT') { el.selectedIndex = was.i; } \ + else { el.value = was.v; } \ + if (was.f) { \ + try { \ + el.focus(); \ + if (was.s >= 0 && el.setSelectionRange) { el.setSelectionRange(was.s, was.e); } \ + } catch (err) { } \ + } \ + }); \ + } \ + function clientMade(node) { \ + return node.nodeType === 1 && node.classList \ + && (node.classList.contains('dd-panel') || node.classList.contains('dd-trigger')); \ + } \ + function pairable(a, b) { \ + if (a.nodeType !== b.nodeType) { return false; } \ + if (a.nodeType !== 1) { return true; } \ + if (a.nodeName !== b.nodeName) { return false; } \ + if (a.id || b.id) { return a.id === b.id; } \ + return true; \ + } \ + function syncAttrs(from, to) { \ + var i, at; \ + for (i = to.attributes.length - 1; i >= 0; i--) { \ + at = to.attributes[i]; \ + if (from.getAttribute(at.name) !== at.value) { from.setAttribute(at.name, at.value); } \ + } \ + for (i = from.attributes.length - 1; i >= 0; i--) { \ + at = from.attributes[i]; \ + if (at.name.indexOf('data-dd') === 0) { continue; } \ + if (!to.hasAttribute(at.name)) { from.removeAttribute(at.name); } \ + } \ + } \ + function morph(from, to) { \ + if (from.nodeType !== 1) { \ + if (from.nodeValue !== to.nodeValue) { from.nodeValue = to.nodeValue; } \ + return; \ + } \ + syncAttrs(from, to); \ + if (from.nodeName === 'SCRIPT') { \ + if (from.textContent !== to.textContent) { \ + var live = document.createElement('script'); \ + if (to.hasAttribute('src')) { live.setAttribute('src', to.getAttribute('src')); } \ + live.textContent = to.textContent; \ + from.replaceWith(live); \ + } \ + return; \ + } \ + morphChildren(from, to); \ + } \ + function morphChildren(from, to) { \ + var mine = [], theirs = [], n; \ + for (n = from.firstChild; n; n = n.nextSibling) { if (!clientMade(n)) { mine.push(n); } } \ + for (n = to.firstChild; n; n = n.nextSibling) { theirs.push(n); } \ + var i; \ + for (i = 0; i < theirs.length; i++) { \ + if (i < mine.length) { \ + if (pairable(mine[i], theirs[i])) { morph(mine[i], theirs[i]); } \ + else { mine[i].replaceWith(document.importNode(theirs[i], true)); } \ + } else { \ + from.appendChild(document.importNode(theirs[i], true)); \ + } \ + } \ + for (i = theirs.length; i < mine.length; i++) { mine[i].remove(); } \ + } \ + function swap(html, url, fresh, push, morphing) { \ + var keep = window.__izlekKeep ? captureFields() : null; \ + window.__izlekKeep = false; \ var doc = new DOMParser().parseFromString(html, 'text/html'); \ var x = window.scrollX, y = window.scrollY; \ var root = doc.documentElement; \ @@ -247,15 +355,20 @@ pub async fn soft_nav_script(cx: &Cx) -> Result { if (root.hasAttribute('data-ui')) { document.documentElement.setAttribute('data-ui', root.getAttribute('data-ui')); } \ else { document.documentElement.removeAttribute('data-ui'); } \ if (url) { history[push ? 'pushState' : 'replaceState'](null, '', url); } \ - document.body.replaceChildren(); \ - while (doc.body.firstChild) { document.body.appendChild(doc.body.firstChild); } \ - document.body.querySelectorAll('script').forEach(function (old) { \ - var live = document.createElement('script'); \ - if (old.hasAttribute('src')) { live.setAttribute('src', old.getAttribute('src')); } \ - live.textContent = old.textContent; \ - old.replaceWith(live); \ - }); \ - window.scrollTo(fresh ? 0 : x, fresh ? 0 : y); \ + if (morphing) { \ + morph(document.body, doc.body); \ + } else { \ + document.body.replaceChildren(); \ + while (doc.body.firstChild) { document.body.appendChild(doc.body.firstChild); } \ + document.body.querySelectorAll('script').forEach(function (old) { \ + var live = document.createElement('script'); \ + if (old.hasAttribute('src')) { live.setAttribute('src', old.getAttribute('src')); } \ + live.textContent = old.textContent; \ + old.replaceWith(live); \ + }); \ + window.scrollTo(fresh ? 0 : x, fresh ? 0 : y); \ + } \ + restoreFields(keep); \ wire(); \ } \ function sweepPanels() { \ @@ -269,6 +382,12 @@ pub async fn soft_nav_script(cx: &Cx) -> Result { function () { window.location.href = url; } \ ); \ }; \ + window.__izlekRefresh = function () { \ + fetch(window.location.href).then( \ + function (r) { return r.text().then(function (t) { swap(t, r.url, false, false, true); }); }, \ + function () {} \ + ); \ + }; \ window.__izlekPost = function (action, fields) { \ fetch(action, { method: 'POST', body: new URLSearchParams(fields) }).then( \ function (r) { return r.text().then(function (t) { swap(t, r.url); }); }, \ @@ -394,6 +513,95 @@ pub async fn soft_nav_script(cx: &Cx) -> Result { /// | 40 | the topbar `.user-menu` (pin+blur), then the rules composer, then a rules edit row (back to `/rules`) | `layout.rs`'s `escape_script` | /// | 20 | the datepicker popover | `board.rs`'s `card_menu_script` | /// | 10 | the card context menu | `board.rs`'s `card_menu_script` | +/// The live channel's browser half: one `EventSource` per tab, and the slow +/// tick that keeps clock-driven text honest. +/// +/// Everything here is one script because both halves end in the same act — +/// re-fetch the current URL through `__izlekGo` and let `swap()` do what it +/// already does after every form post. There is deliberately no second render +/// path: a partial-update mechanism would be a second way for the page to be +/// wrong, and the full swap is the one the app exercises constantly. +/// +/// Three things it must not get wrong: +/// +/// The `__izlekLive` guard is not decoration. `swap()` re-executes every +/// swapped-in script, so without it each soft navigation would open another +/// `EventSource` and the tab would end up holding one connection per page it +/// had ever visited. +/// +/// A refresh must not disturb what somebody is in the middle of. The first +/// attempt held the refresh back while a form was dirty, which was wrong twice +/// over: one unsubmitted form froze every other surface on the screen, and a +/// dropdown could never be used at all while the workspace was busy, because +/// each update slammed it shut. +/// +/// The cause of both was the refresh throwing the whole page away. So the live +/// path does not: it MORPHS. `swap`'s morphing mode walks the freshly fetched +/// document against the live one and touches only what actually differs — +/// changed text, changed attributes, added and removed nodes. Everything else +/// is the same DOM node it was a moment ago, so an open dropdown stays open, a +/// caret stays where it was, a half-typed comment keeps its text, and a scrolled +/// panel keeps its position. Not because any of them is special-cased, but +/// because nothing touched them. +/// +/// Two kinds of node need naming for this to hold. The dropdown builds a +/// `.dd-trigger` beside each select and appends a `.dd-panel` to the body, and +/// neither exists in the server's HTML — a morph that did not know this would +/// delete them as strays on the first update. And a ` } +} + pub async fn escape_manager_script(cx: &Cx) -> Result { use topcoat::view::Unescaped; const JS: &str = "\ @@ -510,6 +718,10 @@ async fn root_layout(cx: &Cx, slot: Result) -> Result { (escape_manager_script(cx).await?) (soft_nav_script(cx).await?) + // Only for a signed-in page: `/api/live` answers 401 to + // everybody else, and an auth screen that opened a stream + // would just reconnect against that refusal forever. + if asking.is_some() { (live_script(cx).await?) } (content) diff --git a/crates/izlek-web/src/lib.rs b/crates/izlek-web/src/lib.rs index 376e3b4..3ea7002 100644 --- a/crates/izlek-web/src/lib.rs +++ b/crates/izlek-web/src/lib.rs @@ -10,6 +10,7 @@ pub mod dropdown; pub mod files; pub mod i18n; pub mod layout; +pub mod live; pub mod logs; pub mod pages; pub mod photo; diff --git a/crates/izlek-web/src/live.rs b/crates/izlek-web/src/live.rs new file mode 100644 index 0000000..c44b7a1 --- /dev/null +++ b/crates/izlek-web/src/live.rs @@ -0,0 +1,151 @@ +//! The live channel: one long-lived connection per open tab, carrying the news +//! that something changed. +//! +//! What travels here is a topic and nothing else — never a row, never a name. +//! That is the whole security design. A channel that carried data would need a +//! role check on every message, and the day somebody adds a topic and forgets +//! the check is the day the queue leaks to a member. A topic name cannot leak +//! anything: the client is told only *which* surface moved, and re-fetches it +//! through the ordinary route, where the ordinary role gate answers. The one +//! thing this file must still get right is not naming an admin-only surface to +//! somebody who is not an admin — [`may_hear`] is that, and it is the reason +//! the filter runs here rather than in the browser. + +use std::time::Duration; + +use izlek_core::{Change, Topic}; +use serde::Serialize; +use tokio::sync::broadcast::error::RecvError; +use tokio::time::Instant; +use topcoat::context::{Cx, try_app_context}; +use topcoat::router::content::sse::{Event, KeepAlive, Sse}; +use topcoat::router::response::{IntoResponse, Response}; +use topcoat::router::{StatusCode, route}; + +use crate::server::{accounts, require_user}; + +/// How long one connection is held before the server ends it and the browser +/// opens another. Set from `config/izlek.toml`; absent — as in the test router +/// — the default stands in. +#[derive(Clone, Copy, Debug)] +pub struct LiveWindow(pub Duration); + +impl Default for LiveWindow { + fn default() -> Self { + Self(Duration::from_secs(300)) + } +} + +/// Tells a live stream that the process is going down. +/// +/// Without this, stopping the server takes as long as its graceful shutdown +/// allows — thirty seconds by default. The server stops accepting connections +/// and then waits for in-flight requests to finish, and an open live stream is +/// an in-flight request that intends to sit there for minutes. Every open tab +/// is one. So the streams are told, and they end; the browser reconnects when +/// the server comes back, which is what it does after any dropped connection. +#[derive(Clone)] +pub struct Shutdown(pub tokio::sync::watch::Receiver); + +/// Whether a reader of this role may be told that this surface moved. +/// +/// The board, a task and the member list are what every signed-in person +/// already sees. The queue, the rules, the settings and the activity log are +/// admin screens, and CLAUDE.md's rule — a role that cannot act on a surface +/// does not see it — reaches the channel too: a member is not told the queue +/// moved, because being told is itself knowing something about the queue. +fn may_hear(topic: &Topic, admin: bool) -> bool { + match topic { + Topic::Board | Topic::Task(_) | Topic::Members => true, + Topic::Queue | Topic::Rules | Topic::Settings | Topic::Activity => admin, + } +} + +/// What one announcement looks like on the wire. +#[derive(Serialize)] +struct Frame<'a> { + topic: &'a str, + /// The task, when the topic is about one. Absent otherwise. + #[serde(skip_serializing_if = "Option::is_none")] + id: Option<&'a str>, + seq: u64, +} + +/// A frame the client reads as "you may have missed something; re-read +/// everything you are showing". +const RESYNC: &str = r#"{"topic":"resync"}"#; + +#[route(GET "/api/live")] +async fn live(cx: &Cx) -> topcoat::Result { + // Resolved once, here, and never again for the life of this connection. + // That is why the connection has a deadline: the reconnect is what + // re-authenticates, so a session revoked mid-stream goes quiet within one + // window rather than never. + let Ok(user) = require_user(cx).await else { + return (StatusCode::UNAUTHORIZED, "").into_response(cx); + }; + let admin = user.role.can_administer(); + let rx = accounts(cx).store().subscribe(); + let stopping = try_app_context::(cx).map(|s| s.0.clone()); + let deadline = Instant::now() + try_app_context::(cx).copied().unwrap_or_default().0; + + let events = futures_util::stream::unfold( + (rx, admin, deadline, stopping), + |(mut rx, admin, deadline, mut stopping)| async move { + loop { + // Already going down: say nothing and end, so this connection + // is not one the shutdown has to sit and wait out. + if stopping.as_ref().is_some_and(|watch| *watch.borrow()) { + return None; + } + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return None; + } + // Three things end the wait: an announcement, the window + // running out, and the server being told to stop. The third is + // watched rather than polled, so Ctrl+C is felt at once. + let heard = tokio::time::timeout(left, async { + match stopping.as_mut() { + Some(watch) => tokio::select! { + _ = watch.changed() => None, + got = rx.recv() => Some(got), + }, + None => Some(rx.recv().await), + } + }) + .await; + let frame = match heard { + // The window closed, or the server is stopping. Ending the + // stream is the point: the browser reconnects by itself and + // authenticates again. + Err(_) | Ok(None) => return None, + // The store is gone, which means the process is going. + Ok(Some(Err(RecvError::Closed))) => return None, + // This reader fell far enough behind that announcements were + // dropped. Which ones is unknowable, so the client is told to + // re-read everything rather than shown a mix of before and + // after. The stream stays open — a slow moment is not a fault. + Ok(Some(Err(RecvError::Lagged(_)))) => Event::new().data(RESYNC), + Ok(Some(Ok(Change { topic, seq }))) => { + if !may_hear(&topic, admin) { + // Not merely unsent: never named. A member's + // connection carries no evidence the queue exists. + continue; + } + let frame = Frame { topic: topic.kind(), id: topic.id(), seq }; + match Event::new().json_data(&frame) { + Ok(event) => event, + Err(problem) => { + return Some((Err(problem), (rx, admin, deadline, stopping))); + } + } + } + }; + return Some((Ok(frame), (rx, admin, deadline, stopping))); + } + }, + ); + + Sse::new(events).keep_alive(KeepAlive::new()).into_response(cx) +} diff --git a/crates/izlek-web/src/logs.rs b/crates/izlek-web/src/logs.rs index 1f3f6ac..bb34004 100644 --- a/crates/izlek-web/src/logs.rs +++ b/crates/izlek-web/src/logs.rs @@ -561,7 +561,7 @@ async fn snapshot( format!( "{} {}", t(lang, Key::NextTry), - izlek_core::detail::moment_label_in(at, zone) + izlek_core::detail::moment_label_with_seconds_in(at, zone) ) } }), @@ -957,6 +957,11 @@ async fn logs_screen( line.state.clone() }; let chip_class = format!("rule-term rule-term-{}", line.state_kind); + // A queued mail's next-try time goes stale on + // the clock, not on a write, so it carries the + // mark the tick looks for. A row with no retry + // left has nothing that moves. + let ticking = line.next_attempt.is_some(); let next_attempt = line.next_attempt.unwrap_or_else(|| t(lang, Key::NoRetry).to_string());
@@ -965,7 +970,7 @@ async fn logs_screen( (state_note) (crate::i18n::attempt_label(lang, line.attempts))
- (next_attempt) + (next_attempt) if line.state_kind == "failed" || line.state_kind == "abandoned" {
diff --git a/crates/izlek-web/src/main.rs b/crates/izlek-web/src/main.rs index 65145e2..6823ad6 100644 --- a/crates/izlek-web/src/main.rs +++ b/crates/izlek-web/src/main.rs @@ -50,7 +50,11 @@ async fn main() { Arc::new(izlek_web::smtp::WorkspaceSmtp::new(store.clone())), config.listen_url(), )); - tokio::spawn(sweep(engine.clone())); + tokio::spawn(sweep(engine.clone(), store.clone())); + + // Told when the process is stopping, so the live streams end instead of + // being waited out. See `izlek_web::live::Shutdown`. + let (stop, stopping) = tokio::sync::watch::channel(false); let router = Router::builder() .discover() @@ -65,6 +69,11 @@ async fn main() { .cookies() .assets(AssetBundle::load().expect("failed to load the asset bundle")) .app_context(accounts) + .app_context(izlek_web::photo::PhotoStamps::default()) + .app_context(izlek_web::live::LiveWindow(std::time::Duration::from_secs( + config.live_seconds, + ))) + .app_context(izlek_web::live::Shutdown(stopping)) .app_context(izlek_web::server::Mail::sending(engine.clone())) .build(); @@ -74,27 +83,65 @@ async fn main() { let listener = tokio::net::TcpListener::bind(config.listen) .await .expect("failed to bind the listen address"); - topcoat::serve(listener, router) - .await - .expect("server error"); + // Not `topcoat::serve`, which installs its own signal handler and gives + // no way to hear it. The handler is taken over so the live streams learn + // about the stop before the graceful shutdown starts counting: without + // that, every open tab holds a stream the shutdown waits its full thirty + // seconds for, and Ctrl+C appears to hang. + topcoat::serve_until(listener, router, async move { + shutdown_signal().await; + let _ = stop.send(true); + }) + .await + .expect("server error"); +} + +/// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a +/// service manager. +async fn shutdown_signal() { + let interrupt = async { + tokio::signal::ctrl_c() + .await + .expect("failed to install the Ctrl+C handler"); + }; + let terminate = async { + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + .expect("failed to install the SIGTERM handler") + .recv() + .await; + }; + + tokio::select! { + () = interrupt => {} + () = terminate => {} + } } /// Retries what a mail server refused earlier and picks up anything a crash /// left claimed but unsent. /// -/// A minute is short enough that the first retry of a host that blinked lands -/// while somebody is still looking at the board, and long enough that a host -/// which is properly down is not hammered — the wait per send widens on its -/// own, and a send that has used its attempts is written off rather than -/// carried forever. -async fn sweep(engine: std::sync::Arc) { +/// It sleeps until the exact moment the next mail falls due rather than waking +/// on a fixed beat. The beat is what made a retry promised for 16:42:47 leave +/// at 16:43 — the row was due and nothing was awake to notice — and a queue +/// that names a second has to mean the second it names. +/// +/// Two other things can wake it. A mail being queued announces itself on the +/// live channel, so an invite goes out as soon as it is asked for instead of +/// waiting out somebody else's timer. And an hour is the longest it will sleep +/// regardless, so a clock jump or a row written by something other than this +/// process is picked up on its own. +async fn sweep( + engine: std::sync::Arc, + store: Arc, +) { /// Enough that a morning's backlog clears in a few passes, few enough that /// one pass cannot sit on the mail server for minutes. const PER_PASS: u32 = 50; + /// The longest this will sleep with nothing due. + const IDLE: std::time::Duration = std::time::Duration::from_secs(3600); - let mut every_minute = tokio::time::interval(std::time::Duration::from_secs(60)); + let mut queued = store.subscribe(); loop { - every_minute.tick().await; match engine .deliver_owed(time::OffsetDateTime::now_utc(), PER_PASS) .await @@ -106,5 +153,60 @@ async fn sweep(engine: std::sync::Arc) { Ok(_) => {} Err(problem) => eprintln!("izlek mail sweep could not read the ledger: {problem}"), } + + // How long until the next mail is owed. A row already due means the + // pass above could not take it — it was over its limit, or something + // else holds it — so the wait is the idle one rather than zero, which + // would spin. + let wait = match store.next_due_at().await { + Ok(Some(at)) => { + let now = time::OffsetDateTime::now_utc(); + if at > now { + (at - now).try_into().unwrap_or(IDLE).min(IDLE) + } else { + IDLE + } + } + Ok(None) => IDLE, + Err(problem) => { + eprintln!("izlek mail sweep could not read the ledger: {problem}"); + IDLE + } + }; + + tokio::select! { + _ = tokio::time::sleep(wait) => {} + // A newly queued mail is due now, so there is no reason to make it + // wait out a timer that was set before it existed. + alive = queue_touched(&mut queued) => { + if !alive { + return; + } + } + } + } +} + +/// Waits for something to happen to the mail queue specifically. +/// +/// The channel carries every topic, and the sweep cares about one. Filtering +/// here rather than in the `select!` matters: a `continue` on somebody else's +/// board edit would send this round the loop and run a whole delivery pass, so +/// every card moved on the board would poke the mail server. Returns false +/// when the channel is gone, which means the process is going with it. +/// +/// Lagging means announcements were dropped — a reason to look, not to stop. +async fn queue_touched(rx: &mut tokio::sync::broadcast::Receiver) -> bool { + use tokio::sync::broadcast::error::RecvError; + loop { + match rx.recv().await { + Ok(change) => { + if change.topic == izlek_core::Topic::Queue { + return true; + } + } + Err(RecvError::Lagged(_)) => return true, + Err(RecvError::Closed) => return false, + } } } diff --git a/crates/izlek-web/src/photo.rs b/crates/izlek-web/src/photo.rs index 8ae26bb..9993dde 100644 --- a/crates/izlek-web/src/photo.rs +++ b/crates/izlek-web/src/photo.rs @@ -1,7 +1,11 @@ //! Profile photo upload, removal and serving. Sibling to `files.rs`, whose //! multipart parsing and mime-sniffing it reuses rather than re-implements. -use topcoat::context::Cx; +use std::collections::HashMap; +use std::sync::{Arc, LazyLock, Mutex}; + +use time::OffsetDateTime; +use topcoat::context::{Cx, try_app_context}; use topcoat::router::content::multipart::Multipart; use topcoat::router::request::headers as request_headers; use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; @@ -67,7 +71,14 @@ async fn upload( return Ok(saved_or_refused("profile_photo", Some(Refusal::NotAnImage))); } return Ok(match store.set_photo(&user.id, &collected, mime).await { - Ok(()) => saved_or_refused("profile_photo", None), + Ok(()) => { + // The bytes changed, so the URL every avatar renders has to + // change with them — bump before the answer goes out. + if let Some(stamps) = try_app_context::(cx) { + stamps.bump(&user.id); + } + saved_or_refused("profile_photo", None) + } Err(_) => saved_or_refused("profile_photo", Some(Refusal::Unavailable)), }); } @@ -87,6 +98,54 @@ async fn delete(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { }) } +/// Photo URL version stamps, in process memory. The `user` row carries no +/// photo-updated moment and a schema column for cache-busting is out of +/// proportion, so the stamp lives here: `upload` bumps it when the bytes +/// change, and every avatar render reads it back. A photo whose bytes this +/// process never saw change — one uploaded by an earlier process — stamps +/// at the process start, which is still a URL no browser has fetched, so +/// it is re-downloaded exactly once per restart and cached from then on. +#[derive(Clone, Default)] +pub struct PhotoStamps(Arc>>); + +/// Unix microseconds at first use: the stamp for every photo whose bytes +/// this process never saw change. Stable for the process's lifetime, and +/// later than any stamp an earlier process emitted, so no pre-restart URL +/// survives a restart. +static PROCESS_START: LazyLock = + LazyLock::new(|| (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000) as i64); + +impl PhotoStamps { + fn stamp(&self, user_id: &str) -> i64 { + self.0 + .lock() + .unwrap() + .get(user_id) + .copied() + .unwrap_or(*PROCESS_START) + } + + fn bump(&self, user_id: &str) { + let now = (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000) as i64; + let mut stamps = self.0.lock().unwrap(); + // A write always moves the URL: never emit a stamp this user has + // already rendered with, even when two writes land inside the same + // microsecond. + let stamp = stamps.get(user_id).copied().unwrap_or(*PROCESS_START); + stamps.insert(user_id.to_string(), now.max(stamp + 1)); + } +} + +/// The stamp an avatar's photo URL carries. A router built without +/// `PhotoStamps` — the test router does this — falls back to the process +/// start, which is still a URL no browser has fetched before. +pub(crate) fn photo_stamp(cx: &Cx, user_id: &str) -> i64 { + match try_app_context::(cx) { + Some(stamps) => stamps.stamp(user_id), + None => *PROCESS_START, + } +} + /// A cheap, non-cryptographic hash — good enough for an `ETag` on bytes only /// this server ever writes. fn fnv1a(bytes: &[u8]) -> u64 { @@ -124,6 +183,15 @@ async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { let etag = format!("\"{:x}\"", fnv1a(&bytes)); let mut headers = HeaderMap::new(); headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap()); + // The stamp in the URL is the other half of this caching: `upload` + // bumps it whenever the bytes change, so a year of `immutable` never + // shows an old photo — a changed photo is a changed URL. `private` + // because the route is session-gated and a shared proxy cache would + // otherwise answer a stranger from another workspace's entry. + headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static("private, max-age=31536000, immutable"), + ); let if_none_match = request_headers(cx) .get(header::IF_NONE_MATCH) diff --git a/crates/izlek-web/src/server.rs b/crates/izlek-web/src/server.rs index 5f45b01..4364faf 100644 --- a/crates/izlek-web/src/server.rs +++ b/crates/izlek-web/src/server.rs @@ -136,6 +136,12 @@ impl Mail { Some(engine.send_test(to).await) } + /// Asks the mail server whether it would have us, sending nothing. + pub async fn check(&self) -> Option> { + let engine = self.0.clone()?; + Some(engine.check_sender().await) + } + fn log(report: izlek_core::store::Result) { match report { Ok(report) if report.sent + report.failed + report.abandoned > 0 => { diff --git a/crates/izlek-web/src/settings.rs b/crates/izlek-web/src/settings.rs index a198aa8..e6081b6 100644 --- a/crates/izlek-web/src/settings.rs +++ b/crates/izlek-web/src/settings.rs @@ -26,7 +26,7 @@ use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, page, route}; use topcoat::view::view; use izlek_core::detail::ActivityKind; -use izlek_core::store::{NewSender, SenderTest, User}; +use izlek_core::store::{NewSender, SenderCheck, SenderTest, Store, User}; use crate::i18n::{Key, Lang, t}; use crate::server::{Refusal, accounts, mail, require_admin, require_user}; @@ -187,7 +187,7 @@ fn redirect_to(query: &str) -> (StatusCode, HeaderMap, Vec) { /// the panel the form it answers actually lives in. fn section_of_call(call: &str) -> &'static str { match call { - "save_sender" | "send_test_mail" => "outgoing", + "save_sender" | "send_test_mail" | "check_sender" => "outgoing", "save_limits" => "limits", "invite_member" | "set_role" | "resend_link" => "members", "send_message" => "message", @@ -436,6 +436,17 @@ async fn save_sender( } Err(problem) => Err(problem), }; + if outcome.is_ok() { + // The settings just changed, so anything known about the old server is + // about a server that is no longer configured. Ask again at once, + // rather than leaving the panel unchecked until somebody presses a + // button. + probe_sender( + mail(cx), + accounts(cx).store().clone(), + admin.workspace_id.clone(), + ); + } let refusal = match outcome { Ok(()) => { let _ = store @@ -462,6 +473,79 @@ async fn save_sender( /// It goes to their own address and nowhere else. A test that could be /// pointed at an address somebody typed would be a way to make İzlek mail a /// stranger on demand, which is a thing worth not building. +/// How long to wait for a mail server before writing the attempt off. +/// +/// Long enough for a slow but healthy server on a bad link, short enough that +/// an admin who mistyped the port is told while still looking at the screen. +const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15); + +/// Asks the mail server whether it would take mail from us, and writes down +/// what it said. +/// +/// Nothing is sent to anybody: this is a handshake — connect, TLS, hello, +/// authenticate, hang up. Spawned rather than awaited by its callers so that +/// saving the settings stays as fast as saving anything else; the result +/// announces itself on the live channel, so the panel catches up on its own a +/// moment later without anybody reloading. +fn probe_sender( + engine: crate::server::Mail, + store: std::sync::Arc, + workspace_id: String, +) { + tokio::spawn(async move { + // This is the bound that actually does the work, not the transport's + // own. Measured: a socket that accepts the connection and then never + // says a word is NOT caught by lettre's `timeout` — the probe sat + // there until this fired. A probe that never records leaves the panel + // on "Unchecked" forever, with nothing to tell anybody it is stuck, so + // something outside the library has to be the backstop. + let dialled = tokio::time::timeout(PROBE_TIMEOUT, engine.check()).await; + let outcome = match dialled { + Ok(outcome) => outcome, + Err(_) => Some(Err(izlek_core::MailError::retryable( + "the mail server did not answer", + ))), + }; + let Some(outcome) = outcome else { + // No engine in this process. Nothing to say, and a failure written + // down here would be about this build rather than these settings. + return; + }; + let at = time::OffsetDateTime::now_utc(); + let check = match outcome { + Ok(took) => SenderCheck { + at, + took_ms: took.whole_milliseconds().max(0) as u64, + error: None, + }, + Err(problem) => SenderCheck { + at, + took_ms: 0, + // Built from what the server said, never from what we sent it. + error: Some(problem.message.clone()), + }, + }; + if let Err(problem) = store.record_sender_check(&workspace_id, check).await { + eprintln!("store error: {problem}"); + } + }); +} + +/// Dials the mail server without sending anything, on an admin's say-so. +#[route(POST "/api/check_sender")] +async fn check_sender(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec)> { + let admin = match require_admin(cx).await { + Ok(admin) => admin, + Err(refusal) => return Ok(saved_or_refused("check_sender", Some(refusal))), + }; + probe_sender( + mail(cx), + accounts(cx).store().clone(), + admin.workspace_id.clone(), + ); + Ok(saved_or_refused("check_sender", None)) +} + #[route(POST "/api/send_test_mail")] async fn send_test_mail(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec)> { let admin = match require_admin(cx).await { @@ -864,6 +948,12 @@ struct TestResult { error: Option, } +/// The last handshake, rendered. +struct CheckResult { + moment: String, + error: Option, +} + /// The sender as the admin's screen may see it, plus the last test's /// outcome — persisted, so it survives the reload the redirect gives it /// rather than living only in this request's memory. @@ -875,18 +965,54 @@ struct Sender { from_address: String, password_set: bool, test: Option, + /// How the last handshake went, and when. `None` means nobody has asked + /// the server yet since these settings were saved. + check: Option, /// The origin mailed links point at, empty when the configured one is /// still in use. public_url: String, } +/// What the panel says about the mail server, in the order the states happen. +/// +/// The point of four states rather than two is that "the fields are filled in" +/// and "the server let us in" are different facts, and the old chip said +/// `Connected` for the first. A host typed correctly with the wrong password +/// showed green while every mail was refused. +#[derive(PartialEq, Eq)] +enum Standing { + /// Something the sender needs is missing. + NotConfigured, + /// Complete, but nobody has asked the server yet. + Unchecked, + /// The server accepted our credentials, at this moment. + Connected(String), + /// The server would not have us, in its own words. + Refused(String), +} + impl Sender { - fn is_connected(&self) -> bool { + /// Whether the form holds everything a sender needs. Says nothing about + /// whether any of it is right — see [`Standing`]. + fn is_complete(&self) -> bool { !self.host.trim().is_empty() && !self.username.trim().is_empty() && !self.from_address.trim().is_empty() && self.password_set } + + fn standing(&self) -> Standing { + if !self.is_complete() { + return Standing::NotConfigured; + } + match &self.check { + None => Standing::Unchecked, + Some(check) => match &check.error { + Some(said) => Standing::Refused(said.clone()), + None => Standing::Connected(check.moment.clone()), + }, + } + } } async fn sender_now(cx: &Cx, zone: time::UtcOffset) -> Result { @@ -900,6 +1026,7 @@ async fn sender_now(cx: &Cx, zone: time::UtcOffset) -> Result { from_address: String::new(), password_set: false, test: None, + check: None, public_url: String::new(), }, Some(workspace) => Sender { @@ -917,6 +1044,10 @@ async fn sender_now(cx: &Cx, zone: time::UtcOffset) -> Result { took: test.error.is_none().then(|| took_label(test.took_ms)), error: test.error, }), + check: workspace.sender_check.map(|check| CheckResult { + moment: izlek_core::detail::moment_label_in(check.at, zone), + error: check.error, + }), public_url: workspace.public_url.unwrap_or_default(), }, }) @@ -1193,20 +1324,41 @@ async fn settings_page(cx: &Cx) -> Result { } if section == Section::Outgoing && let Some(sender) = &sender { - let connected = sender.is_connected(); + let standing = sender.standing(); + let complete = sender.is_complete(); let password_set = sender.password_set; + // One chip, four states. `Connected` carries the moment the + // server said so, because the claim is about a moment: a + // password rotated since is not something this can know. + let (chip_class, chip_text) = match &standing { + Standing::NotConfigured => { + ("chip chip-off", t(lang, Key::NotConfiguredChip).to_string()) + } + Standing::Unchecked => { + ("chip chip-off", t(lang, Key::Unchecked).to_string()) + } + Standing::Connected(at) => ( + "chip chip-connected", + format!("{} {}", t(lang, Key::Connected), at), + ), + Standing::Refused(_) => { + ("chip chip-off", t(lang, Key::Refused).to_string()) + } + };

(t(lang, Key::OutgoingMail))

(t(lang, Key::AdminOnly)) - if connected { - (t(lang, Key::Connected)) - } else { - (t(lang, Key::NotConfiguredChip)) - } + (chip_text)
- if !connected { + // The server's own words when it refused us: + // "535 authentication failed" is something an admin + // can act on, and a bare chip is not. + if let Standing::Refused(said) = &standing { +

(said)

+ } + if !complete {

(t(lang, Key::NotConnectedNote))

} @@ -1282,6 +1434,11 @@ async fn settings_page(cx: &Cx) -> Result {
+
+ +
diff --git a/crates/izlek-web/src/smtp.rs b/crates/izlek-web/src/smtp.rs index bb3b012..a81ae24 100644 --- a/crates/izlek-web/src/smtp.rs +++ b/crates/izlek-web/src/smtp.rs @@ -38,6 +38,16 @@ pub struct Sending { pub from: String, } +/// How long to wait on a mail server that has accepted the connection and then +/// stopped talking. +/// +/// This bounds a server that stalls mid-conversation, and it is why a send +/// cannot hang forever. It is NOT sufficient on its own: measured, a socket +/// that accepts the connection and then says nothing at all is not caught by +/// it, which is why the settings probe wraps its own timeout around the whole +/// call. Both are needed — this one for sends, which nothing else bounds. +const REPLY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15); + /// A sender holding one connection pool. pub struct Smtp { transport: AsyncSmtpTransport, @@ -63,6 +73,7 @@ impl Smtp { Ok(Self { transport: builder .port(mail.port) + .timeout(Some(REPLY_TIMEOUT)) .credentials(Credentials::new( mail.username.clone(), mail.password.clone(), @@ -108,6 +119,31 @@ impl Mailer for Smtp { } }) } + + async fn check(&self) -> Result<(), MailError> { + // `test_connection` opens a connection the same way a send does — + // TLS, EHLO, and AUTH with these credentials — then NOOPs and leaves. + // So a pass means the host, the port, the encryption and the password + // are all right. It does NOT mean mail will arrive: the from-address + // is checked by the server per envelope, and an account that logs in + // fine can still be refused as a sender. + match self.transport.test_connection().await { + Ok(true) => Ok(()), + // Connected, then would not answer a NOOP. Nothing about the + // settings is proven wrong, so it is worth asking again. + Ok(false) => Err(MailError::retryable( + "the mail server accepted the connection and then went quiet", + )), + Err(problem) => { + let said = problem.to_string(); + Err(if problem.is_permanent() { + MailError::permanent(said) + } else { + MailError::retryable(said) + }) + } + } + } } /// The mailer the engine actually holds: it reads the workspace's sender at @@ -200,4 +236,11 @@ impl Mailer for WorkspaceSmtp { }; self.transport(&want).await?.send(mail).await } + + async fn check(&self) -> Result<(), MailError> { + let Some(want) = self.sending().await? else { + return Err(MailError::unsent("no sender configured")); + }; + self.transport(&want).await?.check().await + } } diff --git a/crates/izlek-web/tests/http.rs b/crates/izlek-web/tests/http.rs index 3e586a2..75070df 100644 --- a/crates/izlek-web/tests/http.rs +++ b/crates/izlek-web/tests/http.rs @@ -44,11 +44,22 @@ fn asset_dir() -> PathBuf { )) } +/// A live connection in the suite outlives any test that reads it. The bound +/// on a live test is [`live_until`]'s own timeout — waiting for the frame it +/// expects — not this window: a window short enough to end the stream promptly +/// is also short enough to lose the race on a loaded machine, which is a +/// flaky test rather than a fast one. +const TEST_LIVE_WINDOW: izlek_web::live::LiveWindow = + izlek_web::live::LiveWindow(std::time::Duration::from_secs(10)); + /// A throwaway workspace: its own database file and its own router. struct App { dir: PathBuf, router: Router, store: Arc, + /// Stands in for Ctrl+C. Held so a test can stop this router the way the + /// process stops the real one. + stop: tokio::sync::watch::Sender, } impl App { @@ -61,6 +72,7 @@ impl App { .unwrap(), ); let accounts = Accounts::new(store.clone(), base_url); + let (stop, _) = tokio::sync::watch::channel(false); let router = Router::builder() .discover() .layer( @@ -73,9 +85,12 @@ impl App { .expect("run `topcoat asset bundle` before the http suite"), ) .app_context(accounts) + .app_context(izlek_web::photo::PhotoStamps::default()) + .app_context(TEST_LIVE_WINDOW) + .app_context(izlek_web::live::Shutdown(stop.subscribe())) .app_context(mail) .build(); - Self { dir, router, store } + Self { dir, router, store, stop } } async fn open() -> Self { @@ -99,6 +114,7 @@ impl App { "https://izlek.sh", )); let accounts = Accounts::new(store.clone(), "https://izlek.sh"); + let (stop, _) = tokio::sync::watch::channel(false); let router = Router::builder() .discover() .layer( @@ -111,9 +127,29 @@ impl App { .expect("run `topcoat asset bundle` before the http suite"), ) .app_context(accounts) + .app_context(izlek_web::photo::PhotoStamps::default()) + .app_context(TEST_LIVE_WINDOW) + .app_context(izlek_web::live::Shutdown(stop.subscribe())) .app_context(Mail::sending(engine)) .build(); - Self { dir, router, store } + Self { dir, router, store, stop } + } + + /// Opens `/api/live`. The response is returned as soon as the handler has + /// subscribed, so a caller writes AFTER this returns and the announcement + /// still lands in the feed. + async fn live_open( + &self, + cookie: Option<&str>, + ) -> topcoat::router::response::Response { + let mut request = Request::builder().method("GET").uri("/api/live"); + if let Some(cookie) = cookie { + request = request.header( + header::COOKIE, + HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(), + ); + } + self.router.handle(request.body(Body::empty()).unwrap()).await } /// The single workspace's id, read straight off the store: `TursoStore` is @@ -1980,7 +2016,7 @@ async fn the_soft_swap_rewrites_the_url_before_the_new_pages_scripts_run() { let page = app.get("/", Some(&cookie)).await; let html = String::from_utf8_lossy(&page.bytes); let (_, after) = html - .split_once("function swap(html, url, fresh, push)") + .split_once("function swap(html, url, fresh, push, morphing)") .unwrap_or_else(|| panic!("no soft-nav swap on the board page: {html}")); let body = after .split_once("window.__izlekGo") @@ -3014,7 +3050,11 @@ async fn an_admin_sees_the_sender_and_never_a_password() { let html = String::from_utf8_lossy(&page.bytes); assert!(html.contains("smtp.fastmail.com"), "{html}"); assert!(html.contains("izlek@izlek.sh"), "{html}"); - assert!(html.contains("Connected"), "{html}"); + // Saved in full, and nobody has dialled the server — this router has no + // mail engine at all. "Connected" would be a claim about a handshake that + // never happened, which is the whole reason the chip has four states. + assert!(html.contains("Unchecked"), "{html}"); + assert!(!html.contains("chip-connected"), "{html}"); assert!( !html.contains(SENDER_PASSWORD), "the settings page carried the SMTP password: {html}" @@ -5167,6 +5207,52 @@ async fn an_unknown_photo_id_is_not_found_and_the_photo_revalidates_by_etag() { assert!(cached.bytes.is_empty()); } +/// The whole point of a versioned photo URL: replacing the photo must move +/// the stamp the avatar renders, or the browser keeps serving the bytes it +/// cached under the old URL and the replacement never shows. +#[tokio::test] +async fn a_replaced_photo_moves_the_avatar_url_stamp() { + let app = App::open().await; + let admin = admin(&app).await; + let admin_id = user_id(&app, "ada@izlek.sh").await; + + app.post_multipart( + "/api/profile_photo", + Some(&admin), + &[], + Some(("me.png", "image/png", &PNG)), + ) + .await; + let page = app.get("/settings", Some(&admin)).await; + let html = String::from_utf8_lossy(&page.bytes); + let first = avatar_stamp(&html, &admin_id).expect("avatar photo URL on the settings page"); + + let mut replaced = PNG; + replaced[11] ^= 0xff; + app.post_multipart( + "/api/profile_photo", + Some(&admin), + &[], + Some(("me.png", "image/png", &replaced)), + ) + .await; + let page = app.get("/settings", Some(&admin)).await; + let html = String::from_utf8_lossy(&page.bytes); + let second = avatar_stamp(&html, &admin_id).expect("avatar photo URL after replace"); + + assert!(second > first, "stamp must move: {first} -> {second}"); +} + +/// The `?v=` on an avatar's `/photo/{id}` src, parsed out of a rendered page. +fn avatar_stamp(html: &str, user_id: &str) -> Option { + let marker = format!("/photo/{user_id}?v="); + let rest = &html[html.find(&marker)? + marker.len()..]; + let end = rest + .find(|c: char| !c.is_ascii_digit()) + .unwrap_or(rest.len()); + rest[..end].parse().ok() +} + /// The nav shows a page only to a role that can act on it: an admin's board /// carries all four links, a member's carries neither Rules nor Logs. #[tokio::test] @@ -6626,3 +6712,338 @@ async fn a_big_sheet_pages_down_its_rows_and_across_its_columns() { assert!(html.contains("sheet-table"), "the grid is gone: {html}"); assert!(!html.contains("Col A"), "row 4951 is not row 1: {html}"); } + + +// -- the live channel ------------------------------------------------------- + +/// Reads a live connection until it says `needle`, or until `patience` runs +/// out, and hands back everything it said. Bounded by the frame it is waiting +/// for rather than by a fixed sleep: the positive assertions return the moment +/// the announcement lands, and the negative ones spend their whole patience +/// proving the silence. +async fn live_until( + response: topcoat::router::response::Response, + needle: &str, + patience: std::time::Duration, +) -> String { + use http_body_util::BodyExt; + + let mut body = response.into_body(); + let mut heard = String::new(); + let deadline = tokio::time::Instant::now() + patience; + loop { + let left = deadline.saturating_duration_since(tokio::time::Instant::now()); + if left.is_zero() { + return heard; + } + match tokio::time::timeout(left, body.frame()).await { + Err(_) => return heard, + Ok(None) => return heard, + Ok(Some(Err(_))) => return heard, + Ok(Some(Ok(frame))) => { + if let Some(chunk) = frame.data_ref() { + heard.push_str(&String::from_utf8_lossy(chunk)); + if heard.contains(needle) { + return heard; + } + } + } + } + } +} + +/// A browser nobody signed in gets no feed at all. +#[tokio::test] +async fn the_live_channel_refuses_a_signed_out_caller() { + let app = App::open().await; + admin(&app).await; + let response = app.live_open(None).await; + assert_eq!(response.status(), 401); +} + +/// The role gate reaches the channel: a member is never told that an +/// admin-only surface moved, because being told is itself knowing something +/// about it. The assertion is on the raw bytes on purpose — the topic name +/// must not appear at all, not merely go unrendered. +#[tokio::test] +async fn the_live_channel_never_names_an_admin_surface_to_a_member() { + let app = App::open().await; + let boss = admin(&app).await; + let member = invited(&app, &boss, "bo@izlek.sh", "Bo", Role::Member).await; + + let member_feed = app.live_open(Some(&member)).await; + let admin_feed = app.live_open(Some(&boss)).await; + + // An admin-only write: a mail rule. + let workspace_id = app.workspace_id().await; + let board = app.store.board(&workspace_id).await.unwrap().unwrap().id; + app.store + .create_mail_rule( + &board, + &izlek_core::store::Trigger::Created, + "Something happened", + izlek_core::store::Audience::Board, + time::OffsetDateTime::now_utc(), + false, + ) + .await + .unwrap(); + + // The admin's stream is the clock: once it has the announcement, the + // member's has had every chance to receive one too. + let heard_by_admin = live_until(admin_feed, "rules", std::time::Duration::from_secs(10)).await; + let heard_by_member = + live_until(member_feed, "rules", std::time::Duration::from_millis(500)).await; + + assert!( + !heard_by_member.contains("rules"), + "a member was told about the rules: {heard_by_member}" + ); + assert!( + heard_by_admin.contains("rules"), + "the admin was not told about the rules: {heard_by_admin}" + ); +} + +/// A surface everybody can see is announced to everybody. +#[tokio::test] +async fn the_live_channel_announces_a_shared_surface_to_a_member() { + let app = App::open().await; + let boss = admin(&app).await; + let member = invited(&app, &boss, "bo@izlek.sh", "Bo", Role::Member).await; + let column = first_column(&app).await; + + let feed = app.live_open(Some(&member)).await; + a_task(&app, &boss, &column, "Ship the exporter").await; + let heard = live_until(feed, "board", std::time::Duration::from_secs(10)).await; + + assert!(heard.contains("board"), "no board announcement: {heard}"); +} + +/// The guard is what stops a soft navigation stacking a second `EventSource` +/// on the tab: `swap()` re-executes every script it swaps in, so the script +/// must refuse to run twice. Emitted once, and only once, per page. +#[tokio::test] +async fn the_live_script_is_emitted_once_and_guarded() { + let app = App::open().await; + let boss = admin(&app).await; + let html = String::from_utf8(app.get("/", Some(&boss)).await.bytes).unwrap(); + + assert_eq!( + html.matches("__izlekLive").count(), + 2, + "the live script should appear once, as a guard read and a guard set" + ); + assert!(html.contains("EventSource('/api/live')"), "no live connection"); +} + +/// A signed-out page opens no stream: `/api/live` refuses it, and a tab on the +/// sign-in screen would otherwise reconnect against that refusal forever. +#[tokio::test] +async fn a_signed_out_page_opens_no_live_connection() { + let app = App::open().await; + admin(&app).await; + let html = String::from_utf8(app.get("/", None).await.bytes).unwrap(); + assert!( + !html.contains("__izlekLive"), + "the sign-in page carries the live script" + ); +} + +/// Text that goes stale on the clock rather than on a write carries the mark +/// the tick looks for — a queued mail's next-try time is the case that started +/// this: nothing writes when the minute changes. +#[tokio::test] +async fn a_queued_mails_next_try_is_marked_for_the_tick() { + let app = App::open().await; + let boss = admin(&app).await; + app.store + .queue_notice( + "bo@izlek.sh", + "Your \u{130}zlek sign-in link", + "body", + time::OffsetDateTime::now_utc(), + ) + .await + .unwrap(); + let html = String::from_utf8(app.get("/logs?section=queue", Some(&boss)).await.bytes).unwrap(); + assert!( + html.contains("data-tick"), + "the queue's next-try stamp is not marked for the tick" + ); +} + +/// A live update changes only what actually changed. It morphs the fetched +/// document onto the live one instead of replacing the body, which is what +/// leaves an open dropdown open, a caret where it was and a half-typed comment +/// intact — not because any of those is special-cased, but because nothing +/// touched them. Asserted here so a refactor back to a wholesale replace fails +/// loudly rather than quietly making the app unusable while anyone is typing. +#[tokio::test] +async fn a_live_update_morphs_rather_than_replacing_the_page() { + let app = App::open().await; + let boss = admin(&app).await; + let html = String::from_utf8(app.get("/", Some(&boss)).await.bytes).unwrap(); + + assert!(html.contains("function morph("), "no morph: the live path replaces the page"); + assert!( + html.contains("swap(t, r.url, false, false, true)"), + "the live refresh does not ask for a morphing swap" + ); + // The dropdown's trigger and panel are built by script and are in no + // server response; a morph that did not know that would delete them. + assert!( + html.contains("function clientMade(") && html.contains("dd-panel"), + "the morph would delete the dropdown's own nodes as strays" + ); + // Navigations and form posts must still replace: restoring a sent comment + // over the server's cleared box would look like the message never went. + assert!( + html.contains("document.body.replaceChildren()"), + "the full-replace path is gone, so form posts would carry stale state" + ); + assert!(html.contains("captureFields"), "the swap captures no field state"); + assert!(html.contains("restoreFields"), "the swap restores no field state"); +} + +/// A promise about the future is shown to the second. A retry that says 16:42 +/// but fires at 16:42:47 reads as forty-seven seconds of broken clock to +/// whoever is watching one; the queue names the second it means. +#[tokio::test] +async fn the_queues_next_try_is_shown_to_the_second() { + let app = App::open().await; + let boss = admin(&app).await; + app.store + .queue_notice( + "bo@izlek.sh", + "Subject", + "body", + time::OffsetDateTime::now_utc() + time::Duration::hours(1), + ) + .await + .unwrap(); + + let html = String::from_utf8(app.get("/logs?section=queue", Some(&boss)).await.bytes).unwrap(); + let (_, after) = html.split_once("rule-stamp").expect("no next-try stamp on the queue"); + let stamp: String = after.chars().take(60).collect(); + // hh:mm:ss — three groups, not two. + let seconds = stamp + .split(|c: char| !c.is_ascii_digit() && c != ':') + .find(|part| part.matches(':').count() == 2); + assert!( + seconds.is_some(), + "the next-try stamp is not shown to the second: {stamp}" + ); +} + +/// The chip reports what the server said, not what the form contains. A +/// refusal shows the server's own words, because "535 authentication failed" +/// is something an admin can act on and a grey chip is not. +#[tokio::test] +async fn a_refused_handshake_is_shown_with_what_the_server_said() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + assert!(sender_saved(&app, &admin_cookie).await); + + let workspace = app.workspace_id().await; + app.store + .record_sender_check( + &workspace, + izlek_core::store::SenderCheck { + at: time::OffsetDateTime::now_utc(), + took_ms: 0, + error: Some("535 authentication failed".into()), + }, + ) + .await + .unwrap(); + + let html = String::from_utf8( + app.get("/settings?section=outgoing", Some(&admin_cookie)) + .await + .bytes, + ) + .unwrap(); + assert!(html.contains("Refused"), "{html}"); + assert!( + html.contains("535 authentication failed"), + "the server's words are not on the page: {html}" + ); + assert!(!html.contains("chip-connected"), "a refusal rendered as connected"); +} + +/// A handshake that worked says when, because the claim is about a moment: a +/// password rotated an hour later is not something the panel can know. +#[tokio::test] +async fn a_passed_handshake_says_when_it_passed() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + assert!(sender_saved(&app, &admin_cookie).await); + + let workspace = app.workspace_id().await; + app.store + .record_sender_check( + &workspace, + izlek_core::store::SenderCheck { + at: time::OffsetDateTime::now_utc(), + took_ms: 84, + error: None, + }, + ) + .await + .unwrap(); + + let html = String::from_utf8( + app.get("/settings?section=outgoing", Some(&admin_cookie)) + .await + .bytes, + ) + .unwrap(); + assert!(html.contains("chip-connected"), "{html}"); + assert!(html.contains("Connected"), "{html}"); +} + +/// Dialling the mail server is an admin's business. +#[tokio::test] +async fn a_member_may_not_check_the_sender() { + let app = App::open().await; + let boss = admin(&app).await; + let member = invited(&app, &boss, "bo@izlek.sh", "Bo", Role::Member).await; + let answer = app.post("/api/check_sender", Some(&member), &[]).await; + assert_ne!(answer.body, "null", "a member was allowed to dial the server"); +} + +/// An open live stream must not be something the shutdown has to wait out. +/// +/// The server stops accepting connections and then gives in-flight requests +/// thirty seconds to finish. A live stream intends to sit there for the whole +/// window, and every open tab is one, so before this the answer to Ctrl+C was +/// a thirty-second pause — measured at 30.00s with three tabs open, 0.003s +/// after. The stream is told, and it ends. +#[tokio::test] +async fn a_live_stream_ends_when_the_server_is_told_to_stop() { + use http_body_util::BodyExt; + + let app = App::open().await; + let admin_cookie = admin(&app).await; + let mut body = app.live_open(Some(&admin_cookie)).await.into_body(); + + // It is open and it is staying open: nothing has changed, so a read now + // finds nothing to say. + assert!( + tokio::time::timeout(std::time::Duration::from_millis(200), body.frame()) + .await + .is_err(), + "the stream ended on its own before anything asked it to" + ); + + app.stop.send(true).unwrap(); + + // The window is ten seconds and the patience here is one, so a pass cannot + // be the window expiring. + let ended = tokio::time::timeout(std::time::Duration::from_secs(1), async { + while let Some(Ok(_)) = body.frame().await {} + }) + .await; + assert!(ended.is_ok(), "the stream outlived the stop"); +}