1use std::io::{BufRead, BufReader, ErrorKind, Write};
4use std::os::unix::net::UnixStream;
5use std::sync::Mutex;
6use std::time::Duration;
7
8use serde::{Deserialize, Serialize};
9use uuid::Uuid;
10
11use crate::daemon::paths::events_socket_path;
12use crate::error::{Error, Result};
13use crate::home::UnifierHome;
14
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
20#[serde(tag = "kind", rename_all = "snake_case")]
21pub enum Notice {
22 Mailbox {
23 id: Uuid,
24 from: String,
25 to: String,
26 },
27 Event {
28 id: Uuid,
29 #[serde(default, skip_serializing_if = "Option::is_none")]
30 name: Option<String>,
31 },
32}
33
34impl Notice {
35 pub fn mailbox(id: Uuid, from: impl Into<String>, to: impl Into<String>) -> Self {
36 Self::Mailbox {
37 id,
38 from: from.into(),
39 to: to.into(),
40 }
41 }
42
43 pub fn event(id: Uuid, name: Option<String>) -> Self {
44 Self::Event { id, name }
45 }
46
47 pub fn from_json(line: &str) -> Result<Self> {
48 Ok(serde_json::from_str(line.trim())?)
49 }
50}
51
52#[derive(Default)]
54pub struct EventHub {
55 subscribers: Mutex<Vec<UnixStream>>,
56}
57
58impl EventHub {
59 pub fn add(&self, stream: UnixStream) -> Result<()> {
60 stream.set_nonblocking(false)?;
61 stream.set_write_timeout(Some(Duration::from_millis(250)))?;
62 self.subscribers
63 .lock()
64 .map_err(lock_err)?
65 .push(stream);
66 Ok(())
67 }
68
69 pub fn broadcast(&self, notice: &Notice) {
70 let Ok(json) = serde_json::to_string(notice) else {
71 return;
72 };
73 let line = format!("{json}\n");
74 let Ok(mut subs) = self.subscribers.lock() else {
75 return;
76 };
77 subs.retain_mut(|stream| stream.write_all(line.as_bytes()).is_ok() && stream.flush().is_ok());
78 }
79}
80
81pub fn subscribe(home: &UnifierHome) -> Result<UnixStream> {
83 let path = events_socket_path(home);
84 let stream = UnixStream::connect(&path).map_err(|e| {
85 Error::msg(format!(
86 "event socket not reachable at {}: {e}",
87 path.display()
88 ))
89 })?;
90 stream.set_nonblocking(false)?;
91 stream.set_read_timeout(None)?;
92 Ok(stream)
93}
94
95pub fn watch(home: &UnifierHome) -> Result<()> {
97 let stream = subscribe(home)?;
98 let mut reader = BufReader::new(stream);
99 loop {
100 let mut line = String::new();
101 match reader.read_line(&mut line) {
102 Ok(0) => break,
103 Ok(_) => print!("{line}"),
104 Err(e) if matches!(
105 e.kind(),
106 ErrorKind::Interrupted | ErrorKind::WouldBlock | ErrorKind::TimedOut
107 ) =>
108 {
109 continue
110 }
111 Err(e) => return Err(e.into()),
112 }
113 }
114 Ok(())
115}
116
117pub fn event_name(payload: &str) -> Option<String> {
118 let value: serde_json::Value = serde_json::from_str(payload).ok()?;
119 value.get("name")?.as_str().map(str::to_string)
120}
121
122fn lock_err<E: std::fmt::Display>(e: E) -> Error {
123 Error::msg(format!("event hub lock poisoned: {e}"))
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129 use std::io::BufRead;
130
131 #[test]
132 fn broadcast_reaches_paired_subscriber() {
133 let hub = EventHub::default();
134 let (tx, rx) = UnixStream::pair().unwrap();
135 hub.add(tx).unwrap();
136
137 let id = Uuid::new_v4();
138 hub.broadcast(&Notice::mailbox(id, "alice", "bob"));
139
140 let mut reader = BufReader::new(rx);
141 let mut line = String::new();
142 reader.read_line(&mut line).unwrap();
143 let notice = Notice::from_json(&line).unwrap();
144 assert_eq!(
145 notice,
146 Notice::Mailbox {
147 id,
148 from: "alice".into(),
149 to: "bob".into(),
150 }
151 );
152 }
153}