larust_notifications/lib.rs
1//! Durable, per-notifiable, read-tracked notifications - Laravel's
2//! *database* notification channel - plus a compile-time-checked,
3//! multi-channel delivery builder ([`to`]) covering the database and
4//! mail channels together. Not Laravel's full `Notification`/`via()`/
5//! `toMail()`/`toDatabase()`/`toBroadcast()` shape, and deliberately so.
6//!
7//! Laravel's `Notification` has *optional* per-channel render methods,
8//! decided at runtime by `via($notifiable)`. There's no clean way to
9//! express "this trait method is conditionally required based on another
10//! method's runtime return value" in Rust without `Option`-returning
11//! defaults - and this codebase's closest sibling traits (`Mailable`,
12//! `larust_queue::Job`, `larust_auth::Authenticatable`) are all
13//! zero-default-method traits, deliberately, specifically to force a
14//! compile error on a real gap rather than a silently-never-implemented
15//! one. Building Laravel's full shape here would be the first trait in
16//! this codebase to break that convention - so [`to`]'s builder doesn't
17//! decide channels at runtime from the notification itself either. Each
18//! channel is opted into *explicitly*, at the call site
19//! (`.database().mail()`), and each of those methods carries its own
20//! real trait bound (`N: Notification` for `.database()`; `N:
21//! MailNotification, U: MailNotifiable` for `.mail()`) - asking for a
22//! channel a notification/notifiable doesn't actually implement is a
23//! compile error pointing at the missing `impl`, not a channel silently
24//! skipped at runtime:
25//!
26//! ```ignore
27//! notification::to(&user, &InvoiceSent { invoice_id })
28//! .database()
29//! .mail()
30//! .send()
31//! .await?;
32//! ```
33//!
34//! No broadcast channel yet - `larust-live::push` (`push::broadcast(
35//! channel, html)`) already fully solves "push a live update"
36//! independently, and it's already synchronous and infallible (see its
37//! own doc comment), so there's nothing this builder would add by
38//! wrapping it; call it alongside, same as before:
39//!
40//! ```ignore
41//! notification::to(&user, &InvoiceSent { invoice_id }).database().mail().send().await?;
42//! push::broadcast(&format!("notifications.{}", user.auth_id()), ...);
43//! ```
44//!
45//! [`notify`] and [`notify_and_mail`] (the original, narrower two-channel
46//! facade - [`notify`] and `mail()...send()` run *concurrently* via
47//! `tokio::try_join!`, unlike [`to`]'s own sequential-per-channel
48//! `send()`) both still exist unchanged, for existing callers.
49//!
50//! Re-exported through `larust_support::notification` (see
51//! `crates/larust-support/src/lib.rs`) so generated apps depend only on
52//! `larust-support`, never on this crate directly.
53
54use larust_auth::{authorize, Authenticatable};
55use larust_core::AppError;
56use larust_mail::Mailable;
57use larust_orm::Backend;
58use serde::Serialize;
59use sqlx::AnyPool;
60use std::future::Future;
61use std::pin::Pin;
62use std::time::{SystemTime, UNIX_EPOCH};
63
64/// A durable fact worth recording against a notifiable - Laravel's
65/// `Notification` class, narrowed to just its database-channel shape.
66/// Serializing `Self` *is* the stored `data` payload; there's no separate
67/// render step the way [`Notification::to_database`] would imply if it
68/// existed. `NOTIFICATION_TYPE` is the same explicit, stable, app-chosen
69/// tag convention `larust_queue::Job::JOB_TYPE` already establishes -
70/// deliberately not `std::any::type_name::<Self>()`, since that string
71/// isn't stable across a rename and an already-stored row would silently
72/// stop being attributable to its type.
73///
74/// No `DeserializeOwned` bound (unlike `Job`): nothing in this crate ever
75/// reconstructs a concrete `Self` from a stored row - [`notifications_for`]
76/// reads heterogeneous rows back across many different notification types
77/// at once and can only sensibly return the type tag plus raw JSON,
78/// matching Laravel's own `type`/`data` column split.
79pub trait Notification: Serialize + Send + Sync {
80 const NOTIFICATION_TYPE: &'static str;
81}
82
83/// One stored row, as read back by [`notifications_for`]. `data` stays a
84/// raw [`serde_json::Value`] rather than a concrete type - a single query
85/// reads rows for many different [`Notification`] types at once; the app
86/// is expected to match on `notification_type` to interpret `data` if it
87/// needs more than generic display.
88#[derive(Debug, Clone)]
89pub struct StoredNotification {
90 pub id: i64,
91 pub notification_type: String,
92 pub data: serde_json::Value,
93 pub read_at: Option<i64>,
94 pub created_at: i64,
95}
96
97/// Same lazy self-bootstrap idiom `larust-cache`'s `cache_items` and
98/// `larust-queue`'s `jobs`/`failed_jobs` establish - a plain
99/// `CREATE TABLE IF NOT EXISTS`, no migration file and no explicit
100/// startup call needed anywhere. Unlike either of those tables, this one
101/// is genuinely filtered and sorted by a foreign-key-shaped column
102/// (`notifiable_id`) at read time, so it also creates a matching index -
103/// the first framework-owned table in this codebase that needs one.
104///
105/// Deliberately **not** memoized behind a `OnceCell` the way a first draft
106/// of this function was: a `static` completion flag is process-wide, but
107/// `larust_testing::test_transaction` swaps in a fresh, isolated database
108/// *per test* within the same process - a real regression this shipped
109/// with and a later test suite caught (a page exercising `unread_count`
110/// for the first time started failing with "no such table: notifications"
111/// once an *earlier* test in the same binary had already flipped the flag
112/// against its own, different, since-discarded database). `IF NOT EXISTS`
113/// makes re-running this on every call cheap enough in practice - a
114/// schema lookup SQLite already has to do, no data scan - that giving up
115/// the memoization is a better trade than reintroducing that failure mode.
116async fn ensure_table(pool: &AnyPool) -> Result<(), AppError> {
117 let create_table = match larust_orm::backend() {
118 Backend::Sqlite => {
119 "CREATE TABLE IF NOT EXISTS notifications (\
120 id INTEGER PRIMARY KEY AUTOINCREMENT, \
121 notifiable_id INTEGER NOT NULL, \
122 notification_type TEXT NOT NULL, \
123 data TEXT NOT NULL, \
124 read_at INTEGER, \
125 created_at INTEGER NOT NULL\
126 )"
127 }
128 // `VARCHAR`, not MySQL's own `TEXT` - confirmed empirically (a
129 // real, live MySQL server) that `sqlx`'s `Any` driver maps every
130 // MySQL `TEXT`-family column to its own generic `Blob` kind
131 // unconditionally, and `Decode<Any> for String` only accepts
132 // `Text`-kind values - so a `TEXT` column here would fail to
133 // decode back as `String` at all (only `CHAR`/`VARCHAR` map to
134 // `Any`'s `Text` kind; see `larust-http::session`'s own
135 // `AnySessionStore::migrate` for the same finding in more detail).
136 // `data` gets a generous cap (`VARCHAR(4000)`) rather than an
137 // arbitrary-size one - a real, documented trade-off for a large
138 // notification payload.
139 Backend::MySql => {
140 "CREATE TABLE IF NOT EXISTS notifications (\
141 id INTEGER PRIMARY KEY AUTO_INCREMENT, \
142 notifiable_id INTEGER NOT NULL, \
143 notification_type VARCHAR(255) NOT NULL, \
144 data VARCHAR(4000) NOT NULL, \
145 read_at INTEGER, \
146 created_at INTEGER NOT NULL\
147 )"
148 }
149 // Postgres has native, unbounded `TEXT` - same shape as SQLite's
150 // own arm.
151 Backend::Postgres => {
152 "CREATE TABLE IF NOT EXISTS notifications (\
153 id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
154 notifiable_id INTEGER NOT NULL, \
155 notification_type TEXT NOT NULL, \
156 data TEXT NOT NULL, \
157 read_at INTEGER, \
158 created_at INTEGER NOT NULL\
159 )"
160 }
161 };
162 sqlx::query(create_table)
163 .execute(pool)
164 .await
165 .map_err(|source| AppError::Internal(Box::new(source)))?;
166
167 // MySQL's `CREATE INDEX` has no `IF NOT EXISTS` clause (unlike its
168 // `CREATE TABLE IF NOT EXISTS`, which is standard) - this function
169 // runs on every call (see its own doc comment on why it's
170 // deliberately not memoized), so on MySQL every call after the first
171 // hits and tolerates the "already exists" error instead.
172 match larust_orm::backend() {
173 Backend::Sqlite | Backend::Postgres => {
174 sqlx::query(
175 "CREATE INDEX IF NOT EXISTS idx_notifications_notifiable \
176 ON notifications (notifiable_id, created_at DESC)",
177 )
178 .execute(pool)
179 .await
180 .map_err(|source| AppError::Internal(Box::new(source)))?;
181 }
182 Backend::MySql => {
183 if let Err(error) = sqlx::query(
184 "CREATE INDEX idx_notifications_notifiable \
185 ON notifications (notifiable_id, created_at DESC)",
186 )
187 .execute(pool)
188 .await
189 {
190 let duplicate_key = matches!(&error, sqlx::Error::Database(database)
191 if database.message().contains("Duplicate key name"));
192 if !duplicate_key {
193 return Err(AppError::Internal(Box::new(error)));
194 }
195 }
196 }
197 }
198
199 Ok(())
200}
201
202fn now_unix_secs() -> i64 {
203 SystemTime::now()
204 .duration_since(UNIX_EPOCH)
205 .expect("system clock is before the Unix epoch")
206 .as_secs() as i64
207}
208
209/// Records `notification` against `notifiable` - Laravel's
210/// `$user->notify(new InvoiceSent($invoice))`, narrowed to the database
211/// channel (see this crate's own doc comment for why mail/broadcast
212/// aren't wrapped here).
213pub async fn notify<U: Authenticatable, N: Notification>(
214 notifiable: &U,
215 notification: &N,
216) -> Result<(), AppError> {
217 let pool = larust_orm::pool()?;
218 ensure_table(pool).await?;
219
220 let data = serde_json::to_string(notification)
221 .map_err(|source| AppError::Internal(Box::new(source)))?;
222
223 let backend = larust_orm::backend();
224 let insert_sql = format!(
225 "INSERT INTO notifications (notifiable_id, notification_type, data, created_at) \
226 VALUES ({}, {}, {}, {})",
227 larust_orm::placeholder(backend, 1),
228 larust_orm::placeholder(backend, 2),
229 larust_orm::placeholder(backend, 3),
230 larust_orm::placeholder(backend, 4),
231 );
232 sqlx::query(&insert_sql)
233 .bind(notifiable.auth_id())
234 .bind(N::NOTIFICATION_TYPE)
235 .bind(data)
236 .bind(now_unix_secs())
237 .execute(pool)
238 .await
239 .map_err(|source| AppError::Internal(Box::new(source)))?;
240
241 Ok(())
242}
243
244/// Runs [`notify`] and `mail().to(email).send(mailable)` concurrently -
245/// sugar for the common "record it and email it" case, not a new
246/// dispatch mechanism (see this crate's own module doc comment). Both
247/// calls still exist, still fully typed, still independently callable on
248/// their own; this only removes the sequencing cost of awaiting them one
249/// after the other, via `tokio::try_join!`. Fails with whichever error
250/// occurs first if either side fails - the other side is not rolled
251/// back, matching this crate's own `notify`'s "one plain `INSERT`, no
252/// transaction" posture (a partially-delivered notification, e.g.
253/// recorded but not emailed, is treated the same accepted-tradeoff way
254/// `larust-mail`'s own `.queue()` already treats a similar gap).
255pub async fn notify_and_mail<U, N, M>(
256 notifiable: &U,
257 notification: &N,
258 email: &str,
259 mailable: M,
260) -> Result<(), AppError>
261where
262 U: Authenticatable + Sync,
263 N: Notification + Sync,
264 M: Mailable,
265{
266 tokio::try_join!(
267 notify(notifiable, notification),
268 larust_mail::mail().to(email).send(mailable),
269 )?;
270 Ok(())
271}
272
273/// A notification that also knows how to render itself as mail -
274/// Laravel's `Notification::toMail()`, as a real trait method rather
275/// than a runtime-dispatched one (see this crate's own module doc
276/// comment for why). `Mail: Send + 'static` isn't this trait being
277/// stricter than [`Mailable`] itself needs - it's what lets
278/// [`PendingNotification::mail`] box the delivery future as `dyn Future
279/// <...> + Send` regardless of what a specific `Mailable` impl happens
280/// to capture.
281pub trait MailNotification: Send + Sync {
282 type Mail: Mailable + Send + 'static;
283 fn to_mail(&self) -> Self::Mail;
284}
285
286/// A notifiable that knows its own mail address - Laravel's
287/// `routeNotificationForMail()`, narrowed to the common case (one,
288/// always-available address) rather than Laravel's full per-notification
289/// override mechanism.
290pub trait MailNotifiable: Authenticatable {
291 fn notification_email(&self) -> String;
292}
293
294/// One channel's delivery, already built and type-erased - see
295/// [`PendingNotification`]'s own doc comment for why this is what makes
296/// `.database()`/`.mail()`/`.send()` work as three independently-typed
297/// steps instead of one call needing every channel's bounds at once.
298type BoxedDelivery<'a> = Pin<Box<dyn Future<Output = Result<(), AppError>> + Send + 'a>>;
299
300/// A multi-channel notification being assembled - build with [`to`], add
301/// channels with `.database()`/`.mail()`, run them with `.send()`. Each
302/// channel method builds and immediately boxes its own delivery future
303/// *while* its own bound (`N: Notification`, or `N: MailNotification, U:
304/// MailNotifiable`) is known, erasing it to a plain `BoxedDelivery<'a>`
305/// before storing it - which is what lets `.send()` itself need no bound
306/// on `U`/`N` at all, regardless of how many or which channels were
307/// actually selected.
308pub struct PendingNotification<'a, U, N> {
309 notifiable: &'a U,
310 notification: &'a N,
311 channels: Vec<BoxedDelivery<'a>>,
312}
313
314/// Starts building a multi-channel delivery for `notification`, aimed at
315/// `notifiable` - see [`PendingNotification`]'s own doc comment.
316pub fn to<'a, U, N>(notifiable: &'a U, notification: &'a N) -> PendingNotification<'a, U, N> {
317 PendingNotification {
318 notifiable,
319 notification,
320 channels: Vec::new(),
321 }
322}
323
324impl<'a, U, N> PendingNotification<'a, U, N> {
325 /// Adds the database channel - Laravel's `toDatabase()`, via
326 /// [`notify`].
327 #[must_use]
328 pub fn database(mut self) -> Self
329 where
330 U: Authenticatable,
331 N: Notification,
332 {
333 self.channels
334 .push(Box::pin(notify(self.notifiable, self.notification)));
335 self
336 }
337
338 /// Adds the mail channel - Laravel's `toMail()`, via
339 /// [`MailNotification::to_mail`] and [`MailNotifiable::
340 /// notification_email`]. The boxed future captures only the owned
341 /// email string and the owned `Mail` value it builds right away, not
342 /// a borrow of `self` - so its own `Send`-ness depends only on
343 /// `MailNotification::Mail: Send`, already required by that trait.
344 #[must_use]
345 pub fn mail(mut self) -> Self
346 where
347 U: MailNotifiable,
348 N: MailNotification,
349 {
350 let email = self.notifiable.notification_email();
351 let mailable = self.notification.to_mail();
352 self.channels.push(Box::pin(async move {
353 larust_mail::mail().to(email).send(mailable).await
354 }));
355 self
356 }
357
358 /// Runs every selected channel, in the order they were chosen,
359 /// sequentially - not concurrently the way [`notify_and_mail`]'s
360 /// fixed two channels are, since an arbitrary-length list of
361 /// channels has no single natural `tokio::try_join!`-style shape,
362 /// and sequential delivery keeps which channel a failure came from
363 /// unambiguous. No channel selected at all is logged and treated as
364 /// `Ok(())`, not a silent no-op left completely unremarked - the
365 /// same "nothing to do, but say so" posture elsewhere in this
366 /// framework reserves for a genuinely empty operation.
367 pub async fn send(self) -> Result<(), AppError> {
368 if self.channels.is_empty() {
369 tracing::warn!(
370 "notification::to(...).send() called with no channel selected \
371 (.database()/.mail()) - nothing was sent"
372 );
373 return Ok(());
374 }
375 for channel in self.channels {
376 channel.await?;
377 }
378 Ok(())
379 }
380}
381
382/// Reads `notifiable`'s own notifications, newest first, capped at
383/// `limit` rows. `limit` is caller-supplied rather than a framework-picked
384/// constant - the same real precedent `larust_orm::QueryBuilder::
385/// paginate(per_page)` already sets in this crate family - making an
386/// unbounded query structurally impossible rather than merely
387/// policy-discouraged. No cursor/`before_id` pagination in v1, the same
388/// documented gap `paginate` itself carries.
389pub async fn notifications_for<U: Authenticatable>(
390 notifiable: &U,
391 limit: i64,
392) -> Result<Vec<StoredNotification>, AppError> {
393 let pool = larust_orm::pool()?;
394 ensure_table(pool).await?;
395
396 let backend = larust_orm::backend();
397 let select_sql = format!(
398 "SELECT id, notification_type, data, read_at, created_at FROM notifications \
399 WHERE notifiable_id = {} ORDER BY created_at DESC, id DESC LIMIT {}",
400 larust_orm::placeholder(backend, 1),
401 larust_orm::placeholder(backend, 2),
402 );
403 let rows: Vec<(i64, String, String, Option<i64>, i64)> = sqlx::query_as(&select_sql)
404 .bind(notifiable.auth_id())
405 .bind(limit)
406 .fetch_all(pool)
407 .await
408 .map_err(|source| AppError::Internal(Box::new(source)))?;
409
410 rows.into_iter()
411 .map(|(id, notification_type, data, read_at, created_at)| {
412 Ok(StoredNotification {
413 id,
414 notification_type,
415 data: serde_json::from_str(&data)
416 .map_err(|source| AppError::Internal(Box::new(source)))?,
417 read_at,
418 created_at,
419 })
420 })
421 .collect()
422}
423
424/// The count of `notifiable`'s own notifications that have never been
425/// marked read - the number a notification-bell UI would badge with.
426pub async fn unread_count<U: Authenticatable>(notifiable: &U) -> Result<i64, AppError> {
427 let pool = larust_orm::pool()?;
428 ensure_table(pool).await?;
429
430 let select_sql = format!(
431 "SELECT COUNT(*) FROM notifications WHERE notifiable_id = {} AND read_at IS NULL",
432 larust_orm::placeholder(larust_orm::backend(), 1)
433 );
434 let (count,): (i64,) = sqlx::query_as(&select_sql)
435 .bind(notifiable.auth_id())
436 .fetch_one(pool)
437 .await
438 .map_err(|source| AppError::Internal(Box::new(source)))?;
439
440 Ok(count)
441}
442
443/// Marks one notification read, verifying it actually belongs to
444/// `notifiable` first - the same "does this row belong to the acting
445/// user?" question `larust_auth::Policy<U>::update`/`delete` already
446/// answer, so this reuses [`larust_auth::authorize`] rather than
447/// reinventing the check: a mismatched owner is a loud
448/// `AppError::Http{FORBIDDEN, ..}`, matching how e.g. updating someone
449/// else's post already responds today, not a silent no-op (silently
450/// collapsing "not yours" into `Ok(())` is the right call for an
451/// *authentication*-state ambiguity like "am I logged in at all" -
452/// `larust_auth::guard`'s own precedent - but this is an *authorization*
453/// question about a specific id someone is deliberately trying to act on,
454/// a different question with a different, louder, established answer in
455/// this codebase). A nonexistent id is `AppError::NotFound`, kept
456/// distinct from the mismatched-owner case.
457///
458/// Marking an already-read notification read again is a legal no-op, not
459/// a distinct error - there's no meaningful "double read" state worth
460/// rejecting.
461pub async fn mark_as_read<U: Authenticatable>(
462 notifiable: &U,
463 notification_id: i64,
464) -> Result<(), AppError> {
465 let pool = larust_orm::pool()?;
466 ensure_table(pool).await?;
467
468 let backend = larust_orm::backend();
469 let select_owner_sql = format!(
470 "SELECT notifiable_id FROM notifications WHERE id = {}",
471 larust_orm::placeholder(backend, 1)
472 );
473 let owner: Option<(i64,)> = sqlx::query_as(&select_owner_sql)
474 .bind(notification_id)
475 .fetch_optional(pool)
476 .await
477 .map_err(|source| AppError::Internal(Box::new(source)))?;
478
479 let Some((owner_id,)) = owner else {
480 return Err(AppError::NotFound);
481 };
482 authorize(owner_id == notifiable.auth_id())?;
483
484 let update_sql = format!(
485 "UPDATE notifications SET read_at = {} WHERE id = {}",
486 larust_orm::placeholder(backend, 1),
487 larust_orm::placeholder(backend, 2),
488 );
489 sqlx::query(&update_sql)
490 .bind(now_unix_secs())
491 .bind(notification_id)
492 .execute(pool)
493 .await
494 .map_err(|source| AppError::Internal(Box::new(source)))?;
495
496 Ok(())
497}
498
499/// Marks every one of `notifiable`'s own notifications read. No ownership
500/// check needed the way [`mark_as_read`] needs one - `WHERE notifiable_id
501/// = ?` already makes touching another notifiable's rows structurally
502/// impossible.
503pub async fn mark_all_as_read<U: Authenticatable>(notifiable: &U) -> Result<(), AppError> {
504 let pool = larust_orm::pool()?;
505 ensure_table(pool).await?;
506
507 let backend = larust_orm::backend();
508 let sql = format!(
509 "UPDATE notifications SET read_at = {} WHERE notifiable_id = {} AND read_at IS NULL",
510 larust_orm::placeholder(backend, 1),
511 larust_orm::placeholder(backend, 2),
512 );
513 sqlx::query(&sql)
514 .bind(now_unix_secs())
515 .bind(notifiable.auth_id())
516 .execute(pool)
517 .await
518 .map_err(|source| AppError::Internal(Box::new(source)))?;
519
520 Ok(())
521}
522
523/// Permanently removes one notification, after verifying it belongs to the
524/// acting notifiable. This mirrors [`mark_as_read`]'s ownership behavior:
525/// missing rows are `NotFound`, while another user's row is `FORBIDDEN`.
526pub async fn delete_notification<U: Authenticatable>(
527 notifiable: &U,
528 notification_id: i64,
529) -> Result<(), AppError> {
530 let pool = larust_orm::pool()?;
531 ensure_table(pool).await?;
532
533 let backend = larust_orm::backend();
534 let select_owner_sql = format!(
535 "SELECT notifiable_id FROM notifications WHERE id = {}",
536 larust_orm::placeholder(backend, 1)
537 );
538 let owner: Option<(i64,)> = sqlx::query_as(&select_owner_sql)
539 .bind(notification_id)
540 .fetch_optional(pool)
541 .await
542 .map_err(|source| AppError::Internal(Box::new(source)))?;
543
544 let Some((owner_id,)) = owner else {
545 return Err(AppError::NotFound);
546 };
547 authorize(owner_id == notifiable.auth_id())?;
548
549 let delete_sql = format!(
550 "DELETE FROM notifications WHERE id = {}",
551 larust_orm::placeholder(backend, 1)
552 );
553 sqlx::query(&delete_sql)
554 .bind(notification_id)
555 .execute(pool)
556 .await
557 .map_err(|source| AppError::Internal(Box::new(source)))?;
558
559 Ok(())
560}
561
562/// Permanently removes every notification owned by `notifiable`.
563pub async fn clear_notifications<U: Authenticatable>(notifiable: &U) -> Result<(), AppError> {
564 let pool = larust_orm::pool()?;
565 ensure_table(pool).await?;
566
567 let sql = format!(
568 "DELETE FROM notifications WHERE notifiable_id = {}",
569 larust_orm::placeholder(larust_orm::backend(), 1)
570 );
571 sqlx::query(&sql)
572 .bind(notifiable.auth_id())
573 .execute(pool)
574 .await
575 .map_err(|source| AppError::Internal(Box::new(source)))?;
576
577 Ok(())
578}
579
580#[cfg(test)]
581mod tests {
582 use super::*;
583 use serde::Deserialize;
584
585 struct TestUser {
586 id: i64,
587 }
588
589 impl Authenticatable for TestUser {
590 fn auth_id(&self) -> i64 {
591 self.id
592 }
593
594 async fn find_for_auth(_id: i64) -> Result<Option<Self>, AppError> {
595 unreachable!("not exercised by these tests")
596 }
597 }
598
599 #[derive(Serialize, Deserialize)]
600 struct Greeting {
601 message: String,
602 }
603
604 impl Notification for Greeting {
605 const NOTIFICATION_TYPE: &'static str = "greeting";
606 }
607
608 async fn connect_test_db() {
609 let dir = tempfile::tempdir().unwrap().keep();
610 let database_url = format!("sqlite://{}/test.sqlite", dir.display());
611 larust_orm::connect(&database_url).await.unwrap();
612 }
613
614 async fn greet<U: Authenticatable>(notifiable: &U, message: &str) {
615 notify(
616 notifiable,
617 &Greeting {
618 message: message.to_string(),
619 },
620 )
621 .await
622 .unwrap();
623 }
624
625 /// All scenarios share one test function, not several: `larust_orm::
626 /// connect()` sets a process-wide pool exactly once (a second call in
627 /// the same test binary errors with "connect() called more than
628 /// once"), the same singleton-per-process constraint this codebase's
629 /// other test suites (`larust-mail`'s `queue_job.rs`, `larust-mail`'s
630 /// `fake.rs`) already document and work around. Each scenario uses
631 /// its own, disjoint set of notifiable ids so they can't interfere
632 /// with each other despite sharing one table/connection.
633 #[tokio::test]
634 async fn notifications_crate_behaves_correctly_across_every_scenario() {
635 connect_test_db().await;
636
637 // notify + notifications_for round trip, newest first.
638 let alice = TestUser { id: 1 };
639 let bob = TestUser { id: 2 };
640 greet(&alice, "first").await;
641 greet(&alice, "second").await;
642 greet(&bob, "for bob").await;
643
644 let alice_notifications = notifications_for(&alice, 10).await.unwrap();
645 assert_eq!(alice_notifications.len(), 2);
646 assert_eq!(alice_notifications[0].data["message"], "second");
647 assert_eq!(alice_notifications[1].data["message"], "first");
648 assert_eq!(alice_notifications[0].notification_type, "greeting");
649
650 // unread_count reflects reads.
651 let carol = TestUser { id: 3 };
652 greet(&carol, "a").await;
653 greet(&carol, "b").await;
654 greet(&carol, "c").await;
655 assert_eq!(unread_count(&carol).await.unwrap(), 3);
656 let first_id = notifications_for(&carol, 10).await.unwrap()[2].id;
657 mark_as_read(&carol, first_id).await.unwrap();
658 assert_eq!(unread_count(&carol).await.unwrap(), 2);
659
660 // mark_as_read is idempotent.
661 let dave = TestUser { id: 4 };
662 greet(&dave, "hi").await;
663 let dave_id = notifications_for(&dave, 1).await.unwrap()[0].id;
664 mark_as_read(&dave, dave_id).await.unwrap();
665 mark_as_read(&dave, dave_id).await.unwrap();
666 assert_eq!(unread_count(&dave).await.unwrap(), 0);
667
668 // mark_as_read rejects a mismatched notifiable - the ownership
669 // guarantee this feature hinges on.
670 let erin = TestUser { id: 5 };
671 let frank = TestUser { id: 6 };
672 greet(&erin, "erin's").await;
673 let erin_notification_id = notifications_for(&erin, 1).await.unwrap()[0].id;
674 match mark_as_read(&frank, erin_notification_id).await {
675 Err(AppError::Http { status, .. }) => {
676 assert_eq!(status, larust_core::axum::http::StatusCode::FORBIDDEN);
677 }
678 Err(other) => panic!("expected AppError::Http{{FORBIDDEN, ..}}, got {other:?}"),
679 Ok(()) => panic!("expected AppError::Http{{FORBIDDEN, ..}}, got Ok(())"),
680 }
681 assert_eq!(
682 unread_count(&erin).await.unwrap(),
683 1,
684 "erin's notification must still be unread"
685 );
686
687 // mark_as_read returns NotFound for a nonexistent id, distinct
688 // from the mismatched-owner case above.
689 assert!(matches!(
690 mark_as_read(&erin, 999_999).await,
691 Err(AppError::NotFound)
692 ));
693
694 // mark_all_as_read only touches the caller's own rows.
695 let grace = TestUser { id: 7 };
696 let heidi = TestUser { id: 8 };
697 greet(&grace, "grace's").await;
698 greet(&heidi, "heidi's").await;
699 mark_all_as_read(&grace).await.unwrap();
700 assert_eq!(unread_count(&grace).await.unwrap(), 0);
701 assert_eq!(unread_count(&heidi).await.unwrap(), 1);
702
703 // Deletion follows the same strict ownership model and clear-all
704 // remains scoped to the current notifiable.
705 let judy = TestUser { id: 10 };
706 let karl = TestUser { id: 11 };
707 greet(&judy, "remove me").await;
708 greet(&karl, "keep me").await;
709 let judy_id = notifications_for(&judy, 1).await.unwrap()[0].id;
710 delete_notification(&judy, judy_id).await.unwrap();
711 assert!(notifications_for(&judy, 10).await.unwrap().is_empty());
712 clear_notifications(&judy).await.unwrap();
713 assert_eq!(notifications_for(&karl, 10).await.unwrap().len(), 1);
714
715 // notifications_for respects the caller-supplied limit.
716 let ivan = TestUser { id: 9 };
717 for i in 0..5 {
718 greet(&ivan, &format!("message {i}")).await;
719 }
720 assert_eq!(notifications_for(&ivan, 2).await.unwrap().len(), 2);
721
722 // notify_and_mail records both sides - `Mail::fake()` records
723 // instead of dispatching for real (no `mail_driver`/SMTP config
724 // needed in this test), same tool `larust-mail`'s own tests use.
725 larust_mail::fake();
726 let liam = TestUser { id: 12 };
727 notify_and_mail(
728 &liam,
729 &Greeting {
730 message: "concurrent".to_string(),
731 },
732 "liam@example.com",
733 WelcomeMail,
734 )
735 .await
736 .unwrap();
737
738 let liam_notifications = notifications_for(&liam, 10).await.unwrap();
739 assert_eq!(liam_notifications.len(), 1);
740 assert_eq!(liam_notifications[0].data["message"], "concurrent");
741 larust_mail::assert_sent::<WelcomeMail>(|sent| {
742 sent.to == vec!["liam@example.com".to_string()] && sent.subject == "Welcome"
743 });
744
745 // The `to(...)` builder: both channels chained actually deliver.
746 let mia = TestUser { id: 100 };
747 to(
748 &mia,
749 &Greeting {
750 message: "builder database+mail".to_string(),
751 },
752 )
753 .database()
754 .mail()
755 .send()
756 .await
757 .unwrap();
758 let mia_notifications = notifications_for(&mia, 10).await.unwrap();
759 assert_eq!(mia_notifications.len(), 1);
760 assert_eq!(
761 mia_notifications[0].data["message"],
762 "builder database+mail"
763 );
764 larust_mail::assert_sent::<GreetingMail>(|sent| {
765 sent.to == vec!["user100@example.com".to_string()]
766 && sent.subject == "You have a greeting"
767 });
768
769 // Only the channels actually chained run - a mail-only
770 // notification never writes a database row.
771 let noah = TestUser { id: 101 };
772 to(
773 &noah,
774 &Greeting {
775 message: "mail only".to_string(),
776 },
777 )
778 .mail()
779 .send()
780 .await
781 .unwrap();
782 assert!(notifications_for(&noah, 10).await.unwrap().is_empty());
783 larust_mail::assert_sent::<GreetingMail>(|sent| {
784 sent.to == vec!["user101@example.com".to_string()]
785 });
786
787 // No channel selected at all is not an error.
788 let olive = TestUser { id: 102 };
789 to(
790 &olive,
791 &Greeting {
792 message: "nobody asked".to_string(),
793 },
794 )
795 .send()
796 .await
797 .unwrap();
798 assert!(notifications_for(&olive, 10).await.unwrap().is_empty());
799 }
800
801 struct WelcomeMail;
802
803 impl Mailable for WelcomeMail {
804 fn subject(&self) -> String {
805 "Welcome".to_string()
806 }
807
808 fn html_body(&self) -> String {
809 "<p>hi</p>".to_string()
810 }
811 }
812
813 impl MailNotifiable for TestUser {
814 fn notification_email(&self) -> String {
815 format!("user{}@example.com", self.id)
816 }
817 }
818
819 impl MailNotification for Greeting {
820 type Mail = GreetingMail;
821
822 fn to_mail(&self) -> Self::Mail {
823 GreetingMail {
824 message: self.message.clone(),
825 }
826 }
827 }
828
829 struct GreetingMail {
830 message: String,
831 }
832
833 impl Mailable for GreetingMail {
834 fn subject(&self) -> String {
835 "You have a greeting".to_string()
836 }
837
838 fn html_body(&self) -> String {
839 format!("<p>{}</p>", self.message)
840 }
841 }
842}