Skip to main content

tilo_notify/
service.rs

1//! The notification service an app's session serves it: an app shows, replaces, withdraws and
2//! schedules notifications over the connection its launcher opened for it, and what the person
3//! does with one comes back on the same connection.
4//!
5//! An app runs in a process with no bus of its own, so the session is where notifications go: it
6//! pushes them into the one notifications daemon every app's and the desktop's own notices reach,
7//! attributed to the app the connection was opened for ([`crate::service::FD_ENV`]). The wire is
8//! one length-prefixed JSON message per frame, the framing every socket in the tree uses: the app
9//! sends [`Request`]s, each naming an id, and the session answers the id with an [`Answer`]; what
10//! a notification's actions and dismissals mean for the app arrive as [`Request::Activated`]'s
11//! counterpart, [`Message::Activated`] and [`Message::Closed`].
12//!
13//! [`NotifySide`] is whatever answers on the session's end: the session's notifications service.
14//! [`ServiceNotifier`] is the app's end, and the [`Notifier`] a Rust app's process uses when its
15//! launcher hands it a connection.
16
17use std::collections::HashMap;
18use std::io::Write as _;
19use std::sync::atomic::{AtomicU64, Ordering};
20use std::sync::mpsc::{self, Sender};
21use std::sync::{Arc, Mutex};
22use std::time::Duration;
23
24use serde::{Deserialize, Serialize};
25use tilo_socket::Stream;
26use wire_frame::Framing;
27
28use crate::{
29    AlarmSchedule, AlarmState, CalendarAlarm, CloseReason, Feature, Notification, Notifier,
30    NotifyError, PriorityContact, Scheduled, SystemTime, Unsupported,
31};
32
33/// The descriptor the launcher hands an app it starts: the app's end of the connection served
34/// here.
35pub const FD_ENV: &str = "TILO_SVC_NOTIFY_FD";
36
37/// One message: its JSON, behind the length prefix.
38const FRAME: Framing = Framing::little_endian(1024 * 1024);
39
40/// How long a call waits for the session's answer: the session pushes into the notifications
41/// daemon, which never asks the person, so an answer that does not come is a failure rather than
42/// a hang.
43const WAIT: Duration = Duration::from_secs(30);
44
45/// An alarm as an app hands it over: its local wall-clock time, when the person turned it on, and
46/// the date it last rang, which the session reads as `YYYY-MM-DD`.
47#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
48pub struct AlarmRequest {
49    pub hour: u8,
50    pub minute: u8,
51    /// Monday is bit zero; none rings once.
52    pub weekdays: u8,
53    pub enabled_at_ms: i64,
54    pub last_rung: Option<String>,
55}
56
57impl AlarmRequest {
58    /// The request an app's [`AlarmSchedule`] makes; `None` when its delivered date is not one
59    /// the session reads.
60    #[must_use]
61    pub fn of(schedule: &AlarmSchedule) -> Option<Self> {
62        Some(Self {
63            hour: schedule.alarm.hour,
64            minute: schedule.alarm.minute,
65            weekdays: schedule.alarm.weekdays,
66            enabled_at_ms: schedule.enabled_at_ms,
67            last_rung: schedule
68                .last_rung
69                .map(|date| date.to_string())
70                .filter(|date| !date.is_empty()),
71        })
72    }
73
74    /// This request as an app's own [`AlarmSchedule`].
75    #[must_use]
76    pub fn schedule(&self) -> AlarmSchedule {
77        AlarmSchedule {
78            alarm: CalendarAlarm {
79                hour: self.hour,
80                minute: self.minute,
81                weekdays: self.weekdays,
82            },
83            enabled_at_ms: self.enabled_at_ms,
84            last_rung: self
85                .last_rung
86                .as_deref()
87                .and_then(|date| jiff::civil::Date::strptime("%Y-%m-%d", date).ok()),
88        }
89    }
90}
91
92/// One call an app makes. Each names an `id` its [`Answer`] comes back under; the id is the
93/// app's own and means nothing to the session.
94#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
95pub enum Request {
96    Show {
97        id: u64,
98        notification: Notification,
99    },
100    Withdraw {
101        id: u64,
102        tag: String,
103    },
104    Schedule {
105        id: u64,
106        notification: Notification,
107        at: SystemTime,
108    },
109    ScheduleAlarm {
110        id: u64,
111        notification: Notification,
112        at: SystemTime,
113        alarm: AlarmRequest,
114    },
115    Scheduled {
116        id: u64,
117    },
118    AlarmStates {
119        id: u64,
120    },
121    CancelScheduled {
122        id: u64,
123        tag: String,
124    },
125    /// Replace the people whose messages break through focus and Do Not Disturb with the ones
126    /// this app knows of.
127    PriorityContacts {
128        id: u64,
129        contacts: Vec<PriorityContact>,
130    },
131}
132
133impl Request {
134    /// The call's id, which its answer names.
135    #[must_use]
136    pub const fn id(&self) -> u64 {
137        match self {
138            Self::Show { id, .. }
139            | Self::Withdraw { id, .. }
140            | Self::Schedule { id, .. }
141            | Self::ScheduleAlarm { id, .. }
142            | Self::Scheduled { id }
143            | Self::AlarmStates { id }
144            | Self::CancelScheduled { id, .. }
145            | Self::PriorityContacts { id, .. } => *id,
146        }
147    }
148}
149
150/// One alarm as the session reports it: its state and what it rang.
151#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
152pub struct AlarmStateWire {
153    pub tag: String,
154    pub alarm: AlarmRequest,
155    pub next_at: Option<SystemTime>,
156    pub last_at: Option<SystemTime>,
157}
158
159impl AlarmStateWire {
160    /// The state an [`AlarmState`] reports.
161    #[must_use]
162    pub fn of(state: &AlarmState) -> Self {
163        Self {
164            tag: state.tag.clone(),
165            alarm: AlarmRequest {
166                hour: state.alarm.hour,
167                minute: state.alarm.minute,
168                weekdays: state.alarm.weekdays,
169                enabled_at_ms: state.enabled_at_ms,
170                last_rung: state.last_rung.map(|date| date.to_string()),
171            },
172            next_at: state.next_at,
173            last_at: state.last_at,
174        }
175    }
176
177    /// This wire state as an [`AlarmState`].
178    #[must_use]
179    pub fn state(&self) -> AlarmState {
180        AlarmState {
181            tag: self.tag.clone(),
182            alarm: self.alarm.schedule().alarm,
183            enabled_at_ms: self.alarm.enabled_at_ms,
184            next_at: self.next_at,
185            last_at: self.last_at,
186            last_rung: self
187                .alarm
188                .last_rung
189                .as_deref()
190                .and_then(|date| jiff::civil::Date::strptime("%Y-%m-%d", date).ok()),
191        }
192    }
193}
194
195/// What the session answered a call with.
196#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
197pub enum Answer {
198    Done,
199    Scheduled(Vec<Scheduled>),
200    Alarms(Vec<AlarmStateWire>),
201    /// The session would not do it, and why.
202    Refused(Refusal),
203}
204
205/// Why the session refused a call.
206#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
207pub enum Refusal {
208    /// This host cannot do it: scheduling, the one feature the session may lack.
209    Unsupported,
210    Invalid(String),
211    Failed(String),
212    /// This connection reaches no notification service.
213    Unavailable,
214}
215
216impl Refusal {
217    /// The refusal as the error an app's [`Notifier`] reports.
218    #[must_use]
219    pub fn error(&self) -> NotifyError {
220        match self {
221            Self::Unsupported => NotifyError::Unsupported(Unsupported::of(Feature::Schedule)),
222            Self::Invalid(reason) | Self::Failed(reason) => NotifyError::Failed(reason.clone()),
223            Self::Unavailable => NotifyError::Unavailable,
224        }
225    }
226}
227
228/// One message on its way to the app: the answer to a call, and what the person did with a
229/// notification the app showed.
230#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
231pub enum Message {
232    Answer {
233        id: u64,
234        answer: Answer,
235    },
236    /// The person chose the notification, or one of its buttons: the URI it was shown with.
237    Activated {
238        uri: String,
239    },
240    /// The notification is gone, and why: the person dismissed it, it expired, or it was closed.
241    Closed {
242        tag: String,
243        reason: CloseReason,
244    },
245}
246
247/// What answers on the session's end of an app's notification connection: the session's
248/// notifications daemon, attributed to the app the connection is for.
249pub trait NotifySide: Send + Sync {
250    /// The side of this connection that tells the app what happened to its notifications, before
251    /// the first request. The connection closes with the app, and so does the side.
252    fn attached(&self, channel: Arc<Channel>) {
253        drop(channel);
254    }
255
256    /// Show `notification`, or replace the app's notification with its tag.
257    fn show(&self, notification: &Notification) -> Result<(), Refusal>;
258
259    /// Withdraw the app's notification with `tag`.
260    fn withdraw(&self, tag: &str) -> Result<(), Refusal>;
261
262    /// Hand `notification` over for `at`, with `alarm` for one that rings at a wall-clock time.
263    fn schedule(
264        &self,
265        notification: &Notification,
266        at: SystemTime,
267        alarm: Option<&AlarmRequest>,
268    ) -> Result<(), Refusal>;
269
270    /// The app's deadlines still to fall due.
271    fn scheduled(&self) -> Result<Vec<Scheduled>, Refusal>;
272
273    /// The app's alarms, and what the session delivered of them.
274    fn alarm_states(&self) -> Result<Vec<AlarmState>, Refusal>;
275
276    /// Cancel the app's deadline with `tag`.
277    fn cancel_scheduled(&self, tag: &str) -> Result<(), Refusal>;
278
279    /// Replace the people whose messages may break through focus and Do Not Disturb with
280    /// `contacts`, as this app knows them.
281    /// A side that keeps no priority contacts.
282    fn priority_contacts(&self, _contacts: &[PriorityContact]) -> Result<(), Refusal> {
283        Err(Refusal::Unsupported)
284    }
285}
286
287/// The session's end of one app's connection, for what the person did with its notifications.
288pub struct Channel {
289    writer: Mutex<Stream>,
290}
291
292impl Channel {
293    /// The person chose a notification: `uri` is what the app showed it with.
294    pub fn activated(&self, uri: &str) {
295        self.send(&Message::Activated {
296            uri: uri.to_owned(),
297        });
298    }
299
300    /// The app's notification with `tag` is gone, for `reason`.
301    pub fn closed(&self, tag: &str, reason: CloseReason) {
302        self.send(&Message::Closed {
303            tag: tag.to_owned(),
304            reason,
305        });
306    }
307
308    fn answer(&self, id: u64, answer: Answer) {
309        self.send(&Message::Answer { id, answer });
310    }
311
312    fn send(&self, message: &Message) {
313        let Ok(bytes) = serde_json::to_vec(message) else {
314            return;
315        };
316        let Ok(mut writer) = self.writer.lock() else {
317            return;
318        };
319        if FRAME.write(&mut *writer, &bytes).is_ok() {
320            let _ = writer.flush();
321        }
322    }
323}
324
325/// Serve an app's notification calls on `stream` until it closes the connection.
326pub fn serve(stream: Stream, side: &dyn NotifySide) {
327    let Ok(writer) = stream.try_clone() else {
328        return;
329    };
330    let channel = Arc::new(Channel {
331        writer: Mutex::new(writer),
332    });
333    side.attached(Arc::clone(&channel));
334    let mut reader = stream;
335    while let Ok(Some(frame)) = FRAME.read(&mut reader) {
336        let Ok(request) = serde_json::from_slice::<Request>(&frame) else {
337            return;
338        };
339        let id = request.id();
340        channel.answer(id, answer(side, request));
341    }
342}
343
344/// What `side` answers `request` with.
345fn answer(side: &dyn NotifySide, request: Request) -> Answer {
346    let done = match request {
347        Request::Show { notification, .. } => crate::validate(&notification)
348            .map_err(refused)
349            .and_then(|()| side.show(&notification)),
350        Request::Withdraw { tag, .. } => crate::validate_tag(&tag)
351            .map_err(refused)
352            .and_then(|()| side.withdraw(&tag)),
353        Request::Schedule {
354            notification, at, ..
355        } => crate::validate(&notification)
356            .map_err(refused)
357            .and_then(|()| side.schedule(&notification, at, None)),
358        Request::ScheduleAlarm {
359            notification,
360            at,
361            alarm,
362            ..
363        } => crate::validate(&notification)
364            .map_err(refused)
365            .and_then(|()| side.schedule(&notification, at, Some(&alarm))),
366        Request::Scheduled { .. } => {
367            return match side.scheduled() {
368                Ok(rows) => Answer::Scheduled(rows),
369                Err(refusal) => Answer::Refused(refusal),
370            };
371        }
372        Request::AlarmStates { .. } => {
373            return match side.alarm_states() {
374                Ok(states) => Answer::Alarms(states.iter().map(AlarmStateWire::of).collect()),
375                Err(refusal) => Answer::Refused(refusal),
376            };
377        }
378        Request::CancelScheduled { tag, .. } => crate::validate_tag(&tag)
379            .map_err(refused)
380            .and_then(|()| side.cancel_scheduled(&tag)),
381        Request::PriorityContacts { contacts, .. } => side.priority_contacts(&contacts),
382    };
383    match done {
384        Ok(()) => Answer::Done,
385        Err(refusal) => Answer::Refused(refusal),
386    }
387}
388
389/// A malformed request, as the refusal an app is told.
390fn refused(error: NotifyError) -> Refusal {
391    match error {
392        NotifyError::Invalid(reason) => Refusal::Invalid(reason.to_owned()),
393        NotifyError::Unsupported(_) => Refusal::Unsupported,
394        NotifyError::Failed(reason) => Refusal::Failed(reason),
395        NotifyError::Unavailable => Refusal::Unavailable,
396    }
397}
398
399/// This process's connection to its session's notification service, taken once: what the system
400/// notifier and an app's priority contacts both use. `None` when the launcher handed none, or it
401/// is already closed.
402fn inherited() -> Option<&'static Arc<Connection>> {
403    static INHERITED: std::sync::OnceLock<Option<Arc<Connection>>> = std::sync::OnceLock::new();
404    INHERITED
405        .get_or_init(|| {
406            let fd = std::env::var(FD_ENV).ok()?.parse::<i32>().ok()?;
407            if fd < 0 {
408                return None;
409            }
410            // SAFETY: the launcher passes this descriptor to this process, and it is this
411            // process's from here: nothing else in the app holds the number.
412            let stream = Stream::from(unsafe {
413                <std::os::fd::OwnedFd as std::os::fd::FromRawFd>::from_raw_fd(fd)
414            });
415            Connection::start(stream)
416        })
417        .as_ref()
418}
419
420/// Whether the launcher handed this process a notification service.
421#[must_use]
422pub fn inherited_service() -> bool {
423    inherited().is_some()
424}
425
426/// Replace the people whose messages may break through focus and Do Not Disturb with `contacts`,
427/// as this app knows them, over the connection its session opened for it.
428///
429/// # Errors
430/// This process was handed no notification service, or the session refused the list.
431pub fn publish_priority_contacts(contacts: &[PriorityContact]) -> Result<(), NotifyError> {
432    let Some(connection) = inherited() else {
433        return Err(NotifyError::Unavailable);
434    };
435    let notifier = ServiceNotifier {
436        connection: Arc::clone(connection),
437    };
438    let contacts = contacts.to_vec();
439    ServiceNotifier::did(notifier.ask(move |id| Request::PriorityContacts { id, contacts })?)
440}
441
442/// An app's end of its notification connection: a Rust app's [`Notifier`], the same service a
443/// tilolang instance reaches.
444pub struct ServiceNotifier {
445    connection: Arc<Connection>,
446}
447
448struct Connection {
449    writer: Mutex<Stream>,
450    /// The calls waiting for their answers, by the id they named.
451    waiting: Mutex<HashMap<u64, Sender<Answer>>>,
452    next: AtomicU64,
453}
454
455impl ServiceNotifier {
456    /// The notifier over the connection the launcher opened for this app, named by [`FD_ENV`];
457    /// `None` when this process was handed none.
458    #[must_use]
459    pub fn from_env() -> Option<Self> {
460        Some(Self {
461            connection: Arc::clone(inherited()?),
462        })
463    }
464
465    /// The notifier over `stream`, the connection the session opened for the app; `None` when it
466    /// cannot be read and written beside this end.
467    #[must_use]
468    pub fn connect(stream: Stream) -> Option<Self> {
469        Some(Self {
470            connection: Connection::start(stream)?,
471        })
472    }
473
474    /// Ask the session `request`, built with the id it answers under.
475    fn ask(&self, request: impl FnOnce(u64) -> Request) -> Result<Answer, NotifyError> {
476        let id = self.connection.next.fetch_add(1, Ordering::Relaxed);
477        let (reply, answer) = mpsc::channel();
478        self.connection
479            .waiting
480            .lock()
481            .map_err(|_| NotifyError::Unavailable)?
482            .insert(id, reply);
483        let sent = serde_json::to_vec(&request(id)).ok().and_then(|bytes| {
484            let mut writer = self.connection.writer.lock().ok()?;
485            FRAME.write(&mut *writer, &bytes).ok()?;
486            writer.flush().ok()
487        });
488        if sent.is_none() {
489            if let Ok(mut waiting) = self.connection.waiting.lock() {
490                waiting.remove(&id);
491            }
492            return Err(NotifyError::Unavailable);
493        }
494        answer.recv_timeout(WAIT).map_err(|_| {
495            if let Ok(mut waiting) = self.connection.waiting.lock() {
496                waiting.remove(&id);
497            }
498            NotifyError::Failed("the notification service did not answer".into())
499        })
500    }
501
502    /// `answer` as a result of doing it, or the refusal.
503    fn did(answer: Answer) -> Result<(), NotifyError> {
504        match answer {
505            Answer::Done => Ok(()),
506            Answer::Refused(refusal) => Err(refusal.error()),
507            Answer::Scheduled(_) | Answer::Alarms(_) => Err(NotifyError::Failed(
508                "the notification service answered the wrong call".into(),
509            )),
510        }
511    }
512}
513
514impl Connection {
515    /// The connection over `stream`, with the thread that takes what the session says on it.
516    fn start(stream: Stream) -> Option<Arc<Self>> {
517        let reader = stream.try_clone().ok()?;
518        let connection = Arc::new(Self {
519            writer: Mutex::new(stream),
520            waiting: Mutex::default(),
521            next: AtomicU64::new(1),
522        });
523        let following = Arc::clone(&connection);
524        std::thread::Builder::new()
525            .name("tilo-notify-service".into())
526            .spawn(move || following.listen(reader))
527            .ok()?;
528        Some(connection)
529    }
530
531    /// Take the session's answers and what happened to the app's notifications, until the
532    /// connection closes.
533    fn listen(&self, mut reader: Stream) {
534        while let Ok(Some(frame)) = FRAME.read(&mut reader) {
535            let Ok(message) = serde_json::from_slice::<Message>(&frame) else {
536                return;
537            };
538            match message {
539                Message::Answer { id, answer } => {
540                    let waiting = self
541                        .waiting
542                        .lock()
543                        .ok()
544                        .and_then(|mut waiting| waiting.remove(&id));
545                    if let Some(reply) = waiting {
546                        let _ = reply.send(answer);
547                    }
548                }
549                Message::Activated { uri } => crate::activated(&uri),
550                Message::Closed { tag, reason } => crate::closed(&tag, reason),
551            }
552        }
553    }
554}
555
556impl Notifier for ServiceNotifier {
557    fn show(&self, notification: &Notification) -> Result<(), NotifyError> {
558        crate::validate(notification)?;
559        let notification = notification.clone();
560        Self::did(self.ask(move |id| Request::Show { id, notification })?)
561    }
562
563    fn withdraw(&self, tag: &str) -> Result<(), NotifyError> {
564        crate::validate_tag(tag)?;
565        let tag = tag.to_owned();
566        Self::did(self.ask(move |id| Request::Withdraw { id, tag })?)
567    }
568
569    fn schedule(&self, notification: &Notification, at: SystemTime) -> Result<(), NotifyError> {
570        crate::validate(notification)?;
571        let notification = notification.clone();
572        Self::did(self.ask(move |id| Request::Schedule {
573            id,
574            notification,
575            at,
576        })?)
577    }
578
579    fn schedule_alarm(
580        &self,
581        notification: &Notification,
582        at: SystemTime,
583        schedule: AlarmSchedule,
584    ) -> Result<(), NotifyError> {
585        crate::validate(notification)?;
586        if !schedule.alarm.valid() {
587            return Err(NotifyError::Invalid("invalid alarm time or weekdays"));
588        }
589        let alarm = AlarmRequest::of(&schedule)
590            .ok_or(NotifyError::Invalid("invalid delivered alarm date"))?;
591        let notification = notification.clone();
592        Self::did(self.ask(move |id| Request::ScheduleAlarm {
593            id,
594            notification,
595            at,
596            alarm,
597        })?)
598    }
599
600    fn scheduled(&self) -> Result<Vec<Scheduled>, NotifyError> {
601        match self.ask(|id| Request::Scheduled { id })? {
602            Answer::Scheduled(rows) => Ok(rows),
603            Answer::Refused(refusal) => Err(refusal.error()),
604            Answer::Done | Answer::Alarms(_) => Err(NotifyError::Failed(
605                "the notification service answered the wrong call".into(),
606            )),
607        }
608    }
609
610    fn alarm_states(&self) -> Result<Vec<AlarmState>, NotifyError> {
611        match self.ask(|id| Request::AlarmStates { id })? {
612            Answer::Alarms(states) => Ok(states.iter().map(AlarmStateWire::state).collect()),
613            Answer::Refused(refusal) => Err(refusal.error()),
614            Answer::Done | Answer::Scheduled(_) => Err(NotifyError::Failed(
615                "the notification service answered the wrong call".into(),
616            )),
617        }
618    }
619
620    fn cancel_scheduled(&self, tag: &str) -> Result<(), NotifyError> {
621        crate::validate_tag(tag)?;
622        let tag = tag.to_owned();
623        Self::did(self.ask(move |id| Request::CancelScheduled { id, tag })?)
624    }
625}
626
627#[cfg(test)]
628mod tests {
629    use super::*;
630    use crate::{NotificationButton, NotificationSender, Severity};
631    use std::sync::Mutex;
632
633    #[derive(Default)]
634    struct Recorded {
635        shown: Vec<Notification>,
636        withdrawn: Vec<String>,
637        scheduled: Vec<(Notification, SystemTime, Option<AlarmRequest>)>,
638        cancelled: Vec<String>,
639        contacts: Vec<PriorityContact>,
640        channel: Mutex<Option<Arc<Channel>>>,
641    }
642
643    struct Recording(Arc<Mutex<Recorded>>);
644
645    impl NotifySide for Recording {
646        fn attached(&self, channel: Arc<Channel>) {
647            *self.0.lock().unwrap().channel.lock().unwrap() = Some(channel);
648        }
649
650        fn show(&self, notification: &Notification) -> Result<(), Refusal> {
651            self.0.lock().unwrap().shown.push(notification.clone());
652            Ok(())
653        }
654
655        fn withdraw(&self, tag: &str) -> Result<(), Refusal> {
656            self.0.lock().unwrap().withdrawn.push(tag.to_owned());
657            Ok(())
658        }
659
660        fn schedule(
661            &self,
662            notification: &Notification,
663            at: SystemTime,
664            alarm: Option<&AlarmRequest>,
665        ) -> Result<(), Refusal> {
666            self.0
667                .lock()
668                .unwrap()
669                .scheduled
670                .push((notification.clone(), at, alarm.cloned()));
671            Ok(())
672        }
673
674        fn scheduled(&self) -> Result<Vec<Scheduled>, Refusal> {
675            Ok(self
676                .0
677                .lock()
678                .unwrap()
679                .scheduled
680                .iter()
681                .map(|(notification, at, _)| Scheduled {
682                    tag: notification.tag.clone(),
683                    at: *at,
684                })
685                .collect())
686        }
687
688        fn alarm_states(&self) -> Result<Vec<AlarmState>, Refusal> {
689            Ok(self
690                .0
691                .lock()
692                .unwrap()
693                .scheduled
694                .iter()
695                .filter_map(|(notification, at, alarm)| {
696                    let alarm = alarm.as_ref()?.schedule();
697                    Some(AlarmState {
698                        tag: notification.tag.clone(),
699                        alarm: alarm.alarm,
700                        enabled_at_ms: alarm.enabled_at_ms,
701                        next_at: Some(*at),
702                        last_at: None,
703                        last_rung: alarm.last_rung,
704                    })
705                })
706                .collect())
707        }
708
709        fn cancel_scheduled(&self, tag: &str) -> Result<(), Refusal> {
710            self.0.lock().unwrap().cancelled.push(tag.to_owned());
711            Ok(())
712        }
713
714        fn priority_contacts(&self, contacts: &[PriorityContact]) -> Result<(), Refusal> {
715            self.0.lock().unwrap().contacts = contacts.to_vec();
716            Ok(())
717        }
718    }
719
720    /// A client over one end of a socket pair, with a recording side and a channel on the other.
721    fn session() -> (ServiceNotifier, Arc<Mutex<Recorded>>) {
722        let (app, service) = tilo_socket::pair().expect("a socket pair");
723        let recorded = Arc::new(Mutex::new(Recorded::default()));
724        let side = Arc::new(Recording(Arc::clone(&recorded)));
725        std::thread::spawn(move || serve(service, &*side));
726        let client = ServiceNotifier::connect(app).expect("the connection is usable");
727        (client, recorded)
728    }
729
730    fn waiting(recorded: &Arc<Mutex<Recorded>>) -> Arc<Channel> {
731        for _ in 0..1000 {
732            let channel = { recorded.lock().unwrap().channel.lock().unwrap().clone() };
733            if let Some(channel) = channel {
734                return channel;
735            }
736            std::thread::yield_now();
737        }
738        panic!("the service never attached its channel");
739    }
740
741    #[test]
742    fn an_app_shows_replaces_and_withdraws_its_notifications_over_its_connection() {
743        let (client, recorded) = session();
744        let shown = Notification::new("task", "Saved", "Your change is on every device")
745            .with_activation("tilo-test:open")
746            .with_button("Undo", "tilo-test:undo")
747            .with_severity(Severity::Warning)
748            .quietly();
749        client.show(&shown).expect("the service took it");
750        assert_eq!(recorded.lock().unwrap().shown, [shown]);
751        client.withdraw("task").expect("the service withdrew it");
752        assert_eq!(recorded.lock().unwrap().withdrawn, ["task"]);
753    }
754
755    #[test]
756    fn a_malformed_notification_is_refused_before_it_reaches_the_session() {
757        let (client, recorded) = session();
758        assert!(matches!(
759            client.show(&Notification::new("", "Title", "")),
760            Err(NotifyError::Invalid(_))
761        ));
762        assert!(matches!(
763            client.withdraw("t\nag"),
764            Err(NotifyError::Invalid(_))
765        ));
766        assert!(
767            recorded.lock().unwrap().shown.is_empty(),
768            "nothing malformed reaches the service"
769        );
770    }
771
772    #[test]
773    fn what_the_person_chose_reaches_the_app_that_showed_it() {
774        let (client, recorded) = session();
775        let (seen, chosen) = std::sync::mpsc::channel();
776        crate::set_activation_handler("tilo-service-test", move |uri| {
777            let _ = seen.send(uri.to_owned());
778        });
779        client
780            .show(&Notification::new("task", "Saved", "").with_activation("tilo-service-test:open"))
781            .expect("the service took it");
782        let channel = waiting(&recorded);
783        channel.activated("tilo-service-test:open");
784        assert_eq!(
785            chosen.recv_timeout(Duration::from_secs(30)),
786            Ok("tilo-service-test:open".to_owned())
787        );
788    }
789
790    #[test]
791    fn a_notification_that_goes_away_is_reported_under_its_tag_and_reason() {
792        let (client, recorded) = session();
793        let (gone, closings) = std::sync::mpsc::channel();
794        crate::set_close_handler("tilo-service-close-test:", move |tag, reason| {
795            let _ = gone.send((tag.to_owned(), reason));
796        });
797        client
798            .show(&Notification::new("tilo-service-close-test:1", "Saved", ""))
799            .expect("the service took it");
800        let channel = waiting(&recorded);
801        channel.closed("tilo-service-close-test:1", CloseReason::Dismissed);
802        assert_eq!(
803            closings.recv_timeout(Duration::from_secs(30)),
804            Ok((
805                "tilo-service-close-test:1".to_owned(),
806                CloseReason::Dismissed
807            ))
808        );
809    }
810
811    #[test]
812    fn an_alarm_is_scheduled_read_back_and_cancelled_over_the_connection() {
813        let (client, recorded) = session();
814        let notification = Notification::new("wake", "Wake up", "It is 7:00");
815        let at = SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000);
816        let alarm = AlarmSchedule {
817            alarm: CalendarAlarm {
818                hour: 7,
819                minute: 0,
820                weekdays: 0,
821            },
822            enabled_at_ms: 1_700_000_000_000,
823            last_rung: Some(jiff::civil::date(2026, 11, 25)),
824        };
825        client
826            .schedule_alarm(&notification, at, alarm)
827            .expect("the service scheduled it");
828        let scheduled = client.scheduled().expect("the deadlines");
829        assert_eq!(
830            scheduled,
831            [Scheduled {
832                tag: "wake".to_owned(),
833                at
834            }]
835        );
836        let states = client.alarm_states().expect("the alarms");
837        assert_eq!(states.len(), 1, "{states:?}");
838        assert_eq!(states[0].alarm, alarm.alarm);
839        assert_eq!(states[0].enabled_at_ms, alarm.enabled_at_ms);
840        assert_eq!(states[0].last_rung, alarm.last_rung);
841        client
842            .cancel_scheduled("wake")
843            .expect("the service cancelled it");
844        assert_eq!(recorded.lock().unwrap().cancelled, ["wake"]);
845    }
846
847    #[test]
848    fn priority_contacts_go_over_the_connection_that_names_the_app() {
849        let (client, recorded) = session();
850        let contacts = vec![PriorityContact {
851            id: "person-1".to_owned(),
852            name: "Ada".to_owned(),
853            endpoints: vec!["ada@example.com".to_owned()],
854        }];
855        client
856            .ask(move |id| Request::PriorityContacts { id, contacts })
857            .map(ServiceNotifier::did)
858            .expect("the service answered")
859            .expect("the service took them");
860        assert_eq!(recorded.lock().unwrap().contacts.len(), 1);
861        assert_eq!(recorded.lock().unwrap().contacts[0].id, "person-1");
862    }
863
864    #[test]
865    fn a_refusal_is_the_error_the_app_reads() {
866        struct Refusing;
867
868        impl NotifySide for Refusing {
869            fn show(&self, _notification: &Notification) -> Result<(), Refusal> {
870                Err(Refusal::Failed("the notification centre is off".into()))
871            }
872
873            fn withdraw(&self, _tag: &str) -> Result<(), Refusal> {
874                Err(Refusal::Unsupported)
875            }
876
877            fn schedule(
878                &self,
879                _notification: &Notification,
880                _at: SystemTime,
881                _alarm: Option<&AlarmRequest>,
882            ) -> Result<(), Refusal> {
883                Err(Refusal::Unsupported)
884            }
885
886            fn scheduled(&self) -> Result<Vec<Scheduled>, Refusal> {
887                Err(Refusal::Unsupported)
888            }
889
890            fn alarm_states(&self) -> Result<Vec<AlarmState>, Refusal> {
891                Err(Refusal::Unsupported)
892            }
893
894            fn cancel_scheduled(&self, _tag: &str) -> Result<(), Refusal> {
895                Err(Refusal::Unsupported)
896            }
897        }
898
899        let (app, service) = tilo_socket::pair().expect("a socket pair");
900        std::thread::spawn(move || {
901            let side = Refusing;
902            serve(service, &side);
903        });
904        let client = ServiceNotifier::connect(app).expect("the connection is usable");
905        assert_eq!(
906            client.show(&Notification::new("t", "Title", "")),
907            Err(NotifyError::Failed("the notification centre is off".into()))
908        );
909        assert!(matches!(
910            client.withdraw("t"),
911            Err(NotifyError::Unsupported(_))
912        ));
913    }
914
915    #[test]
916    fn a_process_the_launcher_handed_no_service_is_refused() {
917        let mut env = tilo_test_env::ScopedEnv::new();
918        env.remove(FD_ENV);
919        let notifier = crate::system(Some("so.tilo.notify-test"));
920        assert_eq!(
921            notifier.show(&Notification::new("t", "Title", "")),
922            Err(NotifyError::Unavailable)
923        );
924        assert_eq!(notifier.withdraw("t"), Err(NotifyError::Unavailable));
925    }
926
927    #[test]
928    fn every_notification_shape_survives_the_wire() {
929        let notification = Notification {
930            tag: "tag".into(),
931            title: "Title".into(),
932            body: "Body".into(),
933            activation: Some("tilo-test:open".into()),
934            action: Some("Open".into()),
935            severity: Severity::Error,
936            buttons: vec![NotificationButton {
937                label: "Retry".into(),
938                activation: "tilo-test:retry".into(),
939            }],
940            silent: true,
941            app: Some("Files".into()),
942            from: Some(NotificationSender {
943                name: "Ada".into(),
944                id: "person-1".into(),
945                agent: false,
946            }),
947        };
948        let request = Request::Show {
949            id: 7,
950            notification,
951        };
952        let bytes = serde_json::to_vec(&request).expect("the request");
953        assert_eq!(
954            serde_json::from_slice::<Request>(&bytes).expect("the request"),
955            request
956        );
957    }
958}