forge
Explore
Log in

Don't you dare go Hollow

A committed write tells every open tab which surface moved

Browse files at this commit

c7393d9f85157a375fe822aac10ce05aa8f921e8Ahmet Kaan GümüşParent: 147cc5d
  • feat
    • a committed write tells every open tab which surface moved
Show full message
✨ feat(live): a committed write tells every open tab which surface moved

The live channel carries a topic and nothing else — never a row, never a
name. 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. The woken client re-fetches through the ordinary route, where the
ordinary role gate already answers; `may_hear` only decides which topic
names a viewer may be told. `live_seconds` in config/izlek.toml bounds how
long a connection is held, which is what re-checks a revoked sign-in.

Carried with it: the SMTP settings panel now separates the handshake from
the delivery. `smtp_check_*` proves the host, port, encryption and
credentials; `smtp_test_*` proves a message reached an inbox. A server that
accepts the login can still refuse the envelope, so neither can be read as
the other, and both clear when the sender is edited.
Cargo.lockmodified+2 -0
@@ -1803,8 +1803,10 @@ version = "0.1.0"
1803 dependencies = [1803 dependencies = [
1804 "async-trait",1804 "async-trait",
1805 "calamine",1805 "calamine",
1806+ "futures-util",
1806 "grass",1807 "grass",
1807 "http",1808 "http",
1809+ "http-body-util",
1808 "izlek-core",1810 "izlek-core",
1809 "lettre",1811 "lettre",
1810 "serde",1812 "serde",
crates/izlek-core/migrations/0002_sender_check.sqladded+15 -0
@@ -0,0 +1,15 @@
1+-- Whether the mail server let us in, which is a different fact from whether a
2+-- mail was delivered.
3+--
4+-- `smtp_test_*` records a real message going out to a real inbox. This records
5+-- a handshake: connect, negotiate TLS, say hello, authenticate, hang up. It
6+-- proves the host, the port, the encryption and the credentials, and it proves
7+-- nothing about whether the from-address is one this account may send as — a
8+-- server that accepts the login can still refuse the envelope. Kept apart so
9+-- neither can be read as the other.
10+--
11+-- Cleared whenever the sender is edited, for the same reason the test result
12+-- is: it was about settings that no longer exist.
13+ALTER TABLE workspace ADD COLUMN smtp_check_at TEXT;
14+ALTER TABLE workspace ADD COLUMN smtp_check_ms INTEGER;
15+ALTER TABLE workspace ADD COLUMN smtp_check_error TEXT;
crates/izlek-core/src/config.rsmodified+77 -9
@@ -51,6 +51,10 @@ database = "izlek.db"
51 # this is the only thing that decides where İzlek binds. It is also the51 # this is the only thing that decides where İzlek binds. It is also the
52 # address mail links fall back to, until an admin sets one in Settings.52 # address mail links fall back to, until an admin sets one in Settings.
53 listen = "127.0.0.1:7654"53 listen = "127.0.0.1:7654"
54+# How long a live-update connection is held before the browser is asked to
55+# reconnect, in seconds. The reconnect is what re-checks the session, so a
56+# revoked sign-in stops receiving within this long.
57+live_seconds = 300
54 "#;58 "#;
55 59
56 /// The default `listen` when the file is silent about it. A file missing this60 /// The default `listen` when the file is silent about it. A file missing this
@@ -63,18 +67,38 @@ listen = "127.0.0.1:7654"
63 /// range, so the kernel never hands it to an outgoing connection either.67 /// range, so the kernel never hands it to an outgoing connection either.
64 const DEFAULT_LISTEN: &str = "127.0.0.1:7654";68 const DEFAULT_LISTEN: &str = "127.0.0.1:7654";
65 69
70+/// How long one live-update connection lasts before the server ends it and the
71+/// browser opens another. Five minutes is a compromise: a stream is
72+/// authenticated once, when it opens, so a session revoked mid-stream keeps
73+/// hearing until the next reconnect — and a reconnect costs one request, so
74+/// doing it every few seconds to shorten that window would be worse than the
75+/// window. Long enough to be cheap, short enough that a revoked session goes
76+/// quiet while the person who revoked it is still watching.
77+const DEFAULT_LIVE_SECONDS: u64 = 300;
78+
66 /// Every optional key, with the comment and default a file missing it is79 /// Every optional key, with the comment and default a file missing it is
67 /// completed with. `database` is not here: it has no default worth guessing,80 /// completed with. `database` is not here: it has no default worth guessing,
68 /// so its absence stops the boot instead.81 /// so its absence stops the boot instead.
69-const OPTIONAL_KEYS: &[(&str, &str)] = &[(82+const OPTIONAL_KEYS: &[(&str, &str)] = &[
70- "listen",83+ (
71- concat!(84+ "listen",
72- "# The address the server listens on. Environment variables are ignored —\n",85+ concat!(
73- "# this is the only thing that decides where İzlek binds. It is also the\n",86+ "# The address the server listens on. Environment variables are ignored —\n",
74- "# address mail links fall back to, until an admin sets one in Settings.\n",87+ "# this is the only thing that decides where İzlek binds. It is also the\n",
75- "listen = \"127.0.0.1:7654\"\n"88+ "# address mail links fall back to, until an admin sets one in Settings.\n",
89+ "listen = \"127.0.0.1:7654\"\n"
90+ ),
76 ),91 ),
77-)];92+ (
93+ "live_seconds",
94+ concat!(
95+ "# How long a live-update connection is held before the browser is asked to\n",
96+ "# reconnect, in seconds. The reconnect is what re-checks the session, so a\n",
97+ "# revoked sign-in stops receiving within this long.\n",
98+ "live_seconds = 300\n"
99+ ),
100+ ),
101+];
78 102
79 /// The shape of `config/izlek.toml`, before the values are checked. Anything103 /// The shape of `config/izlek.toml`, before the values are checked. Anything
80 /// else the file says lands in `other`, which is read for its key names only104 /// else the file says lands in `other`, which is read for its key names only
@@ -83,6 +107,7 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[(
83 struct Toml {107 struct Toml {
84 database: Option<String>,108 database: Option<String>,
85 listen: Option<String>,109 listen: Option<String>,
110+ live_seconds: Option<u64>,
86 #[serde(flatten)]111 #[serde(flatten)]
87 other: std::collections::BTreeMap<String, toml::Value>,112 other: std::collections::BTreeMap<String, toml::Value>,
88 }113 }
@@ -98,6 +123,10 @@ pub struct Config {
98 /// Keys the file sets that nothing here reads, in the order the file123 /// Keys the file sets that nothing here reads, in the order the file
99 /// gives them. Named at startup so a typo is visible.124 /// gives them. Named at startup so a typo is visible.
100 pub ignored: Vec<String>,125 pub ignored: Vec<String>,
126+ /// How long one live-update connection is held open before the browser is
127+ /// asked to reconnect. The reconnect re-authenticates, which is how a
128+ /// session revoked mid-stream stops being fed.
129+ pub live_seconds: u64,
101 /// Whether `config/izlek.toml` did not exist and was just written with the130 /// Whether `config/izlek.toml` did not exist and was just written with the
102 /// development defaults this boot.131 /// development defaults this boot.
103 pub defaulted: bool,132 pub defaulted: bool,
@@ -197,9 +226,22 @@ impl Config {
197 why: format!("{listen:?} is not a host:port address — {err}"),226 why: format!("{listen:?} is not a host:port address — {err}"),
198 })?;227 })?;
199 228
229+ // Zero would mean a stream that ends the moment it opens, which is a
230+ // reconnect loop rather than a live feed; the key is refused rather
231+ // than quietly corrected, because a deployment that meant to say
232+ // "never expire" should find out here and not at three in the morning.
233+ let live_seconds = toml.live_seconds.unwrap_or(DEFAULT_LIVE_SECONDS);
234+ if live_seconds == 0 {
235+ return Err(ConfigError::Invalid {
236+ key: "live_seconds",
237+ why: "0 would close every live connection as soon as it opened".to_string(),
238+ });
239+ }
240+
200 Ok(Config {241 Ok(Config {
201 database: absolute(dir, Path::new(&database)),242 database: absolute(dir, Path::new(&database)),
202 listen,243 listen,
244+ live_seconds,
203 ignored: toml.other.into_keys().collect(),245 ignored: toml.other.into_keys().collect(),
204 defaulted,246 defaulted,
205 })247 })
@@ -393,14 +435,40 @@ mod tests {
393 fn completion_leaves_a_key_that_is_already_there() {435 fn completion_leaves_a_key_that_is_already_there() {
394 let dir = scratch();436 let dir = scratch();
395 std::fs::create_dir_all(dir.join("config")).unwrap();437 std::fs::create_dir_all(dir.join("config")).unwrap();
396- let mine = "database = \"izlek.db\"\nlisten = \"0.0.0.0:8080\"\n";438+ let mine =
439+ "database = \"izlek.db\"\nlisten = \"0.0.0.0:8080\"\nlive_seconds = 30\n";
397 std::fs::write(dir.join(FILE_NAME), mine).unwrap();440 std::fs::write(dir.join(FILE_NAME), mine).unwrap();
398 let config = Config::load_from(&dir).unwrap();441 let config = Config::load_from(&dir).unwrap();
399 assert_eq!(config.listen, "0.0.0.0:8080".parse().unwrap());442 assert_eq!(config.listen, "0.0.0.0:8080".parse().unwrap());
443+ assert_eq!(config.live_seconds, 30);
400 assert_eq!(std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(), mine);444 assert_eq!(std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(), mine);
401 let _ = std::fs::remove_dir_all(&dir);445 let _ = std::fs::remove_dir_all(&dir);
402 }446 }
403 447
448+ /// A live connection that expires instantly is a reconnect loop, so the
449+ /// key is refused rather than silently corrected.
450+ #[test]
451+ fn a_zero_live_window_stops_the_boot_naming_the_key() {
452+ let problem = Config::parse(
453+ "database = \"izlek.db\"\nlive_seconds = 0\n",
454+ Path::new("."),
455+ false,
456+ )
457+ .unwrap_err();
458+ assert!(
459+ matches!(problem, ConfigError::Invalid { key: "live_seconds", .. }),
460+ "{problem:?}"
461+ );
462+ }
463+
464+ /// A file that never mentions the key still boots, on the default.
465+ #[test]
466+ fn a_file_without_a_live_window_takes_the_default() {
467+ let config =
468+ Config::parse("database = \"izlek.db\"\n", Path::new("."), false).unwrap();
469+ assert_eq!(config.live_seconds, 300);
470+ }
471+
404 #[test]472 #[test]
405 fn an_empty_string_is_not_a_value() {473 fn an_empty_string_is_not_a_value() {
406 let problem = Config::parse("database = \" \"\n", Path::new("."), false).unwrap_err();474 let problem = Config::parse("database = \" \"\n", Path::new("."), false).unwrap_err();
crates/izlek-core/src/detail.rsmodified+19 -0
@@ -365,6 +365,25 @@ pub fn moment_label_in(at: OffsetDateTime, offset: UtcOffset) -> String {
365 )365 )
366 }366 }
367 367
368+/// The same label, down to the second.
369+///
370+/// Minutes are the right grain for something that already happened — a comment
371+/// was left at 16:42 and nobody cares which second. They are the wrong grain
372+/// for a moment that has not arrived yet: a retry shown as "16:42" that fires
373+/// at 16:42:47 looks forty-seven seconds broken to whoever is watching the
374+/// clock, and a promise about the future has to be readable against the future
375+/// it promises.
376+pub fn moment_label_with_seconds_in(at: OffsetDateTime, offset: UtcOffset) -> String {
377+ let at = at.to_offset(offset);
378+ format!(
379+ "{} {:02}:{:02}:{:02}",
380+ day_label(at.date()),
381+ at.hour(),
382+ at.minute(),
383+ at.second()
384+ )
385+}
386+
368 /// Parses a stored `User::timezone` value — `"UTC"` or `"UTC+03:00"` /387 /// Parses a stored `User::timezone` value — `"UTC"` or `"UTC+03:00"` /
369 /// `"UTC-05:00"` — into the offset it names. There is no tz-database here388 /// `"UTC-05:00"` — into the offset it names. There is no tz-database here
370 /// (see the settings vocabulary decision), only fixed offsets, so anything389 /// (see the settings vocabulary decision), only fixed offsets, so anything
crates/izlek-core/src/lib.rsmodified+4 -0
@@ -17,6 +17,8 @@ pub mod accounts;
17 #[cfg(feature = "server")]17 #[cfg(feature = "server")]
18 pub mod auth;18 pub mod auth;
19 #[cfg(feature = "server")]19 #[cfg(feature = "server")]
20+pub mod live;
21+#[cfg(feature = "server")]
20 pub mod config;22 pub mod config;
21 #[cfg(feature = "server")]23 #[cfg(feature = "server")]
22 pub mod mail;24 pub mod mail;
@@ -32,6 +34,8 @@ pub use config::{Config, ConfigError};
32 #[cfg(feature = "server")]34 #[cfg(feature = "server")]
33 pub use detail::{DetailReads, load as load_detail};35 pub use detail::{DetailReads, load as load_detail};
34 #[cfg(feature = "server")]36 #[cfg(feature = "server")]
37+pub use live::{Change, Topic};
38+#[cfg(feature = "server")]
35 pub use mail::{Engine as MailEngine, MailError, Mailer, Outgoing};39 pub use mail::{Engine as MailEngine, MailError, Mailer, Outgoing};
36 #[cfg(feature = "server")]40 #[cfg(feature = "server")]
37 pub use store::{Store, StoreError, TursoStore};41 pub use store::{Store, StoreError, TursoStore};
crates/izlek-core/src/live.rsadded+77 -0
@@ -0,0 +1,77 @@
1+//! Committed-write announcements.
2+//!
3+//! A write that committed publishes one [`Change`] per surface it touches,
4+//! and the change carries a topic — never data. That is deliberate: a
5+//! channel that carried rows would need a role check per message, and one
6+//! forgotten filter would leak. A topic cannot leak anything; the woken
7+//! client re-fetches through the ordinary route, and the existing role gate
8+//! answers there.
9+//!
10+//! [`Change::seq`] is a process-local counter, so a client that sees 41 and
11+//! then 43 knows it missed one and can resync instead of rendering a mix of
12+//! before and after.
13+
14+use std::sync::atomic::{AtomicU64, Ordering};
15+
16+/// The surface a committed write touched. One write may touch several: a
17+/// comment is a task's detail and the activity log at once.
18+#[derive(Debug, Clone, PartialEq, Eq)]
19+pub enum Topic {
20+ /// The board: task create, move, delete, save, columns.
21+ Board,
22+ /// One task's detail: comments, subtasks, links, attachments,
23+ /// assignees, deadline.
24+ Task(String),
25+ /// Users, roles, invites, sessions, photos, profile.
26+ Members,
27+ /// The mail queue: `mail_send` rows.
28+ Queue,
29+ /// Mail rules and the decisions they made.
30+ Rules,
31+ /// Workspace settings, sender, limits, public URL.
32+ Settings,
33+ /// The activity and event log.
34+ Activity,
35+}
36+
37+impl Topic {
38+ /// The name the wire uses for this topic: the SSE `event:` field, and
39+ /// the key the role filter decides on.
40+ pub fn kind(&self) -> &'static str {
41+ match self {
42+ Topic::Board => "board",
43+ Topic::Task(_) => "task",
44+ Topic::Members => "members",
45+ Topic::Queue => "queue",
46+ Topic::Rules => "rules",
47+ Topic::Settings => "settings",
48+ Topic::Activity => "activity",
49+ }
50+ }
51+
52+ /// The task this topic is about, when it is about one.
53+ pub fn id(&self) -> Option<&str> {
54+ match self {
55+ Topic::Task(id) => Some(id),
56+ _ => None,
57+ }
58+ }
59+}
60+
61+/// One committed write: which surface changed, and where this change sits
62+/// in the store's sequence. Everything a client needs to know to refresh —
63+/// and nothing about what changed.
64+#[derive(Debug, Clone, PartialEq, Eq)]
65+pub struct Change {
66+ pub topic: Topic,
67+ pub seq: u64,
68+}
69+
70+static SEQ: AtomicU64 = AtomicU64::new(0);
71+
72+/// The next sequence number, starting at 1. Process-local on purpose: the
73+/// sequence exists to catch a dropped event inside one stream, not to order
74+/// two servers.
75+pub fn next_seq() -> u64 {
76+ SEQ.fetch_add(1, Ordering::Relaxed) + 1
77+}
crates/izlek-core/src/mail.rsmodified+22 -0
@@ -92,6 +92,16 @@ pub struct Outgoing {
92 #[async_trait]92 #[async_trait]
93 pub trait Mailer: Send + Sync {93 pub trait Mailer: Send + Sync {
94 async fn send(&self, mail: &Outgoing) -> Result<(), MailError>;94 async fn send(&self, mail: &Outgoing) -> Result<(), MailError>;
95+
96+ /// Asks the mail server whether it would have us, without sending anything
97+ /// to anybody: connect, negotiate TLS, say hello, authenticate, hang up.
98+ ///
99+ /// The default answers yes. That is right for a mailer with no server
100+ /// behind it — the ones the tests hold, which accept everything — and the
101+ /// real SMTP sender overrides it with the handshake.
102+ async fn check(&self) -> Result<(), MailError> {
103+ Ok(())
104+ }
95 }105 }
96 106
97 /// How many times a retryable failure is tried before it is given up on and107 /// How many times a retryable failure is tried before it is given up on and
@@ -171,6 +181,18 @@ impl Engine {
171 ))181 ))
172 }182 }
173 183
184+ /// Asks the mail server whether it would take mail from us, without
185+ /// sending any. Hands back how long the handshake took, the way
186+ /// [`Engine::send_test`] does, so an admin can see a server that answers
187+ /// slowly as well as one that refuses.
188+ pub async fn check_sender(&self) -> std::result::Result<Duration, MailError> {
189+ let started = std::time::Instant::now();
190+ self.mailer.check().await?;
191+ Ok(Duration::milliseconds(
192+ started.elapsed().as_millis().min(i64::MAX as u128) as i64,
193+ ))
194+ }
195+
174 /// Everything one crossing owes. Called after the move has committed, never196 /// Everything one crossing owes. Called after the move has committed, never
175 /// inside it.197 /// inside it.
176 pub async fn on_transition(&self, transition: &Transition) -> crate::store::Result<Report> {198 pub async fn on_transition(&self, transition: &Transition) -> crate::store::Result<Report> {
crates/izlek-core/src/store/mod.rsmodified+46 -0
@@ -68,6 +68,10 @@ pub struct Workspace {
68 /// How the last "send test mail to myself" went, if one has been pressed68 /// How the last "send test mail to myself" went, if one has been pressed
69 /// since the sender was last edited.69 /// since the sender was last edited.
70 pub sender_test: Option<SenderTest>,70 pub sender_test: Option<SenderTest>,
71+ /// How the last handshake with the mail server went, if one has happened
72+ /// since the sender was last edited. See [`SenderCheck`] on why this is
73+ /// not the same thing as `sender_test`.
74+ pub sender_check: Option<SenderCheck>,
71 pub attachment_limit_bytes: u64,75 pub attachment_limit_bytes: u64,
72 pub photo_limit_bytes: u64,76 pub photo_limit_bytes: u64,
73 pub allowed_file_types: Vec<String>,77 pub allowed_file_types: Vec<String>,
@@ -128,6 +132,26 @@ pub struct SenderTest {
128 pub error: Option<String>,132 pub error: Option<String>,
129 }133 }
130 134
135+/// How the last handshake with the mail server went.
136+///
137+/// Not the same fact as [`SenderTest`], and kept apart on purpose. A test sends
138+/// a real message to a real inbox and proves delivery. A check connects,
139+/// negotiates TLS, says hello, authenticates and hangs up — it proves the host,
140+/// the port, the encryption and the password without sending anything to
141+/// anybody. What it cannot prove is that the from-address is one this account
142+/// is allowed to send as, which is the usual reason a login that works is
143+/// followed by mail that bounces.
144+///
145+/// `error` is `None` when the server let us in, and otherwise holds what the
146+/// server said, because "535 authentication failed" is actionable and "it did
147+/// not work" is not.
148+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
149+pub struct SenderCheck {
150+ pub at: OffsetDateTime,
151+ pub took_ms: u64,
152+ pub error: Option<String>,
153+}
154+
131 #[derive(Debug, Clone, PartialEq)]155 #[derive(Debug, Clone, PartialEq)]
132 pub struct NewSender {156 pub struct NewSender {
133 pub host: String,157 pub host: String,
@@ -589,6 +613,16 @@ pub struct Recipient {
589 /// trait a test can wrap and count.613 /// trait a test can wrap and count.
590 #[async_trait]614 #[async_trait]
591 pub trait Store: BoardReads + DetailReads + 'static {615 pub trait Store: BoardReads + DetailReads + 'static {
616+
617+ // -- live updates ------------------------------------------------------
618+
619+ /// A receiver of committed-write announcements. One [`Change`] per
620+ /// write that committed, carrying the topic to re-fetch and no data:
621+ /// the channel cannot say more than the reader may hear, because it
622+ /// says nothing — the woken client re-fetches through the ordinary
623+ /// role-gated route. Sending to zero subscribers is normal and silent,
624+ /// and a slow subscriber's overflow is the client's cue to resync.
625+ fn subscribe(&self) -> tokio::sync::broadcast::Receiver<crate::live::Change>;
592 // -- workspace ---------------------------------------------------------626 // -- workspace ---------------------------------------------------------
593 627
594 /// Claims an empty database: writes the workspace, its first account and628 /// Claims an empty database: writes the workspace, its first account and
@@ -619,6 +653,11 @@ pub trait Store: BoardReads + DetailReads + 'static {
619 /// so what is stored is always about the settings that are stored.653 /// so what is stored is always about the settings that are stored.
620 async fn record_sender_test(&self, workspace_id: &str, test: SenderTest) -> Result<()>;654 async fn record_sender_test(&self, workspace_id: &str, test: SenderTest) -> Result<()>;
621 655
656+ /// Writes down how the last handshake went. Separate from
657+ /// [`Store::record_sender_test`] so a login that worked can never be
658+ /// rendered as a mail that arrived.
659+ async fn record_sender_check(&self, workspace_id: &str, check: SenderCheck) -> Result<()>;
660+
622 /// Reads the sender's password. Only the mailer calls this, and nothing it661 /// Reads the sender's password. Only the mailer calls this, and nothing it
623 /// returns reaches a response body.662 /// returns reaches a response body.
624 async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>>;663 async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>>;
@@ -1030,6 +1069,13 @@ pub trait Store: BoardReads + DetailReads + 'static {
1030 /// Sends owed right now: claimed but never accepted, and due.1069 /// Sends owed right now: claimed but never accepted, and due.
1031 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>>;1070 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>>;
1032 1071
1072+ /// When the next mail falls due, whether or not that is yet.
1073+ ///
1074+ /// The sweep asks this so it can sleep exactly that long instead of waking
1075+ /// on a fixed beat. A beat is what makes a retry promised for 16:42:47 go
1076+ /// out at 16:43: the row was due, and nothing was awake to notice.
1077+ async fn next_due_at(&self) -> Result<Option<OffsetDateTime>>;
1078+
1033 /// Every send a rule has made, newest first, for the admin's trail.1079 /// Every send a rule has made, newest first, for the admin's trail.
1034 async fn sends_for_rule(&self, rule_id: &str, limit: u32) -> Result<Vec<MailSend>>;1080 async fn sends_for_rule(&self, rule_id: &str, limit: u32) -> Result<Vec<MailSend>>;
1035 1081
crates/izlek-core/src/store/turso_store.rsmodified+241 -11
@@ -18,9 +18,11 @@ use super::{
18 ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, CommentWritten, Deletion,18 ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, CommentWritten, Deletion,
19 Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, MailSend,19 Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, MailSend,
20 NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState,20 NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState,
21- SenderTest, Session, SigninLink, Store, StoreError, TaskCreated, Trigger, User, Workspace,21+ SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, TaskCreated, Trigger, User,
22+ Workspace,
22 };23 };
23 use crate::Role;24 use crate::Role;
25+use crate::live::{Change, Topic};
24 use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition};26 use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition};
25 use crate::detail::{27 use crate::detail::{
26 ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, FileLine,28 ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, FileLine,
@@ -35,6 +37,7 @@ use time::macros::format_description;
35 /// second file is for the day there is data worth keeping.37 /// second file is for the day there is data worth keeping.
36 const MIGRATIONS: &[(i64, &str)] = &[38 const MIGRATIONS: &[(i64, &str)] = &[
37 (1, include_str!("../../migrations/0001_init.sql")),39 (1, include_str!("../../migrations/0001_init.sql")),
40+ (2, include_str!("../../migrations/0002_sender_check.sql")),
38 ];41 ];
39 42
40 /// The board a fresh workspace gets, and its columns. `Done` is the column43 /// The board a fresh workspace gets, and its columns. `Done` is the column
@@ -57,9 +60,28 @@ pub struct TursoStore {
57 /// exposed through the `Store` trait — callers keep passing and receiving60 /// exposed through the `Store` trait — callers keep passing and receiving
58 /// plaintext, this field is the detail that makes the row not be one.61 /// plaintext, this field is the detail that makes the row not be one.
59 key: secret::Key,62 key: secret::Key,
63+ /// Where committed writes are announced. Held as the sender so the store
64+ /// can hand out a receiver per subscriber; nothing is ever read from here
65+ /// by the store itself.
66+ live: tokio::sync::broadcast::Sender<Change>,
60 }67 }
61 68
62 impl TursoStore {69 impl TursoStore {
70+ /// Announces a committed write. Called only once the write is durable —
71+ /// after commit for a transaction, and never on a path that returned an
72+ /// error — because a subscriber's whole job is to re-read, and waking it
73+ /// before the row lands makes it read the past.
74+ ///
75+ /// A send with no subscribers returns `Err`, which is the ordinary state
76+ /// of a server nobody is looking at. It is dropped on purpose: an
77+ /// announcement nobody is waiting for is not a problem, and logging it
78+ /// would fill the log with the sound of an idle app.
79+ fn announce(&self, topics: impl IntoIterator<Item = Topic>) {
80+ for topic in topics {
81+ let _ = self.live.send(Change { topic, seq: crate::live::next_seq() });
82+ }
83+ }
84+
63 /// Opens (creating if needed) the database at `path` and brings the schema85 /// Opens (creating if needed) the database at `path` and brings the schema
64 /// up to date. `:memory:` gives a throwaway database for tests.86 /// up to date. `:memory:` gives a throwaway database for tests.
65 pub async fn open(path: &str) -> Result<Self> {87 pub async fn open(path: &str) -> Result<Self> {
@@ -88,7 +110,13 @@ impl TursoStore {
88 restrict_if_present(&sibling(path, "-shm"))?;110 restrict_if_present(&sibling(path, "-shm"))?;
89 }111 }
90 let key = load_key(path)?;112 let key = load_key(path)?;
91- let store = Self { conn: tokio::sync::Mutex::new(conn), db, key };113+ // 256 is deep enough that a client which pauses for a moment catches
114+ // up without noticing, and shallow enough that one wedged subscriber
115+ // cannot pin an unbounded backlog. Overflowing it is not a failure:
116+ // the reader is told it lagged and resyncs, which is cheaper than the
117+ // memory a larger buffer would cost to avoid saying so.
118+ let (live, _) = tokio::sync::broadcast::channel(256);
119+ let store = Self { conn: tokio::sync::Mutex::new(conn), db, key, live };
92 store.migrate().await?;120 store.migrate().await?;
93 store.encrypt_plaintext_passwords().await?;121 store.encrypt_plaintext_passwords().await?;
94 Ok(store)122 Ok(store)
@@ -560,6 +588,14 @@ fn workspace_from(row: &Row) -> Result<Workspace> {
560 }),588 }),
561 None => None,589 None => None,
562 },590 },
591+ sender_check: match opt_stamp(row, 16)? {
592+ Some(at) => Some(SenderCheck {
593+ at,
594+ took_ms: row.get::<i64>(17).map_err(backend)?.max(0) as u64,
595+ error: opt_text(row, 18)?,
596+ }),
597+ None => None,
598+ },
563 public_url: opt_text(row, 15)?,599 public_url: opt_text(row, 15)?,
564 })600 })
565 }601 }
@@ -571,7 +607,8 @@ const WORKSPACE_COLUMNS: &str = "id, name, created_at, attachment_limit_bytes, \
571 allowed_file_types, photo_limit_bytes, smtp_host, smtp_port, smtp_username, \607 allowed_file_types, photo_limit_bytes, smtp_host, smtp_port, smtp_username, \
572 smtp_from_name, smtp_from_address, \608 smtp_from_name, smtp_from_address, \
573 (smtp_password IS NOT NULL AND smtp_password <> ''), \609 (smtp_password IS NOT NULL AND smtp_password <> ''), \
574- smtp_test_at, smtp_test_ms, smtp_test_error, public_url";610+ smtp_test_at, smtp_test_ms, smtp_test_error, public_url, \
611+ smtp_check_at, smtp_check_ms, smtp_check_error";
575 612
576 fn user_from(row: &Row) -> Result<User> {613 fn user_from(row: &Row) -> Result<User> {
577 Ok(User {614 Ok(User {
@@ -624,6 +661,10 @@ fn fold_email(email: &str) -> String {
624 661
625 #[async_trait]662 #[async_trait]
626 impl Store for TursoStore {663 impl Store for TursoStore {
664+ fn subscribe(&self) -> tokio::sync::broadcast::Receiver<Change> {
665+ self.live.subscribe()
666+ }
667+
627 async fn claim_workspace(668 async fn claim_workspace(
628 &self,669 &self,
629 workspace_name: &str,670 workspace_name: &str,
@@ -720,6 +761,9 @@ impl Store for TursoStore {
720 });761 });
721 }762 }
722 }763 }
764+ // First write in the database's life: settings, members and the
765+ // board all begin here, so a subscriber on any of the three wakes.
766+ self.announce([Topic::Settings, Topic::Members, Topic::Board]);
723 767
724 let workspace = self.workspace().await?.ok_or(StoreError::NotFound)?;768 let workspace = self.workspace().await?.ok_or(StoreError::NotFound)?;
725 let admin = self.user(&admin_id).await?.ok_or(StoreError::NotFound)?;769 let admin = self.user(&admin_id).await?.ok_or(StoreError::NotFound)?;
@@ -764,7 +808,8 @@ impl Store for TursoStore {
764 "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \808 "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \
765 smtp_password = COALESCE(?4, smtp_password), smtp_from_name = ?5, \809 smtp_password = COALESCE(?4, smtp_password), smtp_from_name = ?5, \
766 smtp_from_address = ?6, smtp_test_at = NULL, smtp_test_ms = NULL, \810 smtp_from_address = ?6, smtp_test_at = NULL, smtp_test_ms = NULL, \
767- smtp_test_error = NULL WHERE id = ?7",811+ smtp_test_error = NULL, smtp_check_at = NULL, smtp_check_ms = NULL, \
812+ smtp_check_error = NULL WHERE id = ?7",
768 params![813 params![
769 sender.host,814 sender.host,
770 sender.port as i64,815 sender.port as i64,
@@ -777,6 +822,28 @@ impl Store for TursoStore {
777 )822 )
778 .await823 .await
779 .map_err(backend)?;824 .map_err(backend)?;
825+ drop(conn);
826+ self.announce([Topic::Settings]);
827+ Ok(())
828+ }
829+
830+ async fn record_sender_check(&self, workspace_id: &str, check: SenderCheck) -> Result<()> {
831+ let conn = self.conn.lock().await;
832+ conn
833+ .execute(
834+ "UPDATE workspace SET smtp_check_at = ?1, smtp_check_ms = ?2, \
835+ smtp_check_error = ?3 WHERE id = ?4",
836+ params![
837+ stamp(check.at)?,
838+ check.took_ms as i64,
839+ check.error,
840+ workspace_id
841+ ],
842+ )
843+ .await
844+ .map_err(backend)?;
845+ drop(conn);
846+ self.announce([Topic::Settings]);
780 Ok(())847 Ok(())
781 }848 }
782 849
@@ -795,6 +862,8 @@ impl Store for TursoStore {
795 )862 )
796 .await863 .await
797 .map_err(backend)?;864 .map_err(backend)?;
865+ drop(conn);
866+ self.announce([Topic::Settings]);
798 Ok(())867 Ok(())
799 }868 }
800 869
@@ -828,6 +897,8 @@ impl Store for TursoStore {
828 )897 )
829 .await898 .await
830 .map_err(backend)?;899 .map_err(backend)?;
900+ drop(conn);
901+ self.announce([Topic::Settings]);
831 Ok(())902 Ok(())
832 }903 }
833 904
@@ -854,6 +925,8 @@ impl Store for TursoStore {
854 )925 )
855 .await926 .await
856 .map_err(backend)?;927 .map_err(backend)?;
928+ drop(conn);
929+ self.announce([Topic::Settings]);
857 Ok(())930 Ok(())
858 }931 }
859 932
@@ -892,6 +965,7 @@ impl Store for TursoStore {
892 backend(e)965 backend(e)
893 }966 }
894 })?;967 })?;
968+ self.announce([Topic::Members]);
895 self.user(&id).await?.ok_or(StoreError::NotFound)969 self.user(&id).await?.ok_or(StoreError::NotFound)
896 }970 }
897 971
@@ -955,6 +1029,8 @@ impl Store for TursoStore {
955 if n == 0 {1029 if n == 0 {
956 Err(StoreError::NotFound)1030 Err(StoreError::NotFound)
957 } else {1031 } else {
1032+ drop(conn);
1033+ self.announce([Topic::Members]);
958 Ok(())1034 Ok(())
959 }1035 }
960 }1036 }
@@ -971,6 +1047,8 @@ impl Store for TursoStore {
971 if n == 0 {1047 if n == 0 {
972 Err(StoreError::NotFound)1048 Err(StoreError::NotFound)
973 } else {1049 } else {
1050+ drop(conn);
1051+ self.announce([Topic::Members]);
974 Ok(())1052 Ok(())
975 }1053 }
976 }1054 }
@@ -987,6 +1065,8 @@ impl Store for TursoStore {
987 if n == 0 {1065 if n == 0 {
988 Err(StoreError::NotFound)1066 Err(StoreError::NotFound)
989 } else {1067 } else {
1068+ drop(conn);
1069+ self.announce([Topic::Members]);
990 Ok(())1070 Ok(())
991 }1071 }
992 }1072 }
@@ -1003,6 +1083,8 @@ impl Store for TursoStore {
1003 if n == 0 {1083 if n == 0 {
1004 Err(StoreError::NotFound)1084 Err(StoreError::NotFound)
1005 } else {1085 } else {
1086+ drop(conn);
1087+ self.announce([Topic::Members]);
1006 Ok(())1088 Ok(())
1007 }1089 }
1008 }1090 }
@@ -1046,6 +1128,8 @@ impl Store for TursoStore {
1046 if n == 0 {1128 if n == 0 {
1047 Err(StoreError::NotFound)1129 Err(StoreError::NotFound)
1048 } else {1130 } else {
1131+ drop(conn);
1132+ self.announce([Topic::Members]);
1049 Ok(())1133 Ok(())
1050 }1134 }
1051 }1135 }
@@ -1069,6 +1153,8 @@ impl Store for TursoStore {
1069 if n == 0 {1153 if n == 0 {
1070 Err(StoreError::NotFound)1154 Err(StoreError::NotFound)
1071 } else {1155 } else {
1156+ drop(conn);
1157+ self.announce([Topic::Members]);
1072 Ok(())1158 Ok(())
1073 }1159 }
1074 }1160 }
@@ -1085,6 +1171,8 @@ impl Store for TursoStore {
1085 if n == 0 {1171 if n == 0 {
1086 Err(StoreError::NotFound)1172 Err(StoreError::NotFound)
1087 } else {1173 } else {
1174+ drop(conn);
1175+ self.announce([Topic::Members]);
1088 Ok(())1176 Ok(())
1089 }1177 }
1090 }1178 }
@@ -1101,6 +1189,8 @@ impl Store for TursoStore {
1101 if n == 0 {1189 if n == 0 {
1102 Err(StoreError::NotFound)1190 Err(StoreError::NotFound)
1103 } else {1191 } else {
1192+ drop(conn);
1193+ self.announce([Topic::Members]);
1104 Ok(())1194 Ok(())
1105 }1195 }
1106 }1196 }
@@ -1128,6 +1218,7 @@ impl Store for TursoStore {
1128 )1218 )
1129 .await1219 .await
1130 .map_err(backend)?;1220 .map_err(backend)?;
1221+ self.announce([Topic::Members]);
1131 match self1222 match self
1132 .one_row(1223 .one_row(
1133 "SELECT id, user_id, created_at, expires_at, used_at FROM signin_link WHERE id = ?1",1224 "SELECT id, user_id, created_at, expires_at, used_at FROM signin_link WHERE id = ?1",
@@ -1170,6 +1261,9 @@ impl Store for TursoStore {
1170 .await1261 .await
1171 .map_err(backend)?;1262 .map_err(backend)?;
1172 tx.commit().await.map_err(backend)?;1263 tx.commit().await.map_err(backend)?;
1264+ if n == 1 {
1265+ self.announce([Topic::Members]);
1266+ }
1173 Ok(n == 1)1267 Ok(n == 1)
1174 }1268 }
1175 1269
@@ -1196,6 +1290,7 @@ impl Store for TursoStore {
1196 )1290 )
1197 .await1291 .await
1198 .map_err(backend)?;1292 .map_err(backend)?;
1293+ self.announce([Topic::Members]);
1199 let sql = format!("SELECT {SESSION_COLUMNS} FROM session WHERE id = ?1");1294 let sql = format!("SELECT {SESSION_COLUMNS} FROM session WHERE id = ?1");
1200 match self.one_row(&sql, params![id]).await? {1295 match self.one_row(&sql, params![id]).await? {
1201 Some(row) => session_from(&row),1296 Some(row) => session_from(&row),
@@ -1233,21 +1328,30 @@ impl Store for TursoStore {
1233 if n == 0 {1328 if n == 0 {
1234 Err(StoreError::NotFound)1329 Err(StoreError::NotFound)
1235 } else {1330 } else {
1331+ drop(conn);
1332+ self.announce([Topic::Members]);
1236 Ok(())1333 Ok(())
1237 }1334 }
1238 }1335 }
1239 1336
1240 async fn revoke_sessions_for_user(&self, user_id: &str, at: OffsetDateTime) -> Result<u64> {1337 async fn revoke_sessions_for_user(&self, user_id: &str, at: OffsetDateTime) -> Result<u64> {
1241 let conn = self.conn.lock().await;1338 let conn = self.conn.lock().await;
1242- conn1339+ let n = conn
1243 .execute(1340 .execute(
1244 "UPDATE session SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL",1341 "UPDATE session SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL",
1245 params![stamp(at)?, user_id],1342 params![stamp(at)?, user_id],
1246 )1343 )
1247 .await1344 .await
1248- .map_err(backend)1345+ .map_err(backend)?;
1346+ drop(conn);
1347+ self.announce([Topic::Members]);
1348+ Ok(n)
1249 }1349 }
1250 1350
1351+ // The three auth-attempt methods below announce nothing, alone among the
1352+ // writes here. They are rate-limit bookkeeping that no surface renders, and
1353+ // announcing them would wake every connected client on every failed
1354+ // sign-in — traffic in exchange for a screen that would look identical.
1251 async fn record_auth_attempt(&self, bucket: &str, at: OffsetDateTime) -> Result<()> {1355 async fn record_auth_attempt(&self, bucket: &str, at: OffsetDateTime) -> Result<()> {
1252 let conn = self.conn.lock().await;1356 let conn = self.conn.lock().await;
1253 conn1357 conn
@@ -1317,6 +1421,8 @@ impl Store for TursoStore {
1317 )1421 )
1318 .await1422 .await
1319 .map_err(backend)?;1423 .map_err(backend)?;
1424+ drop(conn);
1425+ self.announce([Topic::Board]);
1320 Ok(Column {1426 Ok(Column {
1321 id,1427 id,
1322 name: name.to_string(),1428 name: name.to_string(),
@@ -1473,6 +1579,8 @@ impl Store for TursoStore {
1473 };1579 };
1474 tx.commit().await.map_err(backend)?;1580 tx.commit().await.map_err(backend)?;
1475 1581
1582+ // Task birth touches the board, the task page and the feed at once.
1583+ self.announce([Topic::Board, Topic::Task(id.clone()), Topic::Activity]);
1476 let (task_key, position) = written;1584 let (task_key, position) = written;
1477 Ok(TaskCreated {1585 Ok(TaskCreated {
1478 row: TaskRow {1586 row: TaskRow {
@@ -1572,6 +1680,7 @@ impl Store for TursoStore {
1572 match outcome {1680 match outcome {
1573 Ok(Ok(())) => {1681 Ok(Ok(())) => {
1574 tx.commit().await.map_err(backend)?;1682 tx.commit().await.map_err(backend)?;
1683+ self.announce([Topic::Board, Topic::Task(task_id.to_string())]);
1575 Ok(())1684 Ok(())
1576 }1685 }
1577 Ok(Err(refused)) => {1686 Ok(Err(refused)) => {
@@ -1614,25 +1723,33 @@ impl Store for TursoStore {
1614 1723
1615 async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()> {1724 async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()> {
1616 let conn = self.conn.lock().await;1725 let conn = self.conn.lock().await;
1617- conn1726+ let n = conn
1618 .execute(1727 .execute(
1619 "INSERT OR IGNORE INTO task_assignee (task_id, user_id) VALUES (?1, ?2)",1728 "INSERT OR IGNORE INTO task_assignee (task_id, user_id) VALUES (?1, ?2)",
1620 params![task_id, user_id],1729 params![task_id, user_id],
1621 )1730 )
1622 .await1731 .await
1623 .map_err(backend)?;1732 .map_err(backend)?;
1733+ drop(conn);
1734+ if n > 0 {
1735+ self.announce([Topic::Task(task_id.to_string())]);
1736+ }
1624 Ok(())1737 Ok(())
1625 }1738 }
1626 1739
1627 async fn unassign_task(&self, task_id: &str, user_id: &str) -> Result<()> {1740 async fn unassign_task(&self, task_id: &str, user_id: &str) -> Result<()> {
1628 let conn = self.conn.lock().await;1741 let conn = self.conn.lock().await;
1629- conn1742+ let n = conn
1630 .execute(1743 .execute(
1631 "DELETE FROM task_assignee WHERE task_id = ?1 AND user_id = ?2",1744 "DELETE FROM task_assignee WHERE task_id = ?1 AND user_id = ?2",
1632 params![task_id, user_id],1745 params![task_id, user_id],
1633 )1746 )
1634 .await1747 .await
1635 .map_err(backend)?;1748 .map_err(backend)?;
1749+ drop(conn);
1750+ if n > 0 {
1751+ self.announce([Topic::Task(task_id.to_string())]);
1752+ }
1636 Ok(())1753 Ok(())
1637 }1754 }
1638 1755
@@ -1734,7 +1851,16 @@ impl Store for TursoStore {
1734 .await;1851 .await;
1735 1852
1736 match written {1853 match written {
1737- Ok(true) => tx.commit().await.map_err(backend),1854+ Ok(true) => {
1855+ tx.commit().await.map_err(backend)?;
1856+ // An edge is visible from both endpoints and on the board.
1857+ self.announce([
1858+ Topic::Board,
1859+ Topic::Task(blocked_task_id.to_string()),
1860+ Topic::Task(blocking_task_id.to_string()),
1861+ ]);
1862+ Ok(())
1863+ }
1738 Ok(false) => {1864 Ok(false) => {
1739 let _ = tx.rollback().await;1865 let _ = tx.rollback().await;
1740 Err(StoreError::Cycle)1866 Err(StoreError::Cycle)
@@ -1753,7 +1879,7 @@ impl Store for TursoStore {
1753 at: OffsetDateTime,1879 at: OffsetDateTime,
1754 ) -> Result<()> {1880 ) -> Result<()> {
1755 let conn = self.conn.lock().await;1881 let conn = self.conn.lock().await;
1756- conn1882+ let n = conn
1757 .execute(1883 .execute(
1758 "UPDATE task_dependency SET cleared_at = ?3 \1884 "UPDATE task_dependency SET cleared_at = ?3 \
1759 WHERE blocked_task_id = ?1 AND blocking_task_id = ?2 AND cleared_at IS NULL",1885 WHERE blocked_task_id = ?1 AND blocking_task_id = ?2 AND cleared_at IS NULL",
@@ -1761,6 +1887,14 @@ impl Store for TursoStore {
1761 )1887 )
1762 .await1888 .await
1763 .map_err(backend)?;1889 .map_err(backend)?;
1890+ drop(conn);
1891+ if n > 0 {
1892+ self.announce([
1893+ Topic::Board,
1894+ Topic::Task(blocked_task_id.to_string()),
1895+ Topic::Task(blocking_task_id.to_string()),
1896+ ]);
1897+ }
1764 Ok(())1898 Ok(())
1765 }1899 }
1766 1900
@@ -1810,6 +1944,7 @@ impl Store for TursoStore {
1810 }1944 }
1811 tx.commit().await.map_err(backend)?;1945 tx.commit().await.map_err(backend)?;
1812 1946
1947+ self.announce([Topic::Task(task_id.to_string()), Topic::Activity]);
1813 Ok(CommentWritten {1948 Ok(CommentWritten {
1814 comment_id,1949 comment_id,
1815 activity_id,1950 activity_id,
@@ -1839,6 +1974,8 @@ impl Store for TursoStore {
1839 )1974 )
1840 .await1975 .await
1841 .map_err(backend)?;1976 .map_err(backend)?;
1977+ drop(conn);
1978+ self.announce([Topic::Task(new.task_id.to_string())]);
1842 Ok(id)1979 Ok(id)
1843 }1980 }
1844 1981
@@ -1889,11 +2026,25 @@ impl Store for TursoStore {
1889 }2026 }
1890 2027
1891 async fn delete_attachment(&self, id: &str) -> Result<bool> {2028 async fn delete_attachment(&self, id: &str) -> Result<bool> {
2029+ // Which task loses the file has to be read before the row goes: after
2030+ // the delete there is nothing left to ask, and a detail panel that is
2031+ // never told still shows the attachment.
2032+ let owner = self
2033+ .one_row("SELECT task_id FROM attachment WHERE id = ?1", params![id])
2034+ .await?
2035+ .map(|row| row.get::<String>(0).map_err(backend))
2036+ .transpose()?;
1892 let conn = self.conn.lock().await;2037 let conn = self.conn.lock().await;
1893 let gone = conn2038 let gone = conn
1894 .execute("DELETE FROM attachment WHERE id = ?1", params![id])2039 .execute("DELETE FROM attachment WHERE id = ?1", params![id])
1895 .await2040 .await
1896 .map_err(backend)?;2041 .map_err(backend)?;
2042+ drop(conn);
2043+ if gone > 0
2044+ && let Some(task_id) = owner
2045+ {
2046+ self.announce([Topic::Task(task_id)]);
2047+ }
1897 Ok(gone > 0)2048 Ok(gone > 0)
1898 }2049 }
1899 2050
@@ -1969,7 +2120,16 @@ impl Store for TursoStore {
1969 .await;2120 .await;
1970 2121
1971 match written {2122 match written {
1972- Ok(Some(ids)) => tx.commit().await.map(|_| ids).map_err(backend),2123+ Ok(Some(ids)) => {
2124+ tx.commit().await.map_err(backend)?;
2125+ // An edit shows on the card face as well as in the panel.
2126+ self.announce([
2127+ Topic::Board,
2128+ Topic::Task(task_id.to_string()),
2129+ Topic::Activity,
2130+ ]);
2131+ Ok(ids)
2132+ }
1973 Ok(None) => {2133 Ok(None) => {
1974 let _ = tx.rollback().await;2134 let _ = tx.rollback().await;
1975 Err(StoreError::NotFound)2135 Err(StoreError::NotFound)
@@ -2148,6 +2308,14 @@ impl Store for TursoStore {
2148 match written {2308 match written {
2149 Ok(Outcome::Wrote) => {2309 Ok(Outcome::Wrote) => {
2150 tx.commit().await.map_err(backend)?;2310 tx.commit().await.map_err(backend)?;
2311+ // Past the commit, so a woken client re-reads the move rather
2312+ // than the state before it. The rolled-back arms below say
2313+ // nothing on purpose: nothing changed to re-read.
2314+ self.announce([
2315+ Topic::Board,
2316+ Topic::Task(task_id.to_string()),
2317+ Topic::Activity,
2318+ ]);
2151 Ok(Moved::Recorded(Transition {2319 Ok(Moved::Recorded(Transition {
2152 id: transition_id,2320 id: transition_id,
2153 task_id: task_id.to_string(),2321 task_id: task_id.to_string(),
@@ -2332,6 +2500,13 @@ impl Store for TursoStore {
2332 match written {2500 match written {
2333 Ok(Some(deletion)) => {2501 Ok(Some(deletion)) => {
2334 tx.commit().await.map_err(backend)?;2502 tx.commit().await.map_err(backend)?;
2503+ // The card left the board and its detail panel is now a page
2504+ // about nothing — both need to hear, and only after commit.
2505+ self.announce([
2506+ Topic::Board,
2507+ Topic::Task(task_id.to_string()),
2508+ Topic::Activity,
2509+ ]);
2335 Ok(deletion)2510 Ok(deletion)
2336 }2511 }
2337 Ok(None) => {2512 Ok(None) => {
@@ -2444,6 +2619,9 @@ impl Store for TursoStore {
2444 )2619 )
2445 .await2620 .await
2446 .map_err(backend)?;2621 .map_err(backend)?;
2622+ drop(conn);
2623+ // Task-scoped: the task's own trail and the workspace feed both grew.
2624+ self.announce([Topic::Activity, Topic::Task(task_id.to_string())]);
2447 Ok(id)2625 Ok(id)
2448 }2626 }
2449 2627
@@ -2464,6 +2642,9 @@ impl Store for TursoStore {
2464 )2642 )
2465 .await2643 .await
2466 .map_err(backend)?;2644 .map_err(backend)?;
2645+ drop(conn);
2646+ // Workspace-wide, belonging to no task — the feed only.
2647+ self.announce([Topic::Activity]);
2467 Ok(id)2648 Ok(id)
2468 }2649 }
2469 2650
@@ -2501,6 +2682,7 @@ impl Store for TursoStore {
2501 )2682 )
2502 .await2683 .await
2503 .map_err(backend)?;2684 .map_err(backend)?;
2685+ self.announce([Topic::Rules]);
2504 let sql = format!("SELECT {RULE_COLUMNS} FROM mail_rule WHERE id = ?1");2686 let sql = format!("SELECT {RULE_COLUMNS} FROM mail_rule WHERE id = ?1");
2505 match self.one_row(&sql, params![id]).await? {2687 match self.one_row(&sql, params![id]).await? {
2506 Some(row) => rule_from(&row),2688 Some(row) => rule_from(&row),
@@ -2552,6 +2734,8 @@ impl Store for TursoStore {
2552 if n == 0 {2734 if n == 0 {
2553 return Err(StoreError::NotFound);2735 return Err(StoreError::NotFound);
2554 }2736 }
2737+ drop(conn);
2738+ self.announce([Topic::Rules]);
2555 Ok(())2739 Ok(())
2556 }2740 }
2557 2741
@@ -2646,6 +2830,8 @@ impl Store for TursoStore {
2646 if n == 0 {2830 if n == 0 {
2647 return Err(StoreError::NotFound);2831 return Err(StoreError::NotFound);
2648 }2832 }
2833+ drop(conn);
2834+ self.announce([Topic::Rules]);
2649 Ok(())2835 Ok(())
2650 }2836 }
2651 2837
@@ -2660,6 +2846,9 @@ impl Store for TursoStore {
2660 if n == 0 {2846 if n == 0 {
2661 return Err(StoreError::NotFound);2847 return Err(StoreError::NotFound);
2662 }2848 }
2849+ drop(conn);
2850+ // The rule's queued mail cascaded away with it, so the queue moved too.
2851+ self.announce([Topic::Rules, Topic::Queue]);
2663 Ok(())2852 Ok(())
2664 }2853 }
2665 2854
@@ -2720,6 +2909,8 @@ impl Store for TursoStore {
2720 if n == 0 {2909 if n == 0 {
2721 return Ok(None);2910 return Ok(None);
2722 }2911 }
2912+ // A mail joined the queue, so the queue panel is out of date.
2913+ self.announce([Topic::Queue]);
2723 let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");2914 let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");
2724 match self.one_row(&sql, params![id]).await? {2915 match self.one_row(&sql, params![id]).await? {
2725 Some(row) => send_from(&row).map(Some),2916 Some(row) => send_from(&row).map(Some),
@@ -2747,6 +2938,9 @@ impl Store for TursoStore {
2747 )2938 )
2748 .await2939 .await
2749 .map_err(backend)?;2940 .map_err(backend)?;
2941+ // Two surfaces at once: the invite is a queued mail, and an invited
2942+ // person shows up in the members list before they ever sign in.
2943+ self.announce([Topic::Queue, Topic::Members]);
2750 let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");2944 let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");
2751 match self.one_row(&sql, params![id]).await? {2945 match self.one_row(&sql, params![id]).await? {
2752 Some(row) => send_from(&row),2946 Some(row) => send_from(&row),
@@ -2774,6 +2968,7 @@ impl Store for TursoStore {
2774 )2968 )
2775 .await2969 .await
2776 .map_err(backend)?;2970 .map_err(backend)?;
2971+ self.announce([Topic::Queue]);
2777 let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");2972 let sql = format!("SELECT {SEND_COLUMNS} FROM mail_send WHERE id = ?1");
2778 match self.one_row(&sql, params![id]).await? {2973 match self.one_row(&sql, params![id]).await? {
2779 Some(row) => send_from(&row),2974 Some(row) => send_from(&row),
@@ -2796,6 +2991,11 @@ impl Store for TursoStore {
2796 if n == 0 {2991 if n == 0 {
2797 return Err(StoreError::NotFound);2992 return Err(StoreError::NotFound);
2798 }2993 }
2994+ // The connection guard goes first: announcing is a send on a channel
2995+ // whose subscribers may turn round and read this store, and holding
2996+ // the single connection while they do is how that deadlocks.
2997+ drop(conn);
2998+ self.announce([Topic::Queue]);
2799 Ok(())2999 Ok(())
2800 }3000 }
2801 3001
@@ -2831,6 +3031,10 @@ impl Store for TursoStore {
2831 if n == 0 {3031 if n == 0 {
2832 return Err(StoreError::NotFound);3032 return Err(StoreError::NotFound);
2833 }3033 }
3034+ drop(conn);
3035+ // The attempt counter and the next-try time both just moved, and the
3036+ // queue panel renders both.
3037+ self.announce([Topic::Queue]);
2834 Ok(())3038 Ok(())
2835 }3039 }
2836 3040
@@ -2857,9 +3061,30 @@ impl Store for TursoStore {
2857 if n == 0 {3061 if n == 0 {
2858 return Err(StoreError::NotFound);3062 return Err(StoreError::NotFound);
2859 }3063 }
3064+ drop(conn);
3065+ self.announce([Topic::Queue]);
2860 Ok(())3066 Ok(())
2861 }3067 }
2862 3068
3069+ async fn next_due_at(&self) -> Result<Option<OffsetDateTime>> {
3070+ let conn = self.conn.lock().await;
3071+ let mut rows = conn
3072+ .query(
3073+ "SELECT MIN(next_attempt_at) FROM mail_send WHERE next_attempt_at IS NOT NULL",
3074+ (),
3075+ )
3076+ .await
3077+ .map_err(backend)?;
3078+ let Some(row) = rows.next().await.map_err(backend)? else {
3079+ return Ok(None);
3080+ };
3081+ // MIN over no rows is one row holding NULL, not an empty result.
3082+ match row.get_value(0).map_err(backend)? {
3083+ Value::Text(at) => parse_stamp(&at).map(Some),
3084+ _ => Ok(None),
3085+ }
3086+ }
3087+
2863 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>> {3088 async fn sends_owed(&self, now: OffsetDateTime, limit: u32) -> Result<Vec<MailSend>> {
2864 let conn = self.conn.lock().await;3089 let conn = self.conn.lock().await;
2865 let sql = format!(3090 let sql = format!(
@@ -2922,6 +3147,8 @@ impl Store for TursoStore {
2922 )3147 )
2923 .await3148 .await
2924 .map_err(backend)?;3149 .map_err(backend)?;
3150+ drop(conn);
3151+ self.announce([Topic::Queue]);
2925 Ok(())3152 Ok(())
2926 }3153 }
2927 3154
@@ -2948,6 +3175,9 @@ impl Store for TursoStore {
2948 )3175 )
2949 .await3176 .await
2950 .map_err(backend)?;3177 .map_err(backend)?;
3178+ drop(conn);
3179+ // A decision is what the rules page's decisions tab renders.
3180+ self.announce([Topic::Rules]);
2951 Ok(())3181 Ok(())
2952 }3182 }
2953 3183
crates/izlek-core/tests/store.rsmodified+257 -4
@@ -101,14 +101,18 @@ async fn migrations_apply_once_and_survive_reopen() {
101 let path = dir.join("izlek.db").to_string_lossy().into_owned();101 let path = dir.join("izlek.db").to_string_lossy().into_owned();
102 102
103 let first = TursoStore::open(&path).await.unwrap();103 let first = TursoStore::open(&path).await.unwrap();
104- assert_eq!(first.schema_version().await.unwrap(), 1);104+ // Whatever the newest migration is — pinning the number here only means
105+ // editing this line every time one is added, which tests the constant
106+ // rather than the behaviour.
107+ let applied = first.schema_version().await.unwrap();
108+ assert!(applied >= 1, "no migration applied at all");
105 claim(&first).await;109 claim(&first).await;
106 drop(first);110 drop(first);
107 111
108- // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and112+ // Re-opening must not re-run a migration (0001's CREATE TABLE would fail)
109- // must not lose what the first open wrote.113+ // and must not lose what the first open wrote.
110 let second = TursoStore::open(&path).await.unwrap();114 let second = TursoStore::open(&path).await.unwrap();
111- assert_eq!(second.schema_version().await.unwrap(), 1);115+ assert_eq!(second.schema_version().await.unwrap(), applied);
112 assert_eq!(second.workspace().await.unwrap().unwrap().name, "İzlek");116 assert_eq!(second.workspace().await.unwrap().unwrap().name, "İzlek");
113 drop(second);117 drop(second);
114 let _ = std::fs::remove_dir_all(&dir);118 let _ = std::fs::remove_dir_all(&dir);
@@ -5715,3 +5719,252 @@ async fn a_stored_address_is_the_one_mail_links_point_at() {
5715 );5719 );
5716 let _ = std::fs::remove_dir_all(&dir);5720 let _ = std::fs::remove_dir_all(&dir);
5717 }5721 }
5722+
5723+// -- live announcements -----------------------------------------------------
5724+
5725+/// Drains whatever the store has announced so far into the set of topic names.
5726+/// `try_recv` rather than `recv` on purpose: the point is what has ALREADY been
5727+/// said by the time the write returned, not what might arrive later.
5728+fn announced(rx: &mut tokio::sync::broadcast::Receiver<izlek_core::Change>) -> Vec<String> {
5729+ let mut seen = Vec::new();
5730+ while let Ok(change) = rx.try_recv() {
5731+ seen.push(change.topic.kind().to_string());
5732+ }
5733+ seen
5734+}
5735+
5736+/// Every family of write announces the surface it changed. This is the property
5737+/// the whole live layer rests on: a surface nobody announces is a surface that
5738+/// stays stale until the reader reloads by hand.
5739+#[tokio::test]
5740+async fn every_kind_of_write_announces_its_surface() {
5741+ let (scratch, workspace, admin) = workspace_with_admin().await;
5742+ let store = &scratch.store;
5743+ let board = store.board(&workspace).await.unwrap().unwrap();
5744+ let column_id = column_named(store, &workspace, "Backlog").await;
5745+ let now = OffsetDateTime::now_utc();
5746+
5747+ let mut rx = store.subscribe();
5748+
5749+ // Board + Task + Activity.
5750+ store
5751+ .create_task(NewTask {
5752+ board_id: &board.id,
5753+ column_id: &column_id,
5754+ parent_id: None,
5755+ title: "Ship the exporter",
5756+ description: "",
5757+ deadline: None,
5758+ created_by: &admin,
5759+ })
5760+ .await
5761+ .unwrap();
5762+ // Members.
5763+ member(store, &workspace, "bo@izlek.sh", "Bo").await;
5764+ // Queue.
5765+ store
5766+ .queue_notice("bo@izlek.sh", "Subject", "Body", now)
5767+ .await
5768+ .unwrap();
5769+ // Rules.
5770+ store
5771+ .create_mail_rule(
5772+ &board.id,
5773+ &Trigger::StatusBecomes(Some(column_id.clone())),
5774+ "Something moved",
5775+ Audience::Board,
5776+ now,
5777+ false,
5778+ )
5779+ .await
5780+ .unwrap();
5781+ // Settings.
5782+ store
5783+ .set_public_url(&workspace, Some("https://izlek.example"))
5784+ .await
5785+ .unwrap();
5786+ // Activity with no task of its own.
5787+ store
5788+ .record_event(
5789+ Some(&admin),
5790+ &izlek_core::detail::ActivityKind::Other("settings".to_string()),
5791+ "",
5792+ now,
5793+ )
5794+ .await
5795+ .unwrap();
5796+
5797+ let seen = announced(&mut rx);
5798+ for topic in ["board", "task", "members", "queue", "rules", "settings", "activity"] {
5799+ assert!(
5800+ seen.iter().any(|k| k == topic),
5801+ "no {topic} announcement; heard {seen:?}"
5802+ );
5803+ }
5804+}
5805+
5806+/// A write that failed says nothing. A client woken by a change that never
5807+/// committed would re-read the state it already had — harmless once, and a
5808+/// permanent background hum if every refused mail sent one.
5809+#[tokio::test]
5810+async fn a_write_that_failed_announces_nothing() {
5811+ let (scratch, _workspace, _admin) = workspace_with_admin().await;
5812+ let store = &scratch.store;
5813+ let mut rx = store.subscribe();
5814+
5815+ let missing = Ulid::new().to_string();
5816+ assert!(matches!(
5817+ store
5818+ .record_send_accepted(&missing, OffsetDateTime::now_utc())
5819+ .await,
5820+ Err(StoreError::NotFound)
5821+ ));
5822+
5823+ assert!(
5824+ announced(&mut rx).is_empty(),
5825+ "a refused write announced a change"
5826+ );
5827+}
5828+
5829+/// Every write announces, and this is what keeps it true tomorrow.
5830+///
5831+/// The live layer's whole promise — that no surface goes stale until somebody
5832+/// reloads by hand — rests on one thing: a method that changes a row also says
5833+/// so. That is not a property a running test can observe in general, because
5834+/// the failure is a method nobody wrote a test for. So it is checked against
5835+/// the source instead: every method of the `Store` impl that issues an INSERT,
5836+/// UPDATE or DELETE must also announce, and a method that deliberately does
5837+/// not has to say so here, by name, with a reason.
5838+///
5839+/// A new write with no announcement fails this test rather than shipping a
5840+/// screen that quietly stops updating.
5841+#[test]
5842+fn every_writing_method_announces_or_is_named_here() {
5843+ // Rate-limit bookkeeping. No surface renders an auth attempt, and
5844+ // announcing one would wake every connected client on every failed
5845+ // sign-in — traffic bought for a screen that would look identical.
5846+ const SILENT_ON_PURPOSE: &[&str] = &[
5847+ "record_auth_attempt",
5848+ "clear_auth_attempts",
5849+ "prune_auth_attempts",
5850+ ];
5851+
5852+ let source = include_str!("../src/store/turso_store.rs");
5853+ let start = source
5854+ .find("impl Store for TursoStore {")
5855+ .expect("the Store impl moved");
5856+ // The impl ends at the first line that is a lone `}` in column zero.
5857+ let end = source[start..]
5858+ .find("\n}\n")
5859+ .map(|at| start + at)
5860+ .expect("unterminated impl block");
5861+ let impl_block = &source[start..end];
5862+
5863+ let mut silent = Vec::new();
5864+ let mut methods = impl_block.split("\n async fn ").skip(1).peekable();
5865+ while let Some(chunk) = methods.next() {
5866+ let name = chunk
5867+ .split(['(', '<', ' '])
5868+ .next()
5869+ .expect("a method with no name");
5870+ let writes = chunk.contains("INSERT INTO")
5871+ || chunk.contains("UPDATE ")
5872+ || chunk.contains("DELETE FROM");
5873+ if writes && !chunk.contains("announce(") && !SILENT_ON_PURPOSE.contains(&name) {
5874+ silent.push(name.to_string());
5875+ }
5876+ }
5877+
5878+ assert!(
5879+ silent.is_empty(),
5880+ "these methods change rows without announcing it, so the screens \
5881+ showing those rows will go stale until someone reloads by hand: {silent:?}. \
5882+ Either call `self.announce(..)` after the write commits, or add the \
5883+ method to SILENT_ON_PURPOSE with the reason."
5884+ );
5885+}
5886+
5887+/// The sweep sleeps on this answer, so it has to be the earliest moment
5888+/// anything is owed — not merely some moment, and not the newest.
5889+#[tokio::test]
5890+async fn the_next_due_moment_is_the_earliest_one() {
5891+ let (scratch, _workspace, _admin) = workspace_with_admin().await;
5892+ let store = &scratch.store;
5893+
5894+ assert_eq!(
5895+ store.next_due_at().await.unwrap(),
5896+ None,
5897+ "an empty queue owes nothing"
5898+ );
5899+
5900+ let now = OffsetDateTime::now_utc();
5901+ // Queued out of order on purpose: the answer is the earliest, not the first.
5902+ store
5903+ .queue_notice("late@izlek.sh", "Later", "body", now + Duration::hours(2))
5904+ .await
5905+ .unwrap();
5906+ store
5907+ .queue_notice("soon@izlek.sh", "Sooner", "body", now + Duration::minutes(5))
5908+ .await
5909+ .unwrap();
5910+
5911+ let due = store.next_due_at().await.unwrap().expect("nothing owed");
5912+ // Stored to the second, so compare at that grain.
5913+ assert!(
5914+ (due - (now + Duration::minutes(5))).abs() < Duration::seconds(1),
5915+ "expected the sooner of the two, got {due}"
5916+ );
5917+}
5918+
5919+/// A handshake and a delivered mail are different facts, kept in different
5920+/// columns, and editing the sender invalidates both — they were about a server
5921+/// that is no longer the one configured.
5922+#[tokio::test]
5923+async fn a_sender_check_is_recorded_apart_from_a_test_and_cleared_on_edit() {
5924+ let (scratch, workspace, _admin) = workspace_with_admin().await;
5925+ let store = &scratch.store;
5926+ let now = OffsetDateTime::now_utc();
5927+
5928+ let sender = |host: &str| NewSender {
5929+ host: host.to_string(),
5930+ port: 465,
5931+ username: "izlek".into(),
5932+ password: Some("hunter2".into()),
5933+ from_name: "İzlek".into(),
5934+ from_address: "izlek@izlek.sh".into(),
5935+ };
5936+ store.set_sender(&workspace, sender("smtp.one.test")).await.unwrap();
5937+
5938+ // A login that worked, and a mail that did not: both true at once, and
5939+ // neither may be rendered as the other.
5940+ store
5941+ .record_sender_check(
5942+ &workspace,
5943+ izlek_core::store::SenderCheck { at: now, took_ms: 120, error: None },
5944+ )
5945+ .await
5946+ .unwrap();
5947+ store
5948+ .record_sender_test(
5949+ &workspace,
5950+ izlek_core::store::SenderTest { at: now, took_ms: 0, error: Some("550 not allowed".into()) },
5951+ )
5952+ .await
5953+ .unwrap();
5954+
5955+ let ws = store.workspace().await.unwrap().unwrap();
5956+ let check = ws.sender_check.expect("no check recorded");
5957+ assert_eq!(check.error, None, "the handshake succeeded");
5958+ assert_eq!(check.took_ms, 120);
5959+ assert_eq!(
5960+ ws.sender_test.expect("no test recorded").error.as_deref(),
5961+ Some("550 not allowed"),
5962+ "the send still failed, and says why"
5963+ );
5964+
5965+ // Point it at a different server: what was known is now about nothing.
5966+ store.set_sender(&workspace, sender("smtp.two.test")).await.unwrap();
5967+ let ws = store.workspace().await.unwrap().unwrap();
5968+ assert!(ws.sender_check.is_none(), "a stale handshake survived an edit");
5969+ assert!(ws.sender_test.is_none(), "a stale test survived an edit");
5970+}
crates/izlek-web/Cargo.tomlmodified+7 -0
@@ -17,6 +17,7 @@ topcoat = { version = "0.6.2", default-features = false, features = [
17 "serve",17 "serve",
18 "compression",18 "compression",
19 "multipart",19 "multipart",
20+ "sse",
20 ] }21 ] }
21 izlek-core = { workspace = true, features = ["server"] }22 izlek-core = { workspace = true, features = ["server"] }
22 serde.workspace = true23 serde.workspace = true
@@ -25,6 +26,9 @@ time.workspace = true
25 thiserror.workspace = true26 thiserror.workspace = true
26 tokio = { workspace = true }27 tokio = { workspace = true }
27 async-trait = "0.1.92"28 async-trait = "0.1.92"
29+# The live stream is built with `futures_util::stream::unfold`; topcoat does
30+# not re-export the futures traits, so this is named directly.
31+futures-util = { version = "0.3", default-features = false }
28 # TLS through rustls with the ring provider: no OpenSSL on the deployment box,32 # TLS through rustls with the ring provider: no OpenSSL on the deployment box,
29 # and no system certificate store to be missing inside a container.33 # and no system certificate store to be missing inside a container.
30 lettre = { version = "0.11.23", default-features = false, features = [34 lettre = { version = "0.11.23", default-features = false, features = [
@@ -42,4 +46,7 @@ grass = "0.13"
42 46
43 [dev-dependencies]47 [dev-dependencies]
44 http = "1.5"48 http = "1.5"
49+# Reads an SSE body frame by frame, so a live-channel test can wait for the
50+# announcement it expects instead of for a clock.
51+http-body-util = "0.1"
45 ulid = { workspace = true }52 ulid = { workspace = true }
crates/izlek-web/src/board.rsmodified+3 -1
@@ -376,7 +376,9 @@ async fn render_card(
376 </div>376 </div>
377 <div class="card-title">(card.title.clone())</div>377 <div class="card-title">(card.title.clone())</div>
378 <div class="card-foot">378 <div class="card-foot">
379- <span class=(class!("card-deadline", "card-deadline-overdue" if overdue, "card-deadline-none" if !dated))>379+ // Overdue is a comparison against today, so a tab left open
380+ // over midnight is wrong until something re-renders it.
381+ <span data-tick=(dated.then_some("")) class=(class!("card-deadline", "card-deadline-overdue" if overdue, "card-deadline-none" if !dated))>
380 (deadline)382 (deadline)
381 </span>383 </span>
382 if let Some(parts) = subtasks.clone() {384 if let Some(parts) = subtasks.clone() {
crates/izlek-web/src/detail.rsmodified+18 -3
@@ -1530,6 +1530,14 @@ async fn dep_row(
1530 }1530 }
1531 }1531 }
1532 1532
1533+/// The version stamp a `/files/{id}` URL carries: the row's `uploaded_at`.
1534+/// Uploads are insert-only — nothing in the store rewrites an attachment —
1535+/// so the stamp is the one moment the bytes have ever changed, and a URL
1536+/// that carries it can be cached as if it were the bytes themselves.
1537+fn attachment_stamp(attachment: &izlek_core::store::Attachment) -> String {
1538+ (attachment.uploaded_at.unix_timestamp_nanos() / 1_000).to_string()
1539+}
1540+
1533 async fn file_chip(1541 async fn file_chip(
1534 cx: &Cx,1542 cx: &Cx,
1535 task_id: &str,1543 task_id: &str,
@@ -1545,7 +1553,13 @@ async fn file_chip(
1545 let href = if crate::files::viewer_kind(&file.mime_type).is_some() {1553 let href = if crate::files::viewer_kind(&file.mime_type).is_some() {
1546 format!("/?task={task_id}&tab={}&file={}", Tab::Files.slug(), file.id)1554 format!("/?task={task_id}&tab={}&file={}", Tab::Files.slug(), file.id)
1547 } else {1555 } else {
1548- format!("/files/{}", file.id)1556+ // The stamp rides on the row, which the chip's `FileLine` does not
1557+ // carry: one lookup per plain-download chip buys the same versioned
1558+ // URL the viewer streams from.
1559+ match accounts(cx).store().attachment(&file.id).await {
1560+ Ok(Some(row)) => format!("/files/{}?v={}", file.id, attachment_stamp(&row)),
1561+ _ => format!("/files/{}", file.id),
1562+ }
1549 };1563 };
1550 view! {1564 view! {
1551 cx =>1565 cx =>
@@ -2143,8 +2157,9 @@ pub async fn file_viewer_modal(
2143 // Closing a file returns to the panel exactly as it stood, tab and all:2157 // Closing a file returns to the panel exactly as it stood, tab and all:
2144 // a viewer is opened from a section, not from the task at large.2158 // a viewer is opened from a section, not from the task at large.
2145 let close_href = format!("/?task={task_id}&tab={}", tab.slug());2159 let close_href = format!("/?task={task_id}&tab={}", tab.slug());
2146- let src = format!("/files/{file_id}");2160+ let stamp = attachment_stamp(&attachment);
2147- let download_href = format!("/files/{file_id}?dl=1");2161+ let src = format!("/files/{file_id}?v={stamp}");
2162+ let download_href = format!("/files/{file_id}?dl=1&v={stamp}");
2148 let name = attachment.file_name.clone();2163 let name = attachment.file_name.clone();
2149 // A workbook is the one viewer whose bytes are read here rather than2164 // A workbook is the one viewer whose bytes are read here rather than
2150 // handed to an element; every other kind streams from `/files/{id}` and2165 // handed to an element; every other kind streams from `/files/{id}` and
crates/izlek-web/src/files.rsmodified+10 -0
@@ -479,6 +479,16 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)>
479 // without one. Sent on every response, not only media — harmless either479 // without one. Sent on every response, not only media — harmless either
480 // way and one less type to special-case.480 // way and one less type to special-case.
481 headers.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));481 headers.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
482+ // An attachment's bytes are write-once — nothing in the store rewrites
483+ // a row — so the id in the URL is already its own version, and the
484+ // `?v=` stamp the render sites attach only makes that visible. A year
485+ // of `immutable` costs nothing because the URL can never outlive its
486+ // bytes; `private` keeps a shared proxy from handing one workspace's
487+ // attachments to another.
488+ headers.insert(
489+ header::CACHE_CONTROL,
490+ HeaderValue::from_static("private, max-age=31536000, immutable"),
491+ );
482 492
483 let total = bytes.len() as u64;493 let total = bytes.len() as u64;
484 let range = request_headers(cx)494 let range = request_headers(cx)
crates/izlek-web/src/i18n.rsmodified+9 -0
@@ -122,6 +122,9 @@ pub enum Key {
122 OutgoingMail,122 OutgoingMail,
123 Connected,123 Connected,
124 NotConfiguredChip,124 NotConfiguredChip,
125+ Unchecked,
126+ Refused,
127+ CheckConnection,
125 NotConnectedNote,128 NotConnectedNote,
126 SmtpHostLabel,129 SmtpHostLabel,
127 PortLabel,130 PortLabel,
@@ -523,6 +526,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
523 (Connected, Tr) => "Bağlı",526 (Connected, Tr) => "Bağlı",
524 (NotConfiguredChip, En) => "Not configured",527 (NotConfiguredChip, En) => "Not configured",
525 (NotConfiguredChip, Tr) => "Yapılandırılmadı",528 (NotConfiguredChip, Tr) => "Yapılandırılmadı",
529+ (Unchecked, En) => "Unchecked",
530+ (Unchecked, Tr) => "Denenmedi",
531+ (Refused, En) => "Refused",
532+ (Refused, Tr) => "Reddedildi",
533+ (CheckConnection, En) => "Check connection",
534+ (CheckConnection, Tr) => "Bağlantıyı dene",
526 (NotConnectedNote, En) => "Not connected.",535 (NotConnectedNote, En) => "Not connected.",
527 (NotConnectedNote, Tr) => "Bağlı değil.",536 (NotConnectedNote, Tr) => "Bağlı değil.",
528 (SmtpHostLabel, En) => "SMTP HOST",537 (SmtpHostLabel, En) => "SMTP HOST",
crates/izlek-web/src/layout.rsmodified+223 -11
@@ -81,7 +81,11 @@ pub(crate) async fn avatar(cx: &Cx, person: &Person, extra: &str) -> Result {
81 let class = format!("avatar avatar-tone-{tone} {extra}");81 let class = format!("avatar avatar-tone-{tone} {extra}");
82 let name = person.display_name.clone();82 let name = person.display_name.clone();
83 if person.has_photo {83 if person.has_photo {
84- let src = format!("/photo/{}", person.id);84+ let src = format!(
85+ "/photo/{}?v={}",
86+ person.id,
87+ crate::photo::photo_stamp(cx, &person.id)
88+ );
85 view! {89 view! {
86 cx =>90 cx =>
87 <img class=(class) src=(src) alt=(name.clone()) data-name=(name)>91 <img class=(class) src=(src) alt=(name.clone()) data-name=(name)>
@@ -237,7 +241,111 @@ pub async fn soft_nav_script(cx: &Cx) -> Result {
237 document.querySelectorAll('.comment-list').forEach(function (list) { list.scrollTop = list.scrollHeight; }); \241 document.querySelectorAll('.comment-list').forEach(function (list) { list.scrollTop = list.scrollHeight; }); \
238 document.dispatchEvent(new Event('izlek:wire')); \242 document.dispatchEvent(new Event('izlek:wire')); \
239 } \243 } \
240- function swap(html, url, fresh, push) { \244+ function keyOf(el) { \
245+ var form = el.form ? (el.form.getAttribute('action') || '') : ''; \
246+ return form + '|' + (el.name || '') + '|' + (el.type || '') + '|' + (el.tagName || ''); \
247+ } \
248+ function editable(el) { \
249+ return el.type !== 'hidden' && el.type !== 'password' && el.type !== 'file'; \
250+ } \
251+ function captureFields() { \
252+ var active = document.activeElement, out = []; \
253+ document.querySelectorAll('input, textarea, select').forEach(function (el) { \
254+ if (!editable(el)) { return; } \
255+ var moved; \
256+ if (el.type === 'checkbox' || el.type === 'radio') { moved = el.checked !== el.defaultChecked; } \
257+ else if (el.tagName === 'SELECT') { \
258+ var def = -1; \
259+ for (var j = 0; j < el.options.length; j++) { if (el.options[j].defaultSelected) { def = j; break; } } \
260+ if (def < 0) { def = 0; } \
261+ moved = el.selectedIndex !== def; \
262+ } else { moved = el.value !== el.defaultValue; } \
263+ var focused = el === active; \
264+ if (!moved && !focused) { return; } \
265+ var start = -1, end = -1; \
266+ try { if (el.selectionStart != null) { start = el.selectionStart; end = el.selectionEnd; } } catch (err) { } \
267+ out.push({ k: keyOf(el), v: el.value, c: el.checked, i: el.selectedIndex, f: focused, s: start, e: end }); \
268+ }); \
269+ return out; \
270+ } \
271+ function restoreFields(saved) { \
272+ if (!saved || !saved.length) { return; } \
273+ var fields = document.querySelectorAll('input, textarea, select'); \
274+ saved.forEach(function (was) { \
275+ var el = null; \
276+ for (var i = 0; i < fields.length; i++) { \
277+ if (keyOf(fields[i]) === was.k) { el = fields[i]; break; } \
278+ } \
279+ if (!el) { return; } \
280+ if (el.type === 'checkbox' || el.type === 'radio') { el.checked = was.c; } \
281+ else if (el.tagName === 'SELECT') { el.selectedIndex = was.i; } \
282+ else { el.value = was.v; } \
283+ if (was.f) { \
284+ try { \
285+ el.focus(); \
286+ if (was.s >= 0 && el.setSelectionRange) { el.setSelectionRange(was.s, was.e); } \
287+ } catch (err) { } \
288+ } \
289+ }); \
290+ } \
291+ function clientMade(node) { \
292+ return node.nodeType === 1 && node.classList \
293+ && (node.classList.contains('dd-panel') || node.classList.contains('dd-trigger')); \
294+ } \
295+ function pairable(a, b) { \
296+ if (a.nodeType !== b.nodeType) { return false; } \
297+ if (a.nodeType !== 1) { return true; } \
298+ if (a.nodeName !== b.nodeName) { return false; } \
299+ if (a.id || b.id) { return a.id === b.id; } \
300+ return true; \
301+ } \
302+ function syncAttrs(from, to) { \
303+ var i, at; \
304+ for (i = to.attributes.length - 1; i >= 0; i--) { \
305+ at = to.attributes[i]; \
306+ if (from.getAttribute(at.name) !== at.value) { from.setAttribute(at.name, at.value); } \
307+ } \
308+ for (i = from.attributes.length - 1; i >= 0; i--) { \
309+ at = from.attributes[i]; \
310+ if (at.name.indexOf('data-dd') === 0) { continue; } \
311+ if (!to.hasAttribute(at.name)) { from.removeAttribute(at.name); } \
312+ } \
313+ } \
314+ function morph(from, to) { \
315+ if (from.nodeType !== 1) { \
316+ if (from.nodeValue !== to.nodeValue) { from.nodeValue = to.nodeValue; } \
317+ return; \
318+ } \
319+ syncAttrs(from, to); \
320+ if (from.nodeName === 'SCRIPT') { \
321+ if (from.textContent !== to.textContent) { \
322+ var live = document.createElement('script'); \
323+ if (to.hasAttribute('src')) { live.setAttribute('src', to.getAttribute('src')); } \
324+ live.textContent = to.textContent; \
325+ from.replaceWith(live); \
326+ } \
327+ return; \
328+ } \
329+ morphChildren(from, to); \
330+ } \
331+ function morphChildren(from, to) { \
332+ var mine = [], theirs = [], n; \
333+ for (n = from.firstChild; n; n = n.nextSibling) { if (!clientMade(n)) { mine.push(n); } } \
334+ for (n = to.firstChild; n; n = n.nextSibling) { theirs.push(n); } \
335+ var i; \
336+ for (i = 0; i < theirs.length; i++) { \
337+ if (i < mine.length) { \
338+ if (pairable(mine[i], theirs[i])) { morph(mine[i], theirs[i]); } \
339+ else { mine[i].replaceWith(document.importNode(theirs[i], true)); } \
340+ } else { \
341+ from.appendChild(document.importNode(theirs[i], true)); \
342+ } \
343+ } \
344+ for (i = theirs.length; i < mine.length; i++) { mine[i].remove(); } \
345+ } \
346+ function swap(html, url, fresh, push, morphing) { \
347+ var keep = window.__izlekKeep ? captureFields() : null; \
348+ window.__izlekKeep = false; \
241 var doc = new DOMParser().parseFromString(html, 'text/html'); \349 var doc = new DOMParser().parseFromString(html, 'text/html'); \
242 var x = window.scrollX, y = window.scrollY; \350 var x = window.scrollX, y = window.scrollY; \
243 var root = doc.documentElement; \351 var root = doc.documentElement; \
@@ -247,15 +355,20 @@ pub async fn soft_nav_script(cx: &Cx) -> Result {
247 if (root.hasAttribute('data-ui')) { document.documentElement.setAttribute('data-ui', root.getAttribute('data-ui')); } \355 if (root.hasAttribute('data-ui')) { document.documentElement.setAttribute('data-ui', root.getAttribute('data-ui')); } \
248 else { document.documentElement.removeAttribute('data-ui'); } \356 else { document.documentElement.removeAttribute('data-ui'); } \
249 if (url) { history[push ? 'pushState' : 'replaceState'](null, '', url); } \357 if (url) { history[push ? 'pushState' : 'replaceState'](null, '', url); } \
250- document.body.replaceChildren(); \358+ if (morphing) { \
251- while (doc.body.firstChild) { document.body.appendChild(doc.body.firstChild); } \359+ morph(document.body, doc.body); \
252- document.body.querySelectorAll('script').forEach(function (old) { \360+ } else { \
253- var live = document.createElement('script'); \361+ document.body.replaceChildren(); \
254- if (old.hasAttribute('src')) { live.setAttribute('src', old.getAttribute('src')); } \362+ while (doc.body.firstChild) { document.body.appendChild(doc.body.firstChild); } \
255- live.textContent = old.textContent; \363+ document.body.querySelectorAll('script').forEach(function (old) { \
256- old.replaceWith(live); \364+ var live = document.createElement('script'); \
257- }); \365+ if (old.hasAttribute('src')) { live.setAttribute('src', old.getAttribute('src')); } \
258- window.scrollTo(fresh ? 0 : x, fresh ? 0 : y); \366+ live.textContent = old.textContent; \
367+ old.replaceWith(live); \
368+ }); \
369+ window.scrollTo(fresh ? 0 : x, fresh ? 0 : y); \
370+ } \
371+ restoreFields(keep); \
259 wire(); \372 wire(); \
260 } \373 } \
261 function sweepPanels() { \374 function sweepPanels() { \
@@ -269,6 +382,12 @@ pub async fn soft_nav_script(cx: &Cx) -> Result {
269 function () { window.location.href = url; } \382 function () { window.location.href = url; } \
270 ); \383 ); \
271 }; \384 }; \
385+ window.__izlekRefresh = function () { \
386+ fetch(window.location.href).then( \
387+ function (r) { return r.text().then(function (t) { swap(t, r.url, false, false, true); }); }, \
388+ function () {} \
389+ ); \
390+ }; \
272 window.__izlekPost = function (action, fields) { \391 window.__izlekPost = function (action, fields) { \
273 fetch(action, { method: 'POST', body: new URLSearchParams(fields) }).then( \392 fetch(action, { method: 'POST', body: new URLSearchParams(fields) }).then( \
274 function (r) { return r.text().then(function (t) { swap(t, r.url); }); }, \393 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 {
394 /// | 40 | the topbar `.user-menu` (pin+blur), then the rules composer, then a rules edit row (back to `/rules`) | `layout.rs`'s `escape_script` |513 /// | 40 | the topbar `.user-menu` (pin+blur), then the rules composer, then a rules edit row (back to `/rules`) | `layout.rs`'s `escape_script` |
395 /// | 20 | the datepicker popover | `board.rs`'s `card_menu_script` |514 /// | 20 | the datepicker popover | `board.rs`'s `card_menu_script` |
396 /// | 10 | the card context menu | `board.rs`'s `card_menu_script` |515 /// | 10 | the card context menu | `board.rs`'s `card_menu_script` |
516+/// The live channel's browser half: one `EventSource` per tab, and the slow
517+/// tick that keeps clock-driven text honest.
518+///
519+/// Everything here is one script because both halves end in the same act —
520+/// re-fetch the current URL through `__izlekGo` and let `swap()` do what it
521+/// already does after every form post. There is deliberately no second render
522+/// path: a partial-update mechanism would be a second way for the page to be
523+/// wrong, and the full swap is the one the app exercises constantly.
524+///
525+/// Three things it must not get wrong:
526+///
527+/// The `__izlekLive` guard is not decoration. `swap()` re-executes every
528+/// swapped-in script, so without it each soft navigation would open another
529+/// `EventSource` and the tab would end up holding one connection per page it
530+/// had ever visited.
531+///
532+/// A refresh must not disturb what somebody is in the middle of. The first
533+/// attempt held the refresh back while a form was dirty, which was wrong twice
534+/// over: one unsubmitted form froze every other surface on the screen, and a
535+/// dropdown could never be used at all while the workspace was busy, because
536+/// each update slammed it shut.
537+///
538+/// The cause of both was the refresh throwing the whole page away. So the live
539+/// path does not: it MORPHS. `swap`'s morphing mode walks the freshly fetched
540+/// document against the live one and touches only what actually differs —
541+/// changed text, changed attributes, added and removed nodes. Everything else
542+/// is the same DOM node it was a moment ago, so an open dropdown stays open, a
543+/// caret stays where it was, a half-typed comment keeps its text, and a scrolled
544+/// panel keeps its position. Not because any of them is special-cased, but
545+/// because nothing touched them.
546+///
547+/// Two kinds of node need naming for this to hold. The dropdown builds a
548+/// `.dd-trigger` beside each select and appends a `.dd-panel` to the body, and
549+/// neither exists in the server's HTML — a morph that did not know this would
550+/// delete them as strays on the first update. And a `<script>` whose text is
551+/// unchanged is left alone rather than re-created, so the live path stops
552+/// re-running every script on the page; the `__izlek*` guards remain the
553+/// backstop for the full-swap path, which still re-runs them.
554+///
555+/// Morphing is used only for the live refresh. Navigations and form posts keep
556+/// the full replace: they are a different page or a submitted form, where
557+/// carrying the old DOM's state over is wrong rather than kind.
558+///
559+/// The tick exists because some text goes stale with no write behind it: the
560+/// queue's next-try time and a card's overdue mark change because the clock
561+/// moved, and no announcement will ever fire for that. Rather than re-format
562+/// those in JavaScript — which would mean a second implementation of the
563+/// locale- and timezone-aware formatting the server already does, free to
564+/// disagree with it — the tick re-fetches, and the server stays the only thing
565+/// that decides what a moment reads as. It runs only on pages carrying a
566+/// `data-tick` element, so a page with no clock-driven text is silent.
567+pub async fn live_script(cx: &Cx) -> Result {
568+ const JS: &str = "\
569+ (function () { \
570+ if (window.__izlekLive) { return; } \
571+ window.__izlekLive = true; \
572+ var timer = null; \
573+ function refresh() { \
574+ window.__izlekKeep = true; \
575+ if (window.__izlekRefresh) { window.__izlekRefresh(); } \
576+ } \
577+ function schedule() { \
578+ if (timer) { clearTimeout(timer); } \
579+ timer = setTimeout(function () { timer = null; refresh(); }, 200); \
580+ } \
581+ function wanted(topic) { \
582+ if (topic === 'resync') { return true; } \
583+ var path = window.location.pathname; \
584+ if (path === '/logs') { return topic !== 'board' && topic !== 'task'; } \
585+ if (path === '/rules') { return topic === 'rules' || topic === 'members'; } \
586+ if (path === '/settings') { return topic === 'settings' || topic === 'members'; } \
587+ return topic === 'board' || topic === 'task' || topic === 'members'; \
588+ } \
589+ try { \
590+ var src = new EventSource('/api/live'); \
591+ src.onmessage = function (e) { \
592+ var frame; \
593+ try { frame = JSON.parse(e.data); } catch (err) { return; } \
594+ if (frame && wanted(frame.topic)) { schedule(); } \
595+ }; \
596+ } catch (err) { } \
597+ setInterval(function () { \
598+ if (document.querySelector('[data-tick]')) { refresh(); } \
599+ }, 60000); \
600+ })(); \
601+ ";
602+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
603+}
604+
397 pub async fn escape_manager_script(cx: &Cx) -> Result {605 pub async fn escape_manager_script(cx: &Cx) -> Result {
398 use topcoat::view::Unescaped;606 use topcoat::view::Unescaped;
399 const JS: &str = "\607 const JS: &str = "\
@@ -510,6 +718,10 @@ async fn root_layout(cx: &Cx, slot: Result) -> Result {
510 <body>718 <body>
511 (escape_manager_script(cx).await?)719 (escape_manager_script(cx).await?)
512 (soft_nav_script(cx).await?)720 (soft_nav_script(cx).await?)
721+ // Only for a signed-in page: `/api/live` answers 401 to
722+ // everybody else, and an auth screen that opened a stream
723+ // would just reconnect against that refusal forever.
724+ if asking.is_some() { (live_script(cx).await?) }
513 (content)725 (content)
514 </body>726 </body>
515 </html>727 </html>
crates/izlek-web/src/lib.rsmodified+1 -0
@@ -10,6 +10,7 @@ pub mod dropdown;
10 pub mod files;10 pub mod files;
11 pub mod i18n;11 pub mod i18n;
12 pub mod layout;12 pub mod layout;
13+pub mod live;
13 pub mod logs;14 pub mod logs;
14 pub mod pages;15 pub mod pages;
15 pub mod photo;16 pub mod photo;
crates/izlek-web/src/live.rsadded+151 -0
@@ -0,0 +1,151 @@
1+//! The live channel: one long-lived connection per open tab, carrying the news
2+//! that something changed.
3+//!
4+//! What travels here is a topic and nothing else — never a row, never a name.
5+//! That is the whole security design. A channel that carried data would need a
6+//! role check on every message, and the day somebody adds a topic and forgets
7+//! the check is the day the queue leaks to a member. A topic name cannot leak
8+//! anything: the client is told only *which* surface moved, and re-fetches it
9+//! through the ordinary route, where the ordinary role gate answers. The one
10+//! thing this file must still get right is not naming an admin-only surface to
11+//! somebody who is not an admin — [`may_hear`] is that, and it is the reason
12+//! the filter runs here rather than in the browser.
13+
14+use std::time::Duration;
15+
16+use izlek_core::{Change, Topic};
17+use serde::Serialize;
18+use tokio::sync::broadcast::error::RecvError;
19+use tokio::time::Instant;
20+use topcoat::context::{Cx, try_app_context};
21+use topcoat::router::content::sse::{Event, KeepAlive, Sse};
22+use topcoat::router::response::{IntoResponse, Response};
23+use topcoat::router::{StatusCode, route};
24+
25+use crate::server::{accounts, require_user};
26+
27+/// How long one connection is held before the server ends it and the browser
28+/// opens another. Set from `config/izlek.toml`; absent — as in the test router
29+/// — the default stands in.
30+#[derive(Clone, Copy, Debug)]
31+pub struct LiveWindow(pub Duration);
32+
33+impl Default for LiveWindow {
34+ fn default() -> Self {
35+ Self(Duration::from_secs(300))
36+ }
37+}
38+
39+/// Tells a live stream that the process is going down.
40+///
41+/// Without this, stopping the server takes as long as its graceful shutdown
42+/// allows — thirty seconds by default. The server stops accepting connections
43+/// and then waits for in-flight requests to finish, and an open live stream is
44+/// an in-flight request that intends to sit there for minutes. Every open tab
45+/// is one. So the streams are told, and they end; the browser reconnects when
46+/// the server comes back, which is what it does after any dropped connection.
47+#[derive(Clone)]
48+pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>);
49+
50+/// Whether a reader of this role may be told that this surface moved.
51+///
52+/// The board, a task and the member list are what every signed-in person
53+/// already sees. The queue, the rules, the settings and the activity log are
54+/// admin screens, and CLAUDE.md's rule — a role that cannot act on a surface
55+/// does not see it — reaches the channel too: a member is not told the queue
56+/// moved, because being told is itself knowing something about the queue.
57+fn may_hear(topic: &Topic, admin: bool) -> bool {
58+ match topic {
59+ Topic::Board | Topic::Task(_) | Topic::Members => true,
60+ Topic::Queue | Topic::Rules | Topic::Settings | Topic::Activity => admin,
61+ }
62+}
63+
64+/// What one announcement looks like on the wire.
65+#[derive(Serialize)]
66+struct Frame<'a> {
67+ topic: &'a str,
68+ /// The task, when the topic is about one. Absent otherwise.
69+ #[serde(skip_serializing_if = "Option::is_none")]
70+ id: Option<&'a str>,
71+ seq: u64,
72+}
73+
74+/// A frame the client reads as "you may have missed something; re-read
75+/// everything you are showing".
76+const RESYNC: &str = r#"{"topic":"resync"}"#;
77+
78+#[route(GET "/api/live")]
79+async fn live(cx: &Cx) -> topcoat::Result<Response> {
80+ // Resolved once, here, and never again for the life of this connection.
81+ // That is why the connection has a deadline: the reconnect is what
82+ // re-authenticates, so a session revoked mid-stream goes quiet within one
83+ // window rather than never.
84+ let Ok(user) = require_user(cx).await else {
85+ return (StatusCode::UNAUTHORIZED, "").into_response(cx);
86+ };
87+ let admin = user.role.can_administer();
88+ let rx = accounts(cx).store().subscribe();
89+ let stopping = try_app_context::<Shutdown>(cx).map(|s| s.0.clone());
90+ let deadline = Instant::now() + try_app_context::<LiveWindow>(cx).copied().unwrap_or_default().0;
91+
92+ let events = futures_util::stream::unfold(
93+ (rx, admin, deadline, stopping),
94+ |(mut rx, admin, deadline, mut stopping)| async move {
95+ loop {
96+ // Already going down: say nothing and end, so this connection
97+ // is not one the shutdown has to sit and wait out.
98+ if stopping.as_ref().is_some_and(|watch| *watch.borrow()) {
99+ return None;
100+ }
101+ let left = deadline.saturating_duration_since(Instant::now());
102+ if left.is_zero() {
103+ return None;
104+ }
105+ // Three things end the wait: an announcement, the window
106+ // running out, and the server being told to stop. The third is
107+ // watched rather than polled, so Ctrl+C is felt at once.
108+ let heard = tokio::time::timeout(left, async {
109+ match stopping.as_mut() {
110+ Some(watch) => tokio::select! {
111+ _ = watch.changed() => None,
112+ got = rx.recv() => Some(got),
113+ },
114+ None => Some(rx.recv().await),
115+ }
116+ })
117+ .await;
118+ let frame = match heard {
119+ // The window closed, or the server is stopping. Ending the
120+ // stream is the point: the browser reconnects by itself and
121+ // authenticates again.
122+ Err(_) | Ok(None) => return None,
123+ // The store is gone, which means the process is going.
124+ Ok(Some(Err(RecvError::Closed))) => return None,
125+ // This reader fell far enough behind that announcements were
126+ // dropped. Which ones is unknowable, so the client is told to
127+ // re-read everything rather than shown a mix of before and
128+ // after. The stream stays open — a slow moment is not a fault.
129+ Ok(Some(Err(RecvError::Lagged(_)))) => Event::new().data(RESYNC),
130+ Ok(Some(Ok(Change { topic, seq }))) => {
131+ if !may_hear(&topic, admin) {
132+ // Not merely unsent: never named. A member's
133+ // connection carries no evidence the queue exists.
134+ continue;
135+ }
136+ let frame = Frame { topic: topic.kind(), id: topic.id(), seq };
137+ match Event::new().json_data(&frame) {
138+ Ok(event) => event,
139+ Err(problem) => {
140+ return Some((Err(problem), (rx, admin, deadline, stopping)));
141+ }
142+ }
143+ }
144+ };
145+ return Some((Ok(frame), (rx, admin, deadline, stopping)));
146+ }
147+ },
148+ );
149+
150+ Sse::new(events).keep_alive(KeepAlive::new()).into_response(cx)
151+}
crates/izlek-web/src/logs.rsmodified+7 -2
@@ -561,7 +561,7 @@ async fn snapshot(
561 format!(561 format!(
562 "{} {}",562 "{} {}",
563 t(lang, Key::NextTry),563 t(lang, Key::NextTry),
564- izlek_core::detail::moment_label_in(at, zone)564+ izlek_core::detail::moment_label_with_seconds_in(at, zone)
565 )565 )
566 }566 }
567 }),567 }),
@@ -957,6 +957,11 @@ async fn logs_screen(
957 line.state.clone()957 line.state.clone()
958 };958 };
959 let chip_class = format!("rule-term rule-term-{}", line.state_kind);959 let chip_class = format!("rule-term rule-term-{}", line.state_kind);
960+ // A queued mail's next-try time goes stale on
961+ // the clock, not on a write, so it carries the
962+ // mark the tick looks for. A row with no retry
963+ // left has nothing that moves.
964+ let ticking = line.next_attempt.is_some();
960 let next_attempt = line.next_attempt.unwrap_or_else(|| t(lang, Key::NoRetry).to_string());965 let next_attempt = line.next_attempt.unwrap_or_else(|| t(lang, Key::NoRetry).to_string());
961 <div class="rule-row">966 <div class="rule-row">
962 <div class="rule-sentence">967 <div class="rule-sentence">
@@ -965,7 +970,7 @@ async fn logs_screen(
965 <span class=(chip_class)>(state_note)</span>970 <span class=(chip_class)>(state_note)</span>
966 <span>(crate::i18n::attempt_label(lang, line.attempts))</span>971 <span>(crate::i18n::attempt_label(lang, line.attempts))</span>
967 </div>972 </div>
968- <span class="rule-stamp">(next_attempt)</span>973+ <span class="rule-stamp" data-tick=(ticking.then_some(""))>(next_attempt)</span>
969 if line.state_kind == "failed" || line.state_kind == "abandoned" {974 if line.state_kind == "failed" || line.state_kind == "abandoned" {
970 <form method="post" action="/api/retry_send">975 <form method="post" action="/api/retry_send">
971 <input type="hidden" name="send_id" value=(line.id.clone())>976 <input type="hidden" name="send_id" value=(line.id.clone())>
crates/izlek-web/src/main.rsmodified+114 -12
@@ -50,7 +50,11 @@ async fn main() {
50 Arc::new(izlek_web::smtp::WorkspaceSmtp::new(store.clone())),50 Arc::new(izlek_web::smtp::WorkspaceSmtp::new(store.clone())),
51 config.listen_url(),51 config.listen_url(),
52 ));52 ));
53- tokio::spawn(sweep(engine.clone()));53+ tokio::spawn(sweep(engine.clone(), store.clone()));
54+
55+ // Told when the process is stopping, so the live streams end instead of
56+ // being waited out. See `izlek_web::live::Shutdown`.
57+ let (stop, stopping) = tokio::sync::watch::channel(false);
54 58
55 let router = Router::builder()59 let router = Router::builder()
56 .discover()60 .discover()
@@ -65,6 +69,11 @@ async fn main() {
65 .cookies()69 .cookies()
66 .assets(AssetBundle::load().expect("failed to load the asset bundle"))70 .assets(AssetBundle::load().expect("failed to load the asset bundle"))
67 .app_context(accounts)71 .app_context(accounts)
72+ .app_context(izlek_web::photo::PhotoStamps::default())
73+ .app_context(izlek_web::live::LiveWindow(std::time::Duration::from_secs(
74+ config.live_seconds,
75+ )))
76+ .app_context(izlek_web::live::Shutdown(stopping))
68 .app_context(izlek_web::server::Mail::sending(engine.clone()))77 .app_context(izlek_web::server::Mail::sending(engine.clone()))
69 .build();78 .build();
70 79
@@ -74,27 +83,65 @@ async fn main() {
74 let listener = tokio::net::TcpListener::bind(config.listen)83 let listener = tokio::net::TcpListener::bind(config.listen)
75 .await84 .await
76 .expect("failed to bind the listen address");85 .expect("failed to bind the listen address");
77- topcoat::serve(listener, router)86+ // Not `topcoat::serve`, which installs its own signal handler and gives
78- .await87+ // no way to hear it. The handler is taken over so the live streams learn
79- .expect("server error");88+ // about the stop before the graceful shutdown starts counting: without
89+ // that, every open tab holds a stream the shutdown waits its full thirty
90+ // seconds for, and Ctrl+C appears to hang.
91+ topcoat::serve_until(listener, router, async move {
92+ shutdown_signal().await;
93+ let _ = stop.send(true);
94+ })
95+ .await
96+ .expect("server error");
97+}
98+
99+/// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a
100+/// service manager.
101+async fn shutdown_signal() {
102+ let interrupt = async {
103+ tokio::signal::ctrl_c()
104+ .await
105+ .expect("failed to install the Ctrl+C handler");
106+ };
107+ let terminate = async {
108+ tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
109+ .expect("failed to install the SIGTERM handler")
110+ .recv()
111+ .await;
112+ };
113+
114+ tokio::select! {
115+ () = interrupt => {}
116+ () = terminate => {}
117+ }
80 }118 }
81 119
82 /// Retries what a mail server refused earlier and picks up anything a crash120 /// Retries what a mail server refused earlier and picks up anything a crash
83 /// left claimed but unsent.121 /// left claimed but unsent.
84 ///122 ///
85-/// A minute is short enough that the first retry of a host that blinked lands123+/// It sleeps until the exact moment the next mail falls due rather than waking
86-/// while somebody is still looking at the board, and long enough that a host124+/// on a fixed beat. The beat is what made a retry promised for 16:42:47 leave
87-/// which is properly down is not hammered — the wait per send widens on its125+/// at 16:43 — the row was due and nothing was awake to notice — and a queue
88-/// own, and a send that has used its attempts is written off rather than126+/// that names a second has to mean the second it names.
89-/// carried forever.127+///
90-async fn sweep(engine: std::sync::Arc<izlek_core::MailEngine>) {128+/// Two other things can wake it. A mail being queued announces itself on the
129+/// live channel, so an invite goes out as soon as it is asked for instead of
130+/// waiting out somebody else's timer. And an hour is the longest it will sleep
131+/// regardless, so a clock jump or a row written by something other than this
132+/// process is picked up on its own.
133+async fn sweep(
134+ engine: std::sync::Arc<izlek_core::MailEngine>,
135+ store: Arc<dyn izlek_core::store::Store>,
136+) {
91 /// Enough that a morning's backlog clears in a few passes, few enough that137 /// Enough that a morning's backlog clears in a few passes, few enough that
92 /// one pass cannot sit on the mail server for minutes.138 /// one pass cannot sit on the mail server for minutes.
93 const PER_PASS: u32 = 50;139 const PER_PASS: u32 = 50;
140+ /// The longest this will sleep with nothing due.
141+ const IDLE: std::time::Duration = std::time::Duration::from_secs(3600);
94 142
95- let mut every_minute = tokio::time::interval(std::time::Duration::from_secs(60));143+ let mut queued = store.subscribe();
96 loop {144 loop {
97- every_minute.tick().await;
98 match engine145 match engine
99 .deliver_owed(time::OffsetDateTime::now_utc(), PER_PASS)146 .deliver_owed(time::OffsetDateTime::now_utc(), PER_PASS)
100 .await147 .await
@@ -106,5 +153,60 @@ async fn sweep(engine: std::sync::Arc<izlek_core::MailEngine>) {
106 Ok(_) => {}153 Ok(_) => {}
107 Err(problem) => eprintln!("izlek mail sweep could not read the ledger: {problem}"),154 Err(problem) => eprintln!("izlek mail sweep could not read the ledger: {problem}"),
108 }155 }
156+
157+ // How long until the next mail is owed. A row already due means the
158+ // pass above could not take it — it was over its limit, or something
159+ // else holds it — so the wait is the idle one rather than zero, which
160+ // would spin.
161+ let wait = match store.next_due_at().await {
162+ Ok(Some(at)) => {
163+ let now = time::OffsetDateTime::now_utc();
164+ if at > now {
165+ (at - now).try_into().unwrap_or(IDLE).min(IDLE)
166+ } else {
167+ IDLE
168+ }
169+ }
170+ Ok(None) => IDLE,
171+ Err(problem) => {
172+ eprintln!("izlek mail sweep could not read the ledger: {problem}");
173+ IDLE
174+ }
175+ };
176+
177+ tokio::select! {
178+ _ = tokio::time::sleep(wait) => {}
179+ // A newly queued mail is due now, so there is no reason to make it
180+ // wait out a timer that was set before it existed.
181+ alive = queue_touched(&mut queued) => {
182+ if !alive {
183+ return;
184+ }
185+ }
186+ }
187+ }
188+}
189+
190+/// Waits for something to happen to the mail queue specifically.
191+///
192+/// The channel carries every topic, and the sweep cares about one. Filtering
193+/// here rather than in the `select!` matters: a `continue` on somebody else's
194+/// board edit would send this round the loop and run a whole delivery pass, so
195+/// every card moved on the board would poke the mail server. Returns false
196+/// when the channel is gone, which means the process is going with it.
197+///
198+/// Lagging means announcements were dropped — a reason to look, not to stop.
199+async fn queue_touched(rx: &mut tokio::sync::broadcast::Receiver<izlek_core::Change>) -> bool {
200+ use tokio::sync::broadcast::error::RecvError;
201+ loop {
202+ match rx.recv().await {
203+ Ok(change) => {
204+ if change.topic == izlek_core::Topic::Queue {
205+ return true;
206+ }
207+ }
208+ Err(RecvError::Lagged(_)) => return true,
209+ Err(RecvError::Closed) => return false,
210+ }
109 }211 }
110 }212 }
crates/izlek-web/src/photo.rsmodified+70 -2
@@ -1,7 +1,11 @@
1 //! Profile photo upload, removal and serving. Sibling to `files.rs`, whose1 //! Profile photo upload, removal and serving. Sibling to `files.rs`, whose
2 //! multipart parsing and mime-sniffing it reuses rather than re-implements.2 //! multipart parsing and mime-sniffing it reuses rather than re-implements.
3 3
4-use topcoat::context::Cx;4+use std::collections::HashMap;
5+use std::sync::{Arc, LazyLock, Mutex};
6+
7+use time::OffsetDateTime;
8+use topcoat::context::{Cx, try_app_context};
5 use topcoat::router::content::multipart::Multipart;9 use topcoat::router::content::multipart::Multipart;
6 use topcoat::router::request::headers as request_headers;10 use topcoat::router::request::headers as request_headers;
7 use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route};11 use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route};
@@ -67,7 +71,14 @@ async fn upload(
67 return Ok(saved_or_refused("profile_photo", Some(Refusal::NotAnImage)));71 return Ok(saved_or_refused("profile_photo", Some(Refusal::NotAnImage)));
68 }72 }
69 return Ok(match store.set_photo(&user.id, &collected, mime).await {73 return Ok(match store.set_photo(&user.id, &collected, mime).await {
70- Ok(()) => saved_or_refused("profile_photo", None),74+ Ok(()) => {
75+ // The bytes changed, so the URL every avatar renders has to
76+ // change with them — bump before the answer goes out.
77+ if let Some(stamps) = try_app_context::<PhotoStamps>(cx) {
78+ stamps.bump(&user.id);
79+ }
80+ saved_or_refused("profile_photo", None)
81+ }
71 Err(_) => saved_or_refused("profile_photo", Some(Refusal::Unavailable)),82 Err(_) => saved_or_refused("profile_photo", Some(Refusal::Unavailable)),
72 });83 });
73 }84 }
@@ -87,6 +98,54 @@ async fn delete(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
87 })98 })
88 }99 }
89 100
101+/// Photo URL version stamps, in process memory. The `user` row carries no
102+/// photo-updated moment and a schema column for cache-busting is out of
103+/// proportion, so the stamp lives here: `upload` bumps it when the bytes
104+/// change, and every avatar render reads it back. A photo whose bytes this
105+/// process never saw change — one uploaded by an earlier process — stamps
106+/// at the process start, which is still a URL no browser has fetched, so
107+/// it is re-downloaded exactly once per restart and cached from then on.
108+#[derive(Clone, Default)]
109+pub struct PhotoStamps(Arc<Mutex<HashMap<String, i64>>>);
110+
111+/// Unix microseconds at first use: the stamp for every photo whose bytes
112+/// this process never saw change. Stable for the process's lifetime, and
113+/// later than any stamp an earlier process emitted, so no pre-restart URL
114+/// survives a restart.
115+static PROCESS_START: LazyLock<i64> =
116+ LazyLock::new(|| (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000) as i64);
117+
118+impl PhotoStamps {
119+ fn stamp(&self, user_id: &str) -> i64 {
120+ self.0
121+ .lock()
122+ .unwrap()
123+ .get(user_id)
124+ .copied()
125+ .unwrap_or(*PROCESS_START)
126+ }
127+
128+ fn bump(&self, user_id: &str) {
129+ let now = (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000) as i64;
130+ let mut stamps = self.0.lock().unwrap();
131+ // A write always moves the URL: never emit a stamp this user has
132+ // already rendered with, even when two writes land inside the same
133+ // microsecond.
134+ let stamp = stamps.get(user_id).copied().unwrap_or(*PROCESS_START);
135+ stamps.insert(user_id.to_string(), now.max(stamp + 1));
136+ }
137+}
138+
139+/// The stamp an avatar's photo URL carries. A router built without
140+/// `PhotoStamps` — the test router does this — falls back to the process
141+/// start, which is still a URL no browser has fetched before.
142+pub(crate) fn photo_stamp(cx: &Cx, user_id: &str) -> i64 {
143+ match try_app_context::<PhotoStamps>(cx) {
144+ Some(stamps) => stamps.stamp(user_id),
145+ None => *PROCESS_START,
146+ }
147+}
148+
90 /// A cheap, non-cryptographic hash — good enough for an `ETag` on bytes only149 /// A cheap, non-cryptographic hash — good enough for an `ETag` on bytes only
91 /// this server ever writes.150 /// this server ever writes.
92 fn fnv1a(bytes: &[u8]) -> u64 {151 fn fnv1a(bytes: &[u8]) -> u64 {
@@ -124,6 +183,15 @@ async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
124 let etag = format!("\"{:x}\"", fnv1a(&bytes));183 let etag = format!("\"{:x}\"", fnv1a(&bytes));
125 let mut headers = HeaderMap::new();184 let mut headers = HeaderMap::new();
126 headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap());185 headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap());
186+ // The stamp in the URL is the other half of this caching: `upload`
187+ // bumps it whenever the bytes change, so a year of `immutable` never
188+ // shows an old photo — a changed photo is a changed URL. `private`
189+ // because the route is session-gated and a shared proxy cache would
190+ // otherwise answer a stranger from another workspace's entry.
191+ headers.insert(
192+ header::CACHE_CONTROL,
193+ HeaderValue::from_static("private, max-age=31536000, immutable"),
194+ );
127 195
128 let if_none_match = request_headers(cx)196 let if_none_match = request_headers(cx)
129 .get(header::IF_NONE_MATCH)197 .get(header::IF_NONE_MATCH)
crates/izlek-web/src/server.rsmodified+6 -0
@@ -136,6 +136,12 @@ impl Mail {
136 Some(engine.send_test(to).await)136 Some(engine.send_test(to).await)
137 }137 }
138 138
139+ /// Asks the mail server whether it would have us, sending nothing.
140+ pub async fn check(&self) -> Option<Result<time::Duration, izlek_core::MailError>> {
141+ let engine = self.0.clone()?;
142+ Some(engine.check_sender().await)
143+ }
144+
139 fn log(report: izlek_core::store::Result<izlek_core::mail::Report>) {145 fn log(report: izlek_core::store::Result<izlek_core::mail::Report>) {
140 match report {146 match report {
141 Ok(report) if report.sent + report.failed + report.abandoned > 0 => {147 Ok(report) if report.sent + report.failed + report.abandoned > 0 => {
crates/izlek-web/src/settings.rsmodified+167 -10
@@ -26,7 +26,7 @@ use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, page, route};
26 use topcoat::view::view;26 use topcoat::view::view;
27 27
28 use izlek_core::detail::ActivityKind;28 use izlek_core::detail::ActivityKind;
29-use izlek_core::store::{NewSender, SenderTest, User};29+use izlek_core::store::{NewSender, SenderCheck, SenderTest, Store, User};
30 30
31 use crate::i18n::{Key, Lang, t};31 use crate::i18n::{Key, Lang, t};
32 use crate::server::{Refusal, accounts, mail, require_admin, require_user};32 use crate::server::{Refusal, accounts, mail, require_admin, require_user};
@@ -187,7 +187,7 @@ fn redirect_to(query: &str) -> (StatusCode, HeaderMap, Vec<u8>) {
187 /// the panel the form it answers actually lives in.187 /// the panel the form it answers actually lives in.
188 fn section_of_call(call: &str) -> &'static str {188 fn section_of_call(call: &str) -> &'static str {
189 match call {189 match call {
190- "save_sender" | "send_test_mail" => "outgoing",190+ "save_sender" | "send_test_mail" | "check_sender" => "outgoing",
191 "save_limits" => "limits",191 "save_limits" => "limits",
192 "invite_member" | "set_role" | "resend_link" => "members",192 "invite_member" | "set_role" | "resend_link" => "members",
193 "send_message" => "message",193 "send_message" => "message",
@@ -436,6 +436,17 @@ async fn save_sender(
436 }436 }
437 Err(problem) => Err(problem),437 Err(problem) => Err(problem),
438 };438 };
439+ if outcome.is_ok() {
440+ // The settings just changed, so anything known about the old server is
441+ // about a server that is no longer configured. Ask again at once,
442+ // rather than leaving the panel unchecked until somebody presses a
443+ // button.
444+ probe_sender(
445+ mail(cx),
446+ accounts(cx).store().clone(),
447+ admin.workspace_id.clone(),
448+ );
449+ }
439 let refusal = match outcome {450 let refusal = match outcome {
440 Ok(()) => {451 Ok(()) => {
441 let _ = store452 let _ = store
@@ -462,6 +473,79 @@ async fn save_sender(
462 /// It goes to their own address and nowhere else. A test that could be473 /// It goes to their own address and nowhere else. A test that could be
463 /// pointed at an address somebody typed would be a way to make İzlek mail a474 /// pointed at an address somebody typed would be a way to make İzlek mail a
464 /// stranger on demand, which is a thing worth not building.475 /// stranger on demand, which is a thing worth not building.
476+/// How long to wait for a mail server before writing the attempt off.
477+///
478+/// Long enough for a slow but healthy server on a bad link, short enough that
479+/// an admin who mistyped the port is told while still looking at the screen.
480+const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
481+
482+/// Asks the mail server whether it would take mail from us, and writes down
483+/// what it said.
484+///
485+/// Nothing is sent to anybody: this is a handshake — connect, TLS, hello,
486+/// authenticate, hang up. Spawned rather than awaited by its callers so that
487+/// saving the settings stays as fast as saving anything else; the result
488+/// announces itself on the live channel, so the panel catches up on its own a
489+/// moment later without anybody reloading.
490+fn probe_sender(
491+ engine: crate::server::Mail,
492+ store: std::sync::Arc<dyn Store>,
493+ workspace_id: String,
494+) {
495+ tokio::spawn(async move {
496+ // This is the bound that actually does the work, not the transport's
497+ // own. Measured: a socket that accepts the connection and then never
498+ // says a word is NOT caught by lettre's `timeout` — the probe sat
499+ // there until this fired. A probe that never records leaves the panel
500+ // on "Unchecked" forever, with nothing to tell anybody it is stuck, so
501+ // something outside the library has to be the backstop.
502+ let dialled = tokio::time::timeout(PROBE_TIMEOUT, engine.check()).await;
503+ let outcome = match dialled {
504+ Ok(outcome) => outcome,
505+ Err(_) => Some(Err(izlek_core::MailError::retryable(
506+ "the mail server did not answer",
507+ ))),
508+ };
509+ let Some(outcome) = outcome else {
510+ // No engine in this process. Nothing to say, and a failure written
511+ // down here would be about this build rather than these settings.
512+ return;
513+ };
514+ let at = time::OffsetDateTime::now_utc();
515+ let check = match outcome {
516+ Ok(took) => SenderCheck {
517+ at,
518+ took_ms: took.whole_milliseconds().max(0) as u64,
519+ error: None,
520+ },
521+ Err(problem) => SenderCheck {
522+ at,
523+ took_ms: 0,
524+ // Built from what the server said, never from what we sent it.
525+ error: Some(problem.message.clone()),
526+ },
527+ };
528+ if let Err(problem) = store.record_sender_check(&workspace_id, check).await {
529+ eprintln!("store error: {problem}");
530+ }
531+ });
532+}
533+
534+/// Dials the mail server without sending anything, on an admin's say-so.
535+#[route(POST "/api/check_sender")]
536+async fn check_sender(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
537+ let admin = match require_admin(cx).await {
538+ Ok(admin) => admin,
539+ Err(refusal) => return Ok(saved_or_refused("check_sender", Some(refusal))),
540+ };
541+ probe_sender(
542+ mail(cx),
543+ accounts(cx).store().clone(),
544+ admin.workspace_id.clone(),
545+ );
546+ Ok(saved_or_refused("check_sender", None))
547+}
548+
465 #[route(POST "/api/send_test_mail")]549 #[route(POST "/api/send_test_mail")]
466 async fn send_test_mail(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {550 async fn send_test_mail(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
467 let admin = match require_admin(cx).await {551 let admin = match require_admin(cx).await {
@@ -864,6 +948,12 @@ struct TestResult {
864 error: Option<String>,948 error: Option<String>,
865 }949 }
866 950
951+/// The last handshake, rendered.
952+struct CheckResult {
953+ moment: String,
954+ error: Option<String>,
955+}
956+
867 /// The sender as the admin's screen may see it, plus the last test's957 /// The sender as the admin's screen may see it, plus the last test's
868 /// outcome — persisted, so it survives the reload the redirect gives it958 /// outcome — persisted, so it survives the reload the redirect gives it
869 /// rather than living only in this request's memory.959 /// rather than living only in this request's memory.
@@ -875,18 +965,54 @@ struct Sender {
875 from_address: String,965 from_address: String,
876 password_set: bool,966 password_set: bool,
877 test: Option<TestResult>,967 test: Option<TestResult>,
968+ /// How the last handshake went, and when. `None` means nobody has asked
969+ /// the server yet since these settings were saved.
970+ check: Option<CheckResult>,
878 /// The origin mailed links point at, empty when the configured one is971 /// The origin mailed links point at, empty when the configured one is
879 /// still in use.972 /// still in use.
880 public_url: String,973 public_url: String,
881 }974 }
882 975
976+/// What the panel says about the mail server, in the order the states happen.
977+///
978+/// The point of four states rather than two is that "the fields are filled in"
979+/// and "the server let us in" are different facts, and the old chip said
980+/// `Connected` for the first. A host typed correctly with the wrong password
981+/// showed green while every mail was refused.
982+#[derive(PartialEq, Eq)]
983+enum Standing {
984+ /// Something the sender needs is missing.
985+ NotConfigured,
986+ /// Complete, but nobody has asked the server yet.
987+ Unchecked,
988+ /// The server accepted our credentials, at this moment.
989+ Connected(String),
990+ /// The server would not have us, in its own words.
991+ Refused(String),
992+}
993+
883 impl Sender {994 impl Sender {
884- fn is_connected(&self) -> bool {995+ /// Whether the form holds everything a sender needs. Says nothing about
996+ /// whether any of it is right — see [`Standing`].
997+ fn is_complete(&self) -> bool {
885 !self.host.trim().is_empty()998 !self.host.trim().is_empty()
886 && !self.username.trim().is_empty()999 && !self.username.trim().is_empty()
887 && !self.from_address.trim().is_empty()1000 && !self.from_address.trim().is_empty()
888 && self.password_set1001 && self.password_set
889 }1002 }
1003+
1004+ fn standing(&self) -> Standing {
1005+ if !self.is_complete() {
1006+ return Standing::NotConfigured;
1007+ }
1008+ match &self.check {
1009+ None => Standing::Unchecked,
1010+ Some(check) => match &check.error {
1011+ Some(said) => Standing::Refused(said.clone()),
1012+ None => Standing::Connected(check.moment.clone()),
1013+ },
1014+ }
1015+ }
890 }1016 }
891 1017
892 async fn sender_now(cx: &Cx, zone: time::UtcOffset) -> Result<Sender> {1018 async fn sender_now(cx: &Cx, zone: time::UtcOffset) -> Result<Sender> {
@@ -900,6 +1026,7 @@ async fn sender_now(cx: &Cx, zone: time::UtcOffset) -> Result<Sender> {
900 from_address: String::new(),1026 from_address: String::new(),
901 password_set: false,1027 password_set: false,
902 test: None,1028 test: None,
1029+ check: None,
903 public_url: String::new(),1030 public_url: String::new(),
904 },1031 },
905 Some(workspace) => Sender {1032 Some(workspace) => Sender {
@@ -917,6 +1044,10 @@ async fn sender_now(cx: &Cx, zone: time::UtcOffset) -> Result<Sender> {
917 took: test.error.is_none().then(|| took_label(test.took_ms)),1044 took: test.error.is_none().then(|| took_label(test.took_ms)),
918 error: test.error,1045 error: test.error,
919 }),1046 }),
1047+ check: workspace.sender_check.map(|check| CheckResult {
1048+ moment: izlek_core::detail::moment_label_in(check.at, zone),
1049+ error: check.error,
1050+ }),
920 public_url: workspace.public_url.unwrap_or_default(),1051 public_url: workspace.public_url.unwrap_or_default(),
921 },1052 },
922 })1053 })
@@ -1193,20 +1324,41 @@ async fn settings_page(cx: &Cx) -> Result {
1193 }1324 }
1194 1325
1195 if section == Section::Outgoing && let Some(sender) = &sender {1326 if section == Section::Outgoing && let Some(sender) = &sender {
1196- let connected = sender.is_connected();1327+ let standing = sender.standing();
1328+ let complete = sender.is_complete();
1197 let password_set = sender.password_set;1329 let password_set = sender.password_set;
1330+ // One chip, four states. `Connected` carries the moment the
1331+ // server said so, because the claim is about a moment: a
1332+ // password rotated since is not something this can know.
1333+ let (chip_class, chip_text) = match &standing {
1334+ Standing::NotConfigured => {
1335+ ("chip chip-off", t(lang, Key::NotConfiguredChip).to_string())
1336+ }
1337+ Standing::Unchecked => {
1338+ ("chip chip-off", t(lang, Key::Unchecked).to_string())
1339+ }
1340+ Standing::Connected(at) => (
1341+ "chip chip-connected",
1342+ format!("{} {}", t(lang, Key::Connected), at),
1343+ ),
1344+ Standing::Refused(_) => {
1345+ ("chip chip-off", t(lang, Key::Refused).to_string())
1346+ }
1347+ };
1198 <section class="panel" id="outgoing">1348 <section class="panel" id="outgoing">
1199 <div class="panel-head">1349 <div class="panel-head">
1200 <h2 class="panel-title">(t(lang, Key::OutgoingMail))</h2>1350 <h2 class="panel-title">(t(lang, Key::OutgoingMail))</h2>
1201 <span class="chip chip-admin">(t(lang, Key::AdminOnly))</span>1351 <span class="chip chip-admin">(t(lang, Key::AdminOnly))</span>
1202- if connected {1352+ <span class=(chip_class)>(chip_text)</span>
1203- <span class="chip chip-connected">(t(lang, Key::Connected))</span>
1204- } else {
1205- <span class="chip chip-off">(t(lang, Key::NotConfiguredChip))</span>
1206- }
1207 </div>1353 </div>
1208 <div class="panel-body">1354 <div class="panel-body">
1209- if !connected {1355+ // The server's own words when it refused us:
1356+ // "535 authentication failed" is something an admin
1357+ // can act on, and a bare chip is not.
1358+ if let Standing::Refused(said) = &standing {
1359+ <p class="panel-lede">(said)</p>
1360+ }
1361+ if !complete {
1210 <p class="panel-lede">(t(lang, Key::NotConnectedNote))</p>1362 <p class="panel-lede">(t(lang, Key::NotConnectedNote))</p>
1211 }1363 }
1212 <form method="post" action="/api/save_sender" id="sender-settings">1364 <form method="post" action="/api/save_sender" id="sender-settings">
@@ -1282,6 +1434,11 @@ async fn settings_page(cx: &Cx) -> Result {
1282 </form>1434 </form>
1283 <div class="panel-foot panel-foot-split">1435 <div class="panel-foot panel-foot-split">
1284 <div class="foot-side">1436 <div class="foot-side">
1437+ <form method="post" action="/api/check_sender">
1438+ <button class="quiet" type="submit" disabled=(!complete)>
1439+ (t(lang, Key::CheckConnection))
1440+ </button>
1441+ </form>
1285 <form method="post" action="/api/send_test_mail">1442 <form method="post" action="/api/send_test_mail">
1286 <button class="quiet" type="submit">(t(lang, Key::SendTestMail))</button>1443 <button class="quiet" type="submit">(t(lang, Key::SendTestMail))</button>
1287 </form>1444 </form>
crates/izlek-web/src/smtp.rsmodified+43 -0
@@ -38,6 +38,16 @@ pub struct Sending {
38 pub from: String,38 pub from: String,
39 }39 }
40 40
41+/// How long to wait on a mail server that has accepted the connection and then
42+/// stopped talking.
43+///
44+/// This bounds a server that stalls mid-conversation, and it is why a send
45+/// cannot hang forever. It is NOT sufficient on its own: measured, a socket
46+/// that accepts the connection and then says nothing at all is not caught by
47+/// it, which is why the settings probe wraps its own timeout around the whole
48+/// call. Both are needed — this one for sends, which nothing else bounds.
49+const REPLY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
50+
41 /// A sender holding one connection pool.51 /// A sender holding one connection pool.
42 pub struct Smtp {52 pub struct Smtp {
43 transport: AsyncSmtpTransport<Tokio1Executor>,53 transport: AsyncSmtpTransport<Tokio1Executor>,
@@ -63,6 +73,7 @@ impl Smtp {
63 Ok(Self {73 Ok(Self {
64 transport: builder74 transport: builder
65 .port(mail.port)75 .port(mail.port)
76+ .timeout(Some(REPLY_TIMEOUT))
66 .credentials(Credentials::new(77 .credentials(Credentials::new(
67 mail.username.clone(),78 mail.username.clone(),
68 mail.password.clone(),79 mail.password.clone(),
@@ -108,6 +119,31 @@ impl Mailer for Smtp {
108 }119 }
109 })120 })
110 }121 }
122+
123+ async fn check(&self) -> Result<(), MailError> {
124+ // `test_connection` opens a connection the same way a send does —
125+ // TLS, EHLO, and AUTH with these credentials — then NOOPs and leaves.
126+ // So a pass means the host, the port, the encryption and the password
127+ // are all right. It does NOT mean mail will arrive: the from-address
128+ // is checked by the server per envelope, and an account that logs in
129+ // fine can still be refused as a sender.
130+ match self.transport.test_connection().await {
131+ Ok(true) => Ok(()),
132+ // Connected, then would not answer a NOOP. Nothing about the
133+ // settings is proven wrong, so it is worth asking again.
134+ Ok(false) => Err(MailError::retryable(
135+ "the mail server accepted the connection and then went quiet",
136+ )),
137+ Err(problem) => {
138+ let said = problem.to_string();
139+ Err(if problem.is_permanent() {
140+ MailError::permanent(said)
141+ } else {
142+ MailError::retryable(said)
143+ })
144+ }
145+ }
146+ }
111 }147 }
112 148
113 /// The mailer the engine actually holds: it reads the workspace's sender at149 /// The mailer the engine actually holds: it reads the workspace's sender at
@@ -200,4 +236,11 @@ impl Mailer for WorkspaceSmtp {
200 };236 };
201 self.transport(&want).await?.send(mail).await237 self.transport(&want).await?.send(mail).await
202 }238 }
239+
240+ async fn check(&self) -> Result<(), MailError> {
241+ let Some(want) = self.sending().await? else {
242+ return Err(MailError::unsent("no sender configured"));
243+ };
244+ self.transport(&want).await?.check().await
245+ }
203 }246 }
crates/izlek-web/tests/http.rsmodified+425 -4
@@ -44,11 +44,22 @@ fn asset_dir() -> PathBuf {
44 ))44 ))
45 }45 }
46 46
47+/// A live connection in the suite outlives any test that reads it. The bound
48+/// on a live test is [`live_until`]'s own timeout — waiting for the frame it
49+/// expects — not this window: a window short enough to end the stream promptly
50+/// is also short enough to lose the race on a loaded machine, which is a
51+/// flaky test rather than a fast one.
52+const TEST_LIVE_WINDOW: izlek_web::live::LiveWindow =
53+ izlek_web::live::LiveWindow(std::time::Duration::from_secs(10));
54+
47 /// A throwaway workspace: its own database file and its own router.55 /// A throwaway workspace: its own database file and its own router.
48 struct App {56 struct App {
49 dir: PathBuf,57 dir: PathBuf,
50 router: Router,58 router: Router,
51 store: Arc<dyn Store>,59 store: Arc<dyn Store>,
60+ /// Stands in for Ctrl+C. Held so a test can stop this router the way the
61+ /// process stops the real one.
62+ stop: tokio::sync::watch::Sender<bool>,
52 }63 }
53 64
54 impl App {65 impl App {
@@ -61,6 +72,7 @@ impl App {
61 .unwrap(),72 .unwrap(),
62 );73 );
63 let accounts = Accounts::new(store.clone(), base_url);74 let accounts = Accounts::new(store.clone(), base_url);
75+ let (stop, _) = tokio::sync::watch::channel(false);
64 let router = Router::builder()76 let router = Router::builder()
65 .discover()77 .discover()
66 .layer(78 .layer(
@@ -73,9 +85,12 @@ impl App {
73 .expect("run `topcoat asset bundle` before the http suite"),85 .expect("run `topcoat asset bundle` before the http suite"),
74 )86 )
75 .app_context(accounts)87 .app_context(accounts)
88+ .app_context(izlek_web::photo::PhotoStamps::default())
89+ .app_context(TEST_LIVE_WINDOW)
90+ .app_context(izlek_web::live::Shutdown(stop.subscribe()))
76 .app_context(mail)91 .app_context(mail)
77 .build();92 .build();
78- Self { dir, router, store }93+ Self { dir, router, store, stop }
79 }94 }
80 95
81 async fn open() -> Self {96 async fn open() -> Self {
@@ -99,6 +114,7 @@ impl App {
99 "https://izlek.sh",114 "https://izlek.sh",
100 ));115 ));
101 let accounts = Accounts::new(store.clone(), "https://izlek.sh");116 let accounts = Accounts::new(store.clone(), "https://izlek.sh");
117+ let (stop, _) = tokio::sync::watch::channel(false);
102 let router = Router::builder()118 let router = Router::builder()
103 .discover()119 .discover()
104 .layer(120 .layer(
@@ -111,9 +127,29 @@ impl App {
111 .expect("run `topcoat asset bundle` before the http suite"),127 .expect("run `topcoat asset bundle` before the http suite"),
112 )128 )
113 .app_context(accounts)129 .app_context(accounts)
130+ .app_context(izlek_web::photo::PhotoStamps::default())
131+ .app_context(TEST_LIVE_WINDOW)
132+ .app_context(izlek_web::live::Shutdown(stop.subscribe()))
114 .app_context(Mail::sending(engine))133 .app_context(Mail::sending(engine))
115 .build();134 .build();
116- Self { dir, router, store }135+ Self { dir, router, store, stop }
136+ }
137+
138+ /// Opens `/api/live`. The response is returned as soon as the handler has
139+ /// subscribed, so a caller writes AFTER this returns and the announcement
140+ /// still lands in the feed.
141+ async fn live_open(
142+ &self,
143+ cookie: Option<&str>,
144+ ) -> topcoat::router::response::Response<Body> {
145+ let mut request = Request::builder().method("GET").uri("/api/live");
146+ if let Some(cookie) = cookie {
147+ request = request.header(
148+ header::COOKIE,
149+ HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),
150+ );
151+ }
152+ self.router.handle(request.body(Body::empty()).unwrap()).await
117 }153 }
118 154
119 /// The single workspace's id, read straight off the store: `TursoStore` is155 /// 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() {
1980 let page = app.get("/", Some(&cookie)).await;2016 let page = app.get("/", Some(&cookie)).await;
1981 let html = String::from_utf8_lossy(&page.bytes);2017 let html = String::from_utf8_lossy(&page.bytes);
1982 let (_, after) = html2018 let (_, after) = html
1983- .split_once("function swap(html, url, fresh, push)")2019+ .split_once("function swap(html, url, fresh, push, morphing)")
1984 .unwrap_or_else(|| panic!("no soft-nav swap on the board page: {html}"));2020 .unwrap_or_else(|| panic!("no soft-nav swap on the board page: {html}"));
1985 let body = after2021 let body = after
1986 .split_once("window.__izlekGo")2022 .split_once("window.__izlekGo")
@@ -3014,7 +3050,11 @@ async fn an_admin_sees_the_sender_and_never_a_password() {
3014 let html = String::from_utf8_lossy(&page.bytes);3050 let html = String::from_utf8_lossy(&page.bytes);
3015 assert!(html.contains("smtp.fastmail.com"), "{html}");3051 assert!(html.contains("smtp.fastmail.com"), "{html}");
3016 assert!(html.contains("izlek@izlek.sh"), "{html}");3052 assert!(html.contains("izlek@izlek.sh"), "{html}");
3017- assert!(html.contains("Connected"), "{html}");3053+ // Saved in full, and nobody has dialled the server — this router has no
3054+ // mail engine at all. "Connected" would be a claim about a handshake that
3055+ // never happened, which is the whole reason the chip has four states.
3056+ assert!(html.contains("Unchecked"), "{html}");
3057+ assert!(!html.contains("chip-connected"), "{html}");
3018 assert!(3058 assert!(
3019 !html.contains(SENDER_PASSWORD),3059 !html.contains(SENDER_PASSWORD),
3020 "the settings page carried the SMTP password: {html}"3060 "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() {
5167 assert!(cached.bytes.is_empty());5207 assert!(cached.bytes.is_empty());
5168 }5208 }
5169 5209
5210+/// The whole point of a versioned photo URL: replacing the photo must move
5211+/// the stamp the avatar renders, or the browser keeps serving the bytes it
5212+/// cached under the old URL and the replacement never shows.
5213+#[tokio::test]
5214+async fn a_replaced_photo_moves_the_avatar_url_stamp() {
5215+ let app = App::open().await;
5216+ let admin = admin(&app).await;
5217+ let admin_id = user_id(&app, "ada@izlek.sh").await;
5218+
5219+ app.post_multipart(
5220+ "/api/profile_photo",
5221+ Some(&admin),
5222+ &[],
5223+ Some(("me.png", "image/png", &PNG)),
5224+ )
5225+ .await;
5226+ let page = app.get("/settings", Some(&admin)).await;
5227+ let html = String::from_utf8_lossy(&page.bytes);
5228+ let first = avatar_stamp(&html, &admin_id).expect("avatar photo URL on the settings page");
5229+
5230+ let mut replaced = PNG;
5231+ replaced[11] ^= 0xff;
5232+ app.post_multipart(
5233+ "/api/profile_photo",
5234+ Some(&admin),
5235+ &[],
5236+ Some(("me.png", "image/png", &replaced)),
5237+ )
5238+ .await;
5239+ let page = app.get("/settings", Some(&admin)).await;
5240+ let html = String::from_utf8_lossy(&page.bytes);
5241+ let second = avatar_stamp(&html, &admin_id).expect("avatar photo URL after replace");
5242+
5243+ assert!(second > first, "stamp must move: {first} -> {second}");
5244+}
5245+
5246+/// The `?v=` on an avatar's `/photo/{id}` src, parsed out of a rendered page.
5247+fn avatar_stamp(html: &str, user_id: &str) -> Option<i64> {
5248+ let marker = format!("/photo/{user_id}?v=");
5249+ let rest = &html[html.find(&marker)? + marker.len()..];
5250+ let end = rest
5251+ .find(|c: char| !c.is_ascii_digit())
5252+ .unwrap_or(rest.len());
5253+ rest[..end].parse().ok()
5254+}
5255+
5170 /// The nav shows a page only to a role that can act on it: an admin's board5256 /// The nav shows a page only to a role that can act on it: an admin's board
5171 /// carries all four links, a member's carries neither Rules nor Logs.5257 /// carries all four links, a member's carries neither Rules nor Logs.
5172 #[tokio::test]5258 #[tokio::test]
@@ -6626,3 +6712,338 @@ async fn a_big_sheet_pages_down_its_rows_and_across_its_columns() {
6626 assert!(html.contains("sheet-table"), "the grid is gone: {html}");6712 assert!(html.contains("sheet-table"), "the grid is gone: {html}");
6627 assert!(!html.contains("Col A"), "row 4951 is not row 1: {html}");6713 assert!(!html.contains("Col A"), "row 4951 is not row 1: {html}");
6628 }6714 }
6715+
6716+
6717+// -- the live channel -------------------------------------------------------
6718+
6719+/// Reads a live connection until it says `needle`, or until `patience` runs
6720+/// out, and hands back everything it said. Bounded by the frame it is waiting
6721+/// for rather than by a fixed sleep: the positive assertions return the moment
6722+/// the announcement lands, and the negative ones spend their whole patience
6723+/// proving the silence.
6724+async fn live_until(
6725+ response: topcoat::router::response::Response<Body>,
6726+ needle: &str,
6727+ patience: std::time::Duration,
6728+) -> String {
6729+ use http_body_util::BodyExt;
6730+
6731+ let mut body = response.into_body();
6732+ let mut heard = String::new();
6733+ let deadline = tokio::time::Instant::now() + patience;
6734+ loop {
6735+ let left = deadline.saturating_duration_since(tokio::time::Instant::now());
6736+ if left.is_zero() {
6737+ return heard;
6738+ }
6739+ match tokio::time::timeout(left, body.frame()).await {
6740+ Err(_) => return heard,
6741+ Ok(None) => return heard,
6742+ Ok(Some(Err(_))) => return heard,
6743+ Ok(Some(Ok(frame))) => {
6744+ if let Some(chunk) = frame.data_ref() {
6745+ heard.push_str(&String::from_utf8_lossy(chunk));
6746+ if heard.contains(needle) {
6747+ return heard;
6748+ }
6749+ }
6750+ }
6751+ }
6752+ }
6753+}
6754+
6755+/// A browser nobody signed in gets no feed at all.
6756+#[tokio::test]
6757+async fn the_live_channel_refuses_a_signed_out_caller() {
6758+ let app = App::open().await;
6759+ admin(&app).await;
6760+ let response = app.live_open(None).await;
6761+ assert_eq!(response.status(), 401);
6762+}
6763+
6764+/// The role gate reaches the channel: a member is never told that an
6765+/// admin-only surface moved, because being told is itself knowing something
6766+/// about it. The assertion is on the raw bytes on purpose — the topic name
6767+/// must not appear at all, not merely go unrendered.
6768+#[tokio::test]
6769+async fn the_live_channel_never_names_an_admin_surface_to_a_member() {
6770+ let app = App::open().await;
6771+ let boss = admin(&app).await;
6772+ let member = invited(&app, &boss, "bo@izlek.sh", "Bo", Role::Member).await;
6773+
6774+ let member_feed = app.live_open(Some(&member)).await;
6775+ let admin_feed = app.live_open(Some(&boss)).await;
6776+
6777+ // An admin-only write: a mail rule.
6778+ let workspace_id = app.workspace_id().await;
6779+ let board = app.store.board(&workspace_id).await.unwrap().unwrap().id;
6780+ app.store
6781+ .create_mail_rule(
6782+ &board,
6783+ &izlek_core::store::Trigger::Created,
6784+ "Something happened",
6785+ izlek_core::store::Audience::Board,
6786+ time::OffsetDateTime::now_utc(),
6787+ false,
6788+ )
6789+ .await
6790+ .unwrap();
6791+
6792+ // The admin's stream is the clock: once it has the announcement, the
6793+ // member's has had every chance to receive one too.
6794+ let heard_by_admin = live_until(admin_feed, "rules", std::time::Duration::from_secs(10)).await;
6795+ let heard_by_member =
6796+ live_until(member_feed, "rules", std::time::Duration::from_millis(500)).await;
6797+
6798+ assert!(
6799+ !heard_by_member.contains("rules"),
6800+ "a member was told about the rules: {heard_by_member}"
6801+ );
6802+ assert!(
6803+ heard_by_admin.contains("rules"),
6804+ "the admin was not told about the rules: {heard_by_admin}"
6805+ );
6806+}
6807+
6808+/// A surface everybody can see is announced to everybody.
6809+#[tokio::test]
6810+async fn the_live_channel_announces_a_shared_surface_to_a_member() {
6811+ let app = App::open().await;
6812+ let boss = admin(&app).await;
6813+ let member = invited(&app, &boss, "bo@izlek.sh", "Bo", Role::Member).await;
6814+ let column = first_column(&app).await;
6815+
6816+ let feed = app.live_open(Some(&member)).await;
6817+ a_task(&app, &boss, &column, "Ship the exporter").await;
6818+ let heard = live_until(feed, "board", std::time::Duration::from_secs(10)).await;
6819+
6820+ assert!(heard.contains("board"), "no board announcement: {heard}");
6821+}
6822+
6823+/// The guard is what stops a soft navigation stacking a second `EventSource`
6824+/// on the tab: `swap()` re-executes every script it swaps in, so the script
6825+/// must refuse to run twice. Emitted once, and only once, per page.
6826+#[tokio::test]
6827+async fn the_live_script_is_emitted_once_and_guarded() {
6828+ let app = App::open().await;
6829+ let boss = admin(&app).await;
6830+ let html = String::from_utf8(app.get("/", Some(&boss)).await.bytes).unwrap();
6831+
6832+ assert_eq!(
6833+ html.matches("__izlekLive").count(),
6834+ 2,
6835+ "the live script should appear once, as a guard read and a guard set"
6836+ );
6837+ assert!(html.contains("EventSource('/api/live')"), "no live connection");
6838+}
6839+
6840+/// A signed-out page opens no stream: `/api/live` refuses it, and a tab on the
6841+/// sign-in screen would otherwise reconnect against that refusal forever.
6842+#[tokio::test]
6843+async fn a_signed_out_page_opens_no_live_connection() {
6844+ let app = App::open().await;
6845+ admin(&app).await;
6846+ let html = String::from_utf8(app.get("/", None).await.bytes).unwrap();
6847+ assert!(
6848+ !html.contains("__izlekLive"),
6849+ "the sign-in page carries the live script"
6850+ );
6851+}
6852+
6853+/// Text that goes stale on the clock rather than on a write carries the mark
6854+/// the tick looks for — a queued mail's next-try time is the case that started
6855+/// this: nothing writes when the minute changes.
6856+#[tokio::test]
6857+async fn a_queued_mails_next_try_is_marked_for_the_tick() {
6858+ let app = App::open().await;
6859+ let boss = admin(&app).await;
6860+ app.store
6861+ .queue_notice(
6862+ "bo@izlek.sh",
6863+ "Your \u{130}zlek sign-in link",
6864+ "body",
6865+ time::OffsetDateTime::now_utc(),
6866+ )
6867+ .await
6868+ .unwrap();
6869+ let html = String::from_utf8(app.get("/logs?section=queue", Some(&boss)).await.bytes).unwrap();
6870+ assert!(
6871+ html.contains("data-tick"),
6872+ "the queue's next-try stamp is not marked for the tick"
6873+ );
6874+}
6875+
6876+/// A live update changes only what actually changed. It morphs the fetched
6877+/// document onto the live one instead of replacing the body, which is what
6878+/// leaves an open dropdown open, a caret where it was and a half-typed comment
6879+/// intact — not because any of those is special-cased, but because nothing
6880+/// touched them. Asserted here so a refactor back to a wholesale replace fails
6881+/// loudly rather than quietly making the app unusable while anyone is typing.
6882+#[tokio::test]
6883+async fn a_live_update_morphs_rather_than_replacing_the_page() {
6884+ let app = App::open().await;
6885+ let boss = admin(&app).await;
6886+ let html = String::from_utf8(app.get("/", Some(&boss)).await.bytes).unwrap();
6887+
6888+ assert!(html.contains("function morph("), "no morph: the live path replaces the page");
6889+ assert!(
6890+ html.contains("swap(t, r.url, false, false, true)"),
6891+ "the live refresh does not ask for a morphing swap"
6892+ );
6893+ // The dropdown's trigger and panel are built by script and are in no
6894+ // server response; a morph that did not know that would delete them.
6895+ assert!(
6896+ html.contains("function clientMade(") && html.contains("dd-panel"),
6897+ "the morph would delete the dropdown's own nodes as strays"
6898+ );
6899+ // Navigations and form posts must still replace: restoring a sent comment
6900+ // over the server's cleared box would look like the message never went.
6901+ assert!(
6902+ html.contains("document.body.replaceChildren()"),
6903+ "the full-replace path is gone, so form posts would carry stale state"
6904+ );
6905+ assert!(html.contains("captureFields"), "the swap captures no field state");
6906+ assert!(html.contains("restoreFields"), "the swap restores no field state");
6907+}
6908+
6909+/// A promise about the future is shown to the second. A retry that says 16:42
6910+/// but fires at 16:42:47 reads as forty-seven seconds of broken clock to
6911+/// whoever is watching one; the queue names the second it means.
6912+#[tokio::test]
6913+async fn the_queues_next_try_is_shown_to_the_second() {
6914+ let app = App::open().await;
6915+ let boss = admin(&app).await;
6916+ app.store
6917+ .queue_notice(
6918+ "bo@izlek.sh",
6919+ "Subject",
6920+ "body",
6921+ time::OffsetDateTime::now_utc() + time::Duration::hours(1),
6922+ )
6923+ .await
6924+ .unwrap();
6925+
6926+ let html = String::from_utf8(app.get("/logs?section=queue", Some(&boss)).await.bytes).unwrap();
6927+ let (_, after) = html.split_once("rule-stamp").expect("no next-try stamp on the queue");
6928+ let stamp: String = after.chars().take(60).collect();
6929+ // hh:mm:ss — three groups, not two.
6930+ let seconds = stamp
6931+ .split(|c: char| !c.is_ascii_digit() && c != ':')
6932+ .find(|part| part.matches(':').count() == 2);
6933+ assert!(
6934+ seconds.is_some(),
6935+ "the next-try stamp is not shown to the second: {stamp}"
6936+ );
6937+}
6938+
6939+/// The chip reports what the server said, not what the form contains. A
6940+/// refusal shows the server's own words, because "535 authentication failed"
6941+/// is something an admin can act on and a grey chip is not.
6942+#[tokio::test]
6943+async fn a_refused_handshake_is_shown_with_what_the_server_said() {
6944+ let app = App::open().await;
6945+ let admin_cookie = admin(&app).await;
6946+ assert!(sender_saved(&app, &admin_cookie).await);
6947+
6948+ let workspace = app.workspace_id().await;
6949+ app.store
6950+ .record_sender_check(
6951+ &workspace,
6952+ izlek_core::store::SenderCheck {
6953+ at: time::OffsetDateTime::now_utc(),
6954+ took_ms: 0,
6955+ error: Some("535 authentication failed".into()),
6956+ },
6957+ )
6958+ .await
6959+ .unwrap();
6960+
6961+ let html = String::from_utf8(
6962+ app.get("/settings?section=outgoing", Some(&admin_cookie))
6963+ .await
6964+ .bytes,
6965+ )
6966+ .unwrap();
6967+ assert!(html.contains("Refused"), "{html}");
6968+ assert!(
6969+ html.contains("535 authentication failed"),
6970+ "the server's words are not on the page: {html}"
6971+ );
6972+ assert!(!html.contains("chip-connected"), "a refusal rendered as connected");
6973+}
6974+
6975+/// A handshake that worked says when, because the claim is about a moment: a
6976+/// password rotated an hour later is not something the panel can know.
6977+#[tokio::test]
6978+async fn a_passed_handshake_says_when_it_passed() {
6979+ let app = App::open().await;
6980+ let admin_cookie = admin(&app).await;
6981+ assert!(sender_saved(&app, &admin_cookie).await);
6982+
6983+ let workspace = app.workspace_id().await;
6984+ app.store
6985+ .record_sender_check(
6986+ &workspace,
6987+ izlek_core::store::SenderCheck {
6988+ at: time::OffsetDateTime::now_utc(),
6989+ took_ms: 84,
6990+ error: None,
6991+ },
6992+ )
6993+ .await
6994+ .unwrap();
6995+
6996+ let html = String::from_utf8(
6997+ app.get("/settings?section=outgoing", Some(&admin_cookie))
6998+ .await
6999+ .bytes,
7000+ )
7001+ .unwrap();
7002+ assert!(html.contains("chip-connected"), "{html}");
7003+ assert!(html.contains("Connected"), "{html}");
7004+}
7005+
7006+/// Dialling the mail server is an admin's business.
7007+#[tokio::test]
7008+async fn a_member_may_not_check_the_sender() {
7009+ let app = App::open().await;
7010+ let boss = admin(&app).await;
7011+ let member = invited(&app, &boss, "bo@izlek.sh", "Bo", Role::Member).await;
7012+ let answer = app.post("/api/check_sender", Some(&member), &[]).await;
7013+ assert_ne!(answer.body, "null", "a member was allowed to dial the server");
7014+}
7015+
7016+/// An open live stream must not be something the shutdown has to wait out.
7017+///
7018+/// The server stops accepting connections and then gives in-flight requests
7019+/// thirty seconds to finish. A live stream intends to sit there for the whole
7020+/// window, and every open tab is one, so before this the answer to Ctrl+C was
7021+/// a thirty-second pause — measured at 30.00s with three tabs open, 0.003s
7022+/// after. The stream is told, and it ends.
7023+#[tokio::test]
7024+async fn a_live_stream_ends_when_the_server_is_told_to_stop() {
7025+ use http_body_util::BodyExt;
7026+
7027+ let app = App::open().await;
7028+ let admin_cookie = admin(&app).await;
7029+ let mut body = app.live_open(Some(&admin_cookie)).await.into_body();
7030+
7031+ // It is open and it is staying open: nothing has changed, so a read now
7032+ // finds nothing to say.
7033+ assert!(
7034+ tokio::time::timeout(std::time::Duration::from_millis(200), body.frame())
7035+ .await
7036+ .is_err(),
7037+ "the stream ended on its own before anything asked it to"
7038+ );
7039+
7040+ app.stop.send(true).unwrap();
7041+
7042+ // The window is ten seconds and the patience here is one, so a pass cannot
7043+ // be the window expiring.
7044+ let ended = tokio::time::timeout(std::time::Duration::from_secs(1), async {
7045+ while let Some(Ok(_)) = body.frame().await {}
7046+ })
7047+ .await;
7048+ assert!(ended.is_ok(), "the stream outlived the stop");
7049+}