1use crate::client::Client;
6use crate::error::{Error, Result};
7use crate::wire::{self, WatchEventKind};
8use std::collections::{HashMap, VecDeque};
9use std::io;
10use std::panic::{catch_unwind, AssertUnwindSafe};
11use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
12use std::sync::{Arc, Condvar, Mutex, MutexGuard};
13use std::time::{Duration, Instant, SystemTime};
14
15const LISTENER_QUEUE: usize = 1024;
17const WARM_CACHE: usize = 1024;
19
20pub type Logger = Arc<dyn Fn(&str) + Send + Sync>;
22
23pub(crate) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
24 m.lock().unwrap_or_else(|e| e.into_inner())
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum EventKind {
31 WarmDone,
33 WarmFailed,
35 Change,
37 Overflow,
40 Closing,
42 ConnectionLost,
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum ChangeKind {
51 Create,
52 Remove,
53 Write,
54 Rename,
56 Attrib,
57}
58
59#[derive(Debug)]
62#[non_exhaustive]
63pub struct Event {
64 pub kind: EventKind,
65 pub sequence: u64,
67 pub ref_id: u64,
68 pub path: String,
69 pub old_path: String,
70 pub change: Option<ChangeKind>,
72 pub error: Option<Error>,
74 pub time: SystemTime,
76}
77
78impl Clone for Event {
79 fn clone(&self) -> Event {
80 Event {
81 kind: self.kind,
82 sequence: self.sequence,
83 ref_id: self.ref_id,
84 path: self.path.clone(),
85 old_path: self.old_path.clone(),
86 change: self.change,
87 error: self.error.as_ref().map(Error::dup),
88 time: self.time,
89 }
90 }
91}
92
93impl Event {
94 pub(crate) fn local(kind: EventKind, ref_id: u64, error: Option<Error>) -> Event {
95 Event {
96 kind,
97 sequence: 0,
98 ref_id,
99 path: String::new(),
100 old_path: String::new(),
101 change: None,
102 error,
103 time: SystemTime::now(),
104 }
105 }
106
107 pub(crate) fn from_wire(m: wire::Notice) -> Option<Event> {
109 let mut change = None;
110 let kind = match wire::NoticeKind::try_from(m.kind).ok()? {
111 wire::NoticeKind::WarmDone => EventKind::WarmDone,
112 wire::NoticeKind::WarmFailed => EventKind::WarmFailed,
113 wire::NoticeKind::Closing => EventKind::Closing,
114 wire::NoticeKind::Overflow => EventKind::Overflow,
115 wire::NoticeKind::Change => {
116 change = match WatchEventKind::try_from(m.change_kind).ok()? {
117 WatchEventKind::Create => Some(ChangeKind::Create),
118 WatchEventKind::Remove => Some(ChangeKind::Remove),
119 WatchEventKind::Write => Some(ChangeKind::Write),
120 WatchEventKind::Rename => Some(ChangeKind::Rename),
121 WatchEventKind::Attrib => Some(ChangeKind::Attrib),
122 WatchEventKind::Overflow => None,
123 };
124 if change.is_some() {
125 EventKind::Change
126 } else {
127 EventKind::Overflow
128 }
129 }
130 };
131 let error = (kind == EventKind::WarmFailed).then_some(Error::Server {
132 code: m.code,
133 message: m.message,
134 });
135 Some(Event {
136 kind,
137 sequence: m.sequence,
138 ref_id: m.ref_id,
139 path: m.path,
140 old_path: m.old_path,
141 change,
142 error,
143 time: SystemTime::now(),
144 })
145 }
146
147 fn log_line(&self) -> String {
148 let err = self
149 .error
150 .as_ref()
151 .map_or_else(|| "none".to_string(), |e| e.to_string());
152 format!(
153 "event kind={:?} ref_id={} path={:?} error={}",
154 self.kind, self.ref_id, self.path, err
155 )
156 }
157}
158
159#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
161pub struct ListenerId(u64);
162
163struct ChanState {
164 items: VecDeque<Event>,
165 overflowed: bool,
167 closed: bool,
168}
169
170pub(crate) struct Chan {
172 cap: usize,
173 ref_id: AtomicU64,
175 st: Mutex<ChanState>,
176 cv: Condvar,
177}
178
179impl Chan {
180 pub(crate) fn new(cap: usize, ref_id: u64) -> Chan {
181 Chan {
182 cap,
183 ref_id: AtomicU64::new(ref_id),
184 st: Mutex::new(ChanState {
185 items: VecDeque::new(),
186 overflowed: false,
187 closed: false,
188 }),
189 cv: Condvar::new(),
190 }
191 }
192
193 pub(crate) fn set_ref_id(&self, id: u64) {
194 self.ref_id.store(id, Ordering::SeqCst);
195 }
196
197 pub(crate) fn push(&self, ev: Event) -> bool {
200 let mut st = lock(&self.st);
201 if st.closed {
202 return false;
203 }
204 let mut started = false;
205 if st.items.len() >= self.cap {
206 st.items.pop_front();
207 started = !st.overflowed;
208 st.overflowed = true;
209 }
210 st.items.push_back(ev);
211 drop(st);
212 self.cv.notify_one();
213 started
214 }
215
216 pub(crate) fn close(&self, discard: bool) {
218 let mut st = lock(&self.st);
219 st.closed = true;
220 if discard {
221 st.items.clear();
222 st.overflowed = false;
223 }
224 drop(st);
225 self.cv.notify_all();
226 }
227
228 pub(crate) fn pop(&self, timeout: Option<Duration>) -> Option<Event> {
231 let deadline = timeout.and_then(|t| Instant::now().checked_add(t));
232 let mut st = lock(&self.st);
233 loop {
234 if st.overflowed {
235 st.overflowed = false;
236 return Some(Event::local(
237 EventKind::Overflow,
238 self.ref_id.load(Ordering::SeqCst),
239 None,
240 ));
241 }
242 if let Some(ev) = st.items.pop_front() {
243 return Some(ev);
244 }
245 if st.closed {
246 return None;
247 }
248 st = match deadline {
249 None => self.cv.wait(st).unwrap_or_else(|e| e.into_inner()),
250 Some(d) => {
251 let left = d.saturating_duration_since(Instant::now());
252 if left.is_zero() {
253 return None;
254 }
255 self.cv.wait_timeout(st, left).unwrap_or_else(|e| e.into_inner()).0
256 }
257 };
258 }
259 }
260}
261
262type Listener = Arc<dyn Fn(&Event) + Send + Sync>;
263
264#[derive(Default)]
265struct Warms {
266 done: HashMap<u64, std::result::Result<(), (String, String)>>,
268 order: VecDeque<u64>,
269 closed: bool,
270}
271
272struct WatchEntry {
273 conn: u64,
274 chan: Arc<Chan>,
275}
276
277pub(crate) struct Hub {
279 logger: Logger,
280 listeners: Mutex<Vec<(ListenerId, Listener)>>,
281 next_listener: AtomicU64,
282 queue: Chan,
283 warms: Mutex<Warms>,
284 warm_cv: Condvar,
285 watches: Mutex<HashMap<u64, WatchEntry>>,
286 threads: Arc<AtomicUsize>,
288}
289
290pub(crate) struct ThreadGuard(Arc<AtomicUsize>);
292
293impl Drop for ThreadGuard {
294 fn drop(&mut self) {
295 self.0.fetch_sub(1, Ordering::SeqCst);
296 }
297}
298
299impl Hub {
300 pub(crate) fn thread_guard(&self) -> ThreadGuard {
302 self.threads.fetch_add(1, Ordering::SeqCst);
303 ThreadGuard(self.threads.clone())
304 }
305
306 pub(crate) fn thread_probe(&self) -> Arc<AtomicUsize> {
307 self.threads.clone()
308 }
309
310 pub(crate) fn new(logger: Option<Logger>) -> Hub {
311 Hub {
312 logger: logger.unwrap_or_else(|| Arc::new(|line: &str| eprintln!("mountos: {line}"))),
313 listeners: Mutex::new(Vec::new()),
314 next_listener: AtomicU64::new(1),
315 queue: Chan::new(LISTENER_QUEUE, 0),
316 warms: Mutex::new(Warms::default()),
317 warm_cv: Condvar::new(),
318 watches: Mutex::new(HashMap::new()),
319 threads: Arc::new(AtomicUsize::new(0)),
320 }
321 }
322
323 pub(crate) fn log(&self, line: &str) {
324 (self.logger)(line);
325 }
326
327 pub(crate) fn add_watch(&self, id: u64, conn: u64, chan: Arc<Chan>) {
328 chan.set_ref_id(id);
329 lock(&self.watches).insert(id, WatchEntry { conn, chan });
330 }
331
332 pub(crate) fn remove_watch(&self, id: u64) {
333 lock(&self.watches).remove(&id);
334 }
335
336 pub(crate) fn conn_lost(&self, conn: u64) {
338 lock(&self.watches).retain(|_, w| {
339 if w.conn == conn {
340 w.chan.close(false);
341 false
342 } else {
343 true
344 }
345 });
346 }
347
348 pub(crate) fn publish(&self, conn: Option<u64>, ev: Event) {
352 match ev.kind {
353 EventKind::WarmDone | EventKind::WarmFailed => self.record_warm(&ev),
354 EventKind::Overflow if ev.ref_id == 0 => {
355 if let Some(conn) = conn {
356 let chans: Vec<Arc<Chan>> = lock(&self.watches)
357 .values()
358 .filter(|w| w.conn == conn)
359 .map(|w| w.chan.clone())
360 .collect();
361 for c in chans {
362 c.push(ev.clone());
363 }
364 }
365 }
366 EventKind::Change | EventKind::Overflow if ev.ref_id != 0 => {
367 let chan = lock(&self.watches).get(&ev.ref_id).map(|w| w.chan.clone());
368 if let Some(c) = chan {
369 if c.push(ev.clone()) {
370 self.log(&format!("watch {} queue full, dropped oldest events", ev.ref_id));
371 }
372 }
373 }
374 _ => {}
375 }
376 if self.queue.push(ev) {
377 self.log("listener queue full, dropped oldest events");
378 }
379 }
380
381 fn record_warm(&self, ev: &Event) {
382 let r = match &ev.error {
383 Some(Error::Server { code, message }) => Err((code.clone(), message.clone())),
384 _ => Ok(()),
385 };
386 let mut w = lock(&self.warms);
387 if w.done.insert(ev.ref_id, r).is_none() {
388 w.order.push_back(ev.ref_id);
389 }
390 while w.order.len() > WARM_CACHE {
391 if let Some(old) = w.order.pop_front() {
392 w.done.remove(&old);
393 }
394 }
395 drop(w);
396 self.warm_cv.notify_all();
397 }
398
399 pub(crate) fn wait_warm(&self, id: u64, timeout: Duration) -> Result<()> {
400 let deadline = Instant::now().checked_add(timeout);
401 let mut w = lock(&self.warms);
402 loop {
403 if w.closed {
404 return Err(Error::Io(io::Error::new(
405 io::ErrorKind::ConnectionAborted,
406 "client closed",
407 )));
408 }
409 match w.done.get(&id) {
410 Some(Ok(())) => return Ok(()),
411 Some(Err((code, message))) => {
412 return Err(Error::Server {
413 code: code.clone(),
414 message: message.clone(),
415 })
416 }
417 None => {}
418 }
419 let left = match deadline {
420 Some(d) => d.saturating_duration_since(Instant::now()),
421 None => Duration::from_secs(3600),
422 };
423 if left.is_zero() {
424 return Err(Error::Io(io::Error::new(
425 io::ErrorKind::TimedOut,
426 "wait_warm timed out",
427 )));
428 }
429 w = self.warm_cv.wait_timeout(w, left).unwrap_or_else(|e| e.into_inner()).0;
430 }
431 }
432
433 pub(crate) fn shutdown(&self) {
435 self.queue.close(true);
436 for (_, w) in lock(&self.watches).drain() {
437 w.chan.close(false);
438 }
439 lock(&self.warms).closed = true;
440 self.warm_cv.notify_all();
441 }
442
443 pub(crate) fn clear_listeners(&self) {
445 let old = std::mem::take(&mut *lock(&self.listeners));
446 drop(old);
447 }
448
449 pub(crate) fn dispatch_loop(&self) {
451 while let Some(ev) = self.queue.pop(None) {
452 let ls: Vec<Listener> = lock(&self.listeners).iter().map(|(_, l)| l.clone()).collect();
453 if ls.is_empty() {
454 self.log(&ev.log_line());
455 continue;
456 }
457 for l in ls {
458 if catch_unwind(AssertUnwindSafe(|| l(&ev))).is_err() {
459 self.log(&format!("listener panicked on {}", ev.log_line()));
460 }
461 }
462 }
463 }
464}
465
466impl Client {
467 pub fn add_listener(&self, f: impl Fn(&Event) + Send + Sync + 'static) -> ListenerId {
473 let hub = &self.inner.hub;
474 let id = ListenerId(hub.next_listener.fetch_add(1, Ordering::SeqCst));
475 lock(&hub.listeners).push((id, Arc::new(f)));
476 id
477 }
478
479 #[doc(hidden)]
481 pub fn thread_probe(&self) -> Arc<AtomicUsize> {
482 self.inner.hub.thread_probe()
483 }
484
485 pub fn remove_listener(&self, id: ListenerId) {
487 lock(&self.inner.hub.listeners).retain(|(i, _)| *i != id);
488 }
489
490 pub fn wait_warm(&self, id: u64, timeout: Duration) -> Result<()> {
495 self.inner.hub.wait_warm(id, timeout)
496 }
497}