}
+}
+
+/// Every path that matches no page raises a `NotFoundError`, so it renders
+/// through `root_layout`'s catch below rather than the router's bare default.
+/// `/` itself is served by `landing` above and never reaches this route.
+#[page("/{*path}")]
+async fn missing() -> Result {
+ Err(not_found().into())
+}
+
+/// `style/main.scss`, compiled by `build.rs` into `assets/main.css`.
+const STYLE: Asset = asset!("assets/main.css");
+
+#[layout("/")]
+async fn root_layout(slot: Result) -> Result {
+ let content = match slot {
+ Err(error) if error.downcast_ref::().is_some() => view! {
+ (StatusCode::NOT_FOUND)
+
+
"Nothing at this address."
+
+ },
+ content => content,
+ }?;
+
+ view! {
+
+
+
+
+
+
+
+
+ "Izlek"
+
+ topcoat::runtime::script()
+ topcoat::dev::script()
+
+
+ (content)
+
+
+ }
+}
diff --git a/crates/izlek-topcoat/src/lib.rs b/crates/izlek-topcoat/src/lib.rs
new file mode 100644
index 0000000..2ef9765
--- /dev/null
+++ b/crates/izlek-topcoat/src/lib.rs
@@ -0,0 +1,7 @@
+// topcoat's `view!` nests as deeply as leptos's did for the same pages, so
+// the raised limit carries over from day one rather than waiting for the
+// first overflow.
+#![recursion_limit = "256"]
+
+pub mod layout;
+pub mod smtp;
diff --git a/crates/izlek-topcoat/src/main.rs b/crates/izlek-topcoat/src/main.rs
new file mode 100644
index 0000000..03d931c
--- /dev/null
+++ b/crates/izlek-topcoat/src/main.rs
@@ -0,0 +1,93 @@
+use izlek_core::accounts::Accounts;
+use izlek_core::store::TursoStore;
+use std::sync::Arc;
+use topcoat::Result;
+use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};
+use topcoat::cookie::RouterBuilderCookieExt;
+use topcoat::router::{Router, RouterBuilderDiscoverExt, route};
+
+#[route(GET "/healthz")]
+async fn healthz() -> Result<&'static str> {
+ Ok("ok")
+}
+
+#[tokio::main]
+async fn main() {
+ // config/izlek.toml is read here, before anything is opened, and written with
+ // development defaults if it is not there yet. A broken key stops the
+ // boot with its name in the message: the failure this prevents is not an
+ // empty database, it is a second Izlek writing a different file while
+ // everyone believes they share a board.
+ let config = match izlek_core::Config::load() {
+ Ok(config) => config,
+ Err(problem) => {
+ eprintln!("izlek: {problem}");
+ std::process::exit(2);
+ }
+ };
+ // Said once, so the answer to "which file are we on" lives in the log.
+ for line in config.report() {
+ println!("izlek {line}");
+ }
+
+ // One process per database file: Turso is a single-writer engine and a
+ // second process on the same file loses writes rather than queueing.
+ //
+ // `open` applies any unapplied migration before it returns.
+ let store = TursoStore::open(&config.database.to_string_lossy())
+ .await
+ .expect("failed to open the database");
+ let store: Arc = Arc::new(store);
+ let accounts = Accounts::new(store.clone(), config.base_url.clone());
+
+ // The engine is always built, because a sender can appear at any moment:
+ // an admin fills the panel in and the next sweep sends what was held. It
+ // holds one connection pool, rebuilt only when the settings behind it
+ // change, and two things use it — every committed crossing, and the sweep.
+ let engine = Arc::new(izlek_core::MailEngine::new(
+ store.clone(),
+ Arc::new(izlek_topcoat::smtp::WorkspaceSmtp::new(store.clone())),
+ config.base_url.clone(),
+ ));
+ tokio::spawn(sweep(engine.clone()));
+
+ let router = Router::builder()
+ .discover()
+ .cookies()
+ .assets(AssetBundle::load().expect("failed to load the asset bundle"))
+ .app_context(accounts)
+ .app_context(engine)
+ .build();
+
+ topcoat::start(router).await.expect("server error");
+}
+
+/// Retries what a mail server refused earlier and picks up anything a crash
+/// left claimed but unsent.
+///
+/// A minute is short enough that the first retry of a host that blinked lands
+/// while somebody is still looking at the board, and long enough that a host
+/// which is properly down is not hammered — the wait per send widens on its
+/// own, and a send that has used its attempts is written off rather than
+/// carried forever.
+async fn sweep(engine: std::sync::Arc) {
+ /// Enough that a morning's backlog clears in a few passes, few enough that
+ /// one pass cannot sit on the mail server for minutes.
+ const PER_PASS: u32 = 50;
+
+ let mut every_minute = tokio::time::interval(std::time::Duration::from_secs(60));
+ loop {
+ every_minute.tick().await;
+ match engine
+ .deliver_owed(time::OffsetDateTime::now_utc(), PER_PASS)
+ .await
+ {
+ Ok(report) if report.sent + report.failed + report.abandoned > 0 => println!(
+ "izlek mail sweep: {} sent, {} to retry, {} given up on",
+ report.sent, report.failed, report.abandoned
+ ),
+ Ok(_) => {}
+ Err(problem) => eprintln!("izlek mail sweep could not read the ledger: {problem}"),
+ }
+ }
+}
diff --git a/crates/izlek-topcoat/src/smtp.rs b/crates/izlek-topcoat/src/smtp.rs
new file mode 100644
index 0000000..2768e3d
--- /dev/null
+++ b/crates/izlek-topcoat/src/smtp.rs
@@ -0,0 +1,203 @@
+//! The `Mailer` the engine talks to when the mail is real.
+//!
+//! Everything about SMTP stops here. The engine knows a send was accepted or
+//! refused, and whether the refusal is worth trying again; it does not know
+//! what a 550 is. Keeping the protocol in one file is also what makes the
+//! engine testable — the tests hand it a mailer that remembers instead of
+//! connecting.
+//!
+//! The credentials come from the workspace's own settings, written by an admin
+//! on the Settings screen. They are never in a literal in here, and the
+//! password is not in anything this module logs or puts in an error message: a
+//! refusal that quoted the password would put it in the ledger, where an admin
+//! screen would later print it.
+//!
+//! Because the sender is editable while the process runs, the transport cannot
+//! be built once at boot. [`WorkspaceSmtp`] holds the last one it built and the
+//! settings it was built from; a send whose settings still match reuses the
+//! connection pool, and a send after an edit builds a new one and drops the old.
+
+use std::sync::Arc;
+
+use izlek_core::store::Store;
+use izlek_core::mail::{MailError, Mailer, Outgoing};
+use lettre::message::header::ContentType;
+use lettre::transport::smtp::authentication::Credentials;
+use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
+
+/// The sender as the mailer needs it: what the admin typed, password included.
+/// It exists only inside this module and inside the store; nothing that can
+/// reach a response body holds one.
+#[derive(Clone, PartialEq, Eq)]
+pub struct Sending {
+ pub host: String,
+ pub port: u16,
+ pub username: String,
+ pub password: String,
+ /// `Name ` if a name was given, the bare address otherwise.
+ pub from: String,
+}
+
+/// A sender holding one connection pool.
+pub struct Smtp {
+ transport: AsyncSmtpTransport,
+ from: String,
+}
+
+impl Smtp {
+ /// Builds the transport. Fails only on a host name TLS cannot be set up
+ /// against — a server that is merely unreachable is discovered per send,
+ /// as a retryable refusal, which is the honest place for it.
+ pub fn new(mail: &Sending) -> Result {
+ // 465 is submissions, where TLS is up before the greeting. Everything
+ // else — 587 above all — is submission, where the session starts in
+ // the clear and is upgraded. Both are encrypted before the password
+ // moves; a plaintext session is not among the options.
+ let builder = if mail.port == 465 {
+ AsyncSmtpTransport::::relay(&mail.host)
+ } else {
+ AsyncSmtpTransport::::starttls_relay(&mail.host)
+ }
+ .map_err(|problem| format!("{} cannot be reached over TLS: {problem}", mail.host))?;
+
+ Ok(Self {
+ transport: builder
+ .port(mail.port)
+ .credentials(Credentials::new(
+ mail.username.clone(),
+ mail.password.clone(),
+ ))
+ .build(),
+ from: mail.from.clone(),
+ })
+ }
+}
+
+#[async_trait::async_trait]
+impl Mailer for Smtp {
+ async fn send(&self, mail: &Outgoing) -> Result<(), MailError> {
+ let built =
+ Message::builder()
+ .from(self.from.parse().map_err(|_| {
+ MailError::permanent(format!("{} is not an address", self.from))
+ })?)
+ .to(mail
+ .to
+ .parse()
+ .map_err(|_| MailError::permanent(format!("{} is not an address", mail.to)))?)
+ .subject(&mail.subject)
+ .header(ContentType::TEXT_PLAIN)
+ .body(mail.body.clone())
+ .map_err(|problem| MailError::permanent(problem.to_string()))?;
+
+ self.transport
+ .send(built)
+ .await
+ .map(|_| ())
+ .map_err(|problem| {
+ let said = problem.to_string();
+ // A permanent SMTP code is the server saying the address will not
+ // work today or tomorrow — a mailbox that does not exist, a domain
+ // that does not accept us. Everything else, a timeout above all,
+ // is worth another attempt: the alternative is losing a mail
+ // because a host restarted at the wrong moment.
+ if problem.is_permanent() {
+ MailError::permanent(said)
+ } else {
+ MailError::retryable(said)
+ }
+ })
+ }
+}
+
+/// The mailer the engine actually holds: it reads the workspace's sender at
+/// send time, so an admin who fixes a typo in the host does not have to restart
+/// anything for the next mail to go out.
+pub struct WorkspaceSmtp {
+ store: Arc,
+ /// The live transport and the settings it was built from. Rebuilt only when
+ /// those settings change — building one per send would throw away the
+ /// connection pool that makes a backlog drain quickly.
+ current: tokio::sync::Mutex