interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-coord / src / board / notify.rs

259 lines · 9541 bytes Raw Blame History
1//! Wake notification: a best-effort datagram per post, so a waiting agent needs no polling.
2//!
3//! A watcher binds `wake/<16 hex>.sock` (the hash of its tag: a board root plus a 64-byte
4//! tag would not fit the 108-byte `sockaddr_un`). After a post is durable and its lock is
5//! released, the writer sends the 8-byte little-endian event id to every wake socket on the
6//! board (at most [`MAX_WAKE_FANOUT`], non-blocking). A datagram is only a hint: a lost,
7//! dropped or never-sent wake costs latency (the waiter times out and reads), never an
8//! event, because the journal and the cursor are the only truth. A wake spends no model
9//! token; the reading agent still has to run to act on what it reads.
10
11use super::frame::key_hash;
12use super::journal::make_dir;
13use super::{io_err, Board, BoardError, Resume};
14use crate::record::{refusal_for, RecordRefusal};
15use std::fs;
16use std::io::ErrorKind;
17use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
18use std::os::unix::net::UnixDatagram;
19use std::path::{Path, PathBuf};
20use std::time::Duration;
21
22/// Most wake sockets a single post signals.
23pub const MAX_WAKE_FANOUT: usize = 256;
24const H_WAKE: u8 = b'w';
25/// `sockaddr_un.sun_path` is 108 bytes including the terminating NUL.
26const MAX_SUN_PATH: usize = 107;
27
28/// Result of a wait.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum Wake {
31 /// A post happened (the highest id named by the datagrams drained, or by the read
32 /// that found undelivered events). Read the board to see what is yours.
33 Woke(u64),
34 /// Nothing arrived in time. Reading is still correct (a datagram may have been lost).
35 TimedOut,
36}
37
38/// A bound wake socket for one tag. Dropping it removes its socket file.
39pub struct Watcher {
40 tag: String,
41 path: PathBuf,
42 sock: UnixDatagram,
43 ino: (u64, u64),
44}
45
46pub(crate) fn wake_path(root: &Path, tag: &str) -> PathBuf {
47 root.join("wake")
48 .join(format!("{:016x}.sock", key_hash(H_WAKE, tag.as_bytes())))
49}
50
51fn is_wake_name(n: &str) -> bool {
52 n.len() == 21
53 && n.ends_with(".sock")
54 && n[..16]
55 .bytes()
56 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
57}
58
59impl Watcher {
60 fn bind(board: &Board, tag: &str) -> Result<Watcher, BoardError> {
61 // Wake sockets are not durable state: no root reconciliation for a watcher.
62 make_dir(board.root(), "wake")?;
63 let path = wake_path(board.root(), tag);
64 if path.as_os_str().len() > MAX_SUN_PATH {
65 return Err(BoardError::SocketPathTooLong { path });
66 }
67 match fs::symlink_metadata(&path) {
68 Ok(m) if m.file_type().is_socket() => {
69 // A live watcher answers a connect; a stale file refuses it.
70 let probe = UnixDatagram::unbound().map_err(io_err(&path))?;
71 match probe.connect(&path) {
72 Ok(()) => {
73 return Err(BoardError::WatcherBusy {
74 tag: tag.into(),
75 path,
76 })
77 }
78 Err(e) if e.kind() == ErrorKind::ConnectionRefused => {
79 fs::remove_file(&path).map_err(io_err(&path))?;
80 }
81 Err(e) => return Err(io_err(&path)(e)),
82 }
83 }
84 Ok(m) => {
85 return Err(BoardError::Refused {
86 path,
87 reason: refusal_for(&m.file_type())
88 .unwrap_or(RecordRefusal::NotRegular("regular file")),
89 })
90 }
91 Err(e) if e.kind() == ErrorKind::NotFound => {}
92 Err(e) => return Err(io_err(&path)(e)),
93 }
94 let sock = match UnixDatagram::bind(&path) {
95 Ok(s) => s,
96 Err(e) if e.kind() == ErrorKind::AddrInUse => {
97 return Err(BoardError::WatcherBusy {
98 tag: tag.into(),
99 path,
100 })
101 }
102 Err(e) => return Err(io_err(&path)(e)),
103 };
104 fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).map_err(io_err(&path))?;
105 let m = fs::symlink_metadata(&path).map_err(io_err(&path))?;
106 Ok(Watcher {
107 tag: tag.into(),
108 path,
109 sock,
110 ino: (m.dev(), m.ino()),
111 })
112 }
113
114 pub fn tag(&self) -> &str {
115 &self.tag
116 }
117
118 pub fn path(&self) -> &Path {
119 &self.path
120 }
121
122 /// Block up to `timeout` for a wake datagram, then drain any queued ones.
123 pub fn wait(&self, timeout: Duration) -> Result<Wake, BoardError> {
124 let mut buf = [0u8; 16];
125 let first = if timeout.is_zero() {
126 self.sock
127 .set_nonblocking(true)
128 .map_err(io_err(&self.path))?;
129 self.sock.recv(&mut buf)
130 } else {
131 self.sock
132 .set_nonblocking(false)
133 .map_err(io_err(&self.path))?;
134 self.sock
135 .set_read_timeout(Some(timeout))
136 .map_err(io_err(&self.path))?;
137 self.sock.recv(&mut buf)
138 };
139 let mut best = match first {
140 Ok(n) => datagram_id(&buf[..n]),
141 Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
142 return Ok(Wake::TimedOut)
143 }
144 Err(e) if e.kind() == ErrorKind::Interrupted => return Ok(Wake::TimedOut),
145 Err(e) => return Err(io_err(&self.path)(e)),
146 };
147 self.sock
148 .set_nonblocking(true)
149 .map_err(io_err(&self.path))?;
150 // Bounded drain: at most one fanout's worth per wait.
151 for _ in 0..MAX_WAKE_FANOUT * 4 {
152 match self.sock.recv(&mut buf) {
153 Ok(n) => best = best.max(datagram_id(&buf[..n])),
154 Err(_) => break,
155 }
156 }
157 Ok(Wake::Woke(best))
158 }
159}
160
161/// A malformed datagram (anyone who can write the board can send one) still wakes, with id 0.
162fn datagram_id(b: &[u8]) -> u64 {
163 match <[u8; 8]>::try_from(b) {
164 Ok(a) => u64::from_le_bytes(a),
165 Err(_) => 0,
166 }
167}
168
169impl Drop for Watcher {
170 fn drop(&mut self) {
171 // Best-effort cleanup of a non-durable socket: a failed lookup leaves the file, and
172 // the next `bind` finds it stale (connect refused) and removes it.
173 if let Ok(m) = fs::symlink_metadata(&self.path) {
174 if (m.dev(), m.ino()) == self.ino {
175 let _ = fs::remove_file(&self.path);
176 }
177 }
178 }
179}
180
181/// Send `id` to every wake socket under `root/wake` (best effort, non-blocking). Returns the
182/// number of datagrams accepted by the kernel.
183///
184/// Every failure here (an unlistable `wake/`, an unreadable entry, a socket lookup or send
185/// that fails) only skips a wake, deliberately: wakes are advisory and sent after the ACK,
186/// nothing durable or acknowledged depends on them, and a watcher that misses one still
187/// finds the event on its next read (`Board::wait` reads before it blocks, and a wait
188/// ends at its timeout).
189pub(crate) fn wake_all(root: &Path, id: u64) -> usize {
190 let Ok(rd) = fs::read_dir(root.join("wake")) else {
191 return 0;
192 };
193 let Ok(tx) = UnixDatagram::unbound() else {
194 return 0;
195 };
196 if tx.set_nonblocking(true).is_err() {
197 return 0;
198 }
199 let msg = id.to_le_bytes();
200 let mut tried = 0;
201 let mut sent = 0;
202 for ent in rd.filter_map(|e| e.ok()) {
203 if tried == MAX_WAKE_FANOUT {
204 break;
205 }
206 let name = ent.file_name();
207 let Some(n) = name.to_str() else { continue };
208 if !is_wake_name(n) {
209 continue;
210 }
211 let p = ent.path();
212 match fs::symlink_metadata(&p) {
213 Ok(m) if m.file_type().is_socket() => {}
214 _ => continue,
215 }
216 tried += 1;
217 if tx.send_to(&msg, &p).is_ok() {
218 sent += 1;
219 }
220 }
221 sent
222}
223
224impl Board {
225 /// Bind this session's wake socket. Bind before reading, then wait: a post that lands
226 /// between the read and the wait still wakes the socket.
227 pub fn watcher(&self, session: &str) -> Result<Watcher, BoardError> {
228 let me = self.whoami(session)?;
229 Watcher::bind(self, &me.tag)
230 }
231
232 /// Wait up to `timeout` for something new for this session. Returns `Woke` at once when
233 /// events past the `delivered` cursor are already visible to it; otherwise binds the
234 /// wake socket for the duration of the call and blocks on it. Race-free: the socket is
235 /// bound before the check.
236 pub fn wait(&self, session: &str, timeout: Duration) -> Result<Wake, BoardError> {
237 let w = self.watcher(session)?;
238 if let Some(id) = self.first_undelivered(session)? {
239 return Ok(Wake::Woke(id));
240 }
241 w.wait(timeout)
242 }
243
244 /// The first event past the `delivered` cursor visible to this session, if any (pure).
245 fn first_undelivered(&self, session: &str) -> Result<Option<u64>, BoardError> {
246 let me = self.whoami(session)?;
247 let mut after = self.start_after(&me.tag, Resume::Delivered)?;
248 loop {
249 let b = self.read_since(session, after, 64)?;
250 if let Some(d) = b.events.first() {
251 return Ok(Some(d.event.id));
252 }
253 if !b.more || b.through <= after {
254 return Ok(None);
255 }
256 after = b.through;
257 }
258 }
259}