Skip to main content

mountos_native/
client.rs

1use crate::dir::Dir;
2use crate::error::{Error, Result};
3use crate::events::{lock, Chan, Event, EventKind, Hub, Logger};
4use crate::file::File;
5use crate::frame::{self, Frame, FLAG_ERROR, FLAG_NOTIFY, FLAG_RESPONSE, MAX_PAYLOAD_BYTES};
6use crate::wire::*;
7use prost::Message;
8use std::collections::{HashMap, HashSet};
9use std::fmt;
10use std::io;
11use std::net::Shutdown;
12use std::os::unix::net::UnixStream;
13use std::path::{Path, PathBuf};
14use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
15use std::sync::{Arc, Condvar, Mutex, OnceLock};
16use std::thread::JoinHandle;
17use std::time::{Duration, Instant};
18
19/// Client settings. Start from `Options::default()` and chain the `with_` methods. New fields
20/// can be added in a minor version, so a struct literal does not compile outside this crate.
21#[derive(Clone)]
22#[non_exhaustive]
23pub struct Options {
24  /// Number of connections. Calls on different files can run in parallel up to this number.
25  pub pool_size: usize,
26  pub client_name: String,
27  /// Receives log lines: events nobody listens for, listener panics and dropped events.
28  /// The line has no prefix and no newline. When `None`, lines go to stderr with the prefix
29  /// "mountos: ". Pass your own function to route them elsewhere.
30  pub logger: Option<Logger>,
31  /// Longest a single request may take, from the end of the send to the reply. `Duration::ZERO`
32  /// (the default) means no limit. A call that runs over fails with `Error::Timeout`. When the
33  /// connection pipelines, only that call fails: its id is marked abandoned and the late reply is
34  /// dropped. Otherwise, or when too many ids are abandoned, the connection is dropped and dialed
35  /// again on the next call, and its files and watches are gone. A call that sends several
36  /// requests (a large read or write) gets the limit for each request.
37  pub call_timeout: Duration,
38  /// Most requests outstanding on one connection when the server pipelines. The server limit
39  /// (`max_inflight` in its Hello reply) also applies. Values are held between 1 and 1024. A
40  /// server without the pipelining capability gets one request at a time.
41  pub max_inflight: usize,
42}
43
44/// Default for `Options::max_inflight`.
45pub const DEFAULT_MAX_INFLIGHT: usize = 32;
46const MAX_INFLIGHT_CEILING: usize = 1024;
47
48/// Alias of `Options`.
49pub type ClientOptions = Options;
50
51impl Default for Options {
52  fn default() -> Options {
53    Options {
54      pool_size: 4,
55      client_name: concat!("mountos-native-rust/", env!("CARGO_PKG_VERSION")).into(),
56      logger: None,
57      call_timeout: Duration::ZERO,
58      max_inflight: DEFAULT_MAX_INFLIGHT,
59    }
60  }
61}
62
63impl Options {
64  /// Sets `pool_size`.
65  pub fn with_pool_size(mut self, pool_size: usize) -> Options {
66    self.pool_size = pool_size;
67    self
68  }
69
70  /// Sets `logger`.
71  pub fn with_logger(mut self, logger: Logger) -> Options {
72    self.logger = Some(logger);
73    self
74  }
75
76  /// Sets `call_timeout`.
77  pub fn with_call_timeout(mut self, call_timeout: Duration) -> Options {
78    self.call_timeout = call_timeout;
79    self
80  }
81
82  /// Sets `max_inflight`.
83  pub fn with_max_inflight(mut self, max_inflight: usize) -> Options {
84    self.max_inflight = max_inflight;
85    self
86  }
87}
88
89impl fmt::Debug for Options {
90  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91    f.debug_struct("Options")
92      .field("pool_size", &self.pool_size)
93      .field("client_name", &self.client_name)
94      .field("logger", &self.logger.as_ref().map(|_| "<fn>"))
95      .field("call_timeout", &self.call_timeout)
96      .field("max_inflight", &self.max_inflight)
97      .finish()
98  }
99}
100
101fn aborted(msg: &str) -> Error {
102  Error::Io(io::Error::new(io::ErrorKind::ConnectionAborted, msg.to_string()))
103}
104
105/// Joins a thread unless it is the calling one, which would wait for itself.
106fn join_other(h: JoinHandle<()>) {
107  if h.thread().id() != std::thread::current().id() {
108    let _ = h.join();
109  }
110}
111
112/// Capability the server must report for a method, if any.
113fn required_capability(m: u16) -> Option<&'static str> {
114  match m {
115    method::LS => Some("ls_stat"),
116    method::STAT_BATCH | method::READ_BATCH | method::WRITE_BATCH | method::READ_FILE | method::WRITE_FILE => {
117      Some("bulk_io")
118    }
119    method::REMOVE_ALL => Some("remove_all"),
120    method::WATCH => Some("watch"),
121    method::WARM_OPEN | method::WARM_READ => Some("warm"),
122    _ => None,
123  }
124}
125
126/// Turns a socket write that hit the send timeout into `Error::Timeout`.
127fn write_timeout(e: Error) -> Error {
128  match e {
129    Error::Io(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {
130      Error::Timeout(format!("send: {e}"))
131    }
132    e => e,
133  }
134}
135
136static CONN_SEQ: AtomicU64 = AtomicU64::new(1);
137
138/// One request in flight. The caller waits on it, the reader fills it.
139struct Waiter {
140  method: u16,
141  /// Queue that receives the notices of a watch started by this request.
142  watch: Option<Arc<Chan>>,
143  out: Mutex<Option<Result<Frame>>>,
144  cv: Condvar,
145}
146
147impl Waiter {
148  fn set(&self, r: Result<Frame>) {
149    *lock(&self.out) = Some(r);
150    self.cv.notify_one();
151  }
152
153  /// Waits for the result. `None` means the deadline passed first.
154  fn wait(&self, deadline: Option<Instant>) -> Option<Result<Frame>> {
155    let mut g = lock(&self.out);
156    loop {
157      if let Some(r) = g.take() {
158        return Some(r);
159      }
160      g = match deadline {
161        None => self.cv.wait(g).unwrap_or_else(|e| e.into_inner()),
162        Some(d) => {
163          let left = d.saturating_duration_since(Instant::now());
164          if left.is_zero() {
165            return None;
166          }
167          self.cv.wait_timeout(g, left).unwrap_or_else(|e| e.into_inner()).0
168        }
169      };
170    }
171  }
172}
173
174#[derive(Default)]
175struct Core {
176  pending: HashMap<u64, Arc<Waiter>>,
177  /// Ids whose caller gave up, with the method. A late reply is dropped (an Open, Opendir or
178  /// Watch reply also releases what it created).
179  abandoned: HashMap<u64, u16>,
180  next_id: u64,
181  /// Why the connection ended. Set once.
182  end: Option<Error>,
183}
184
185/// What the Hello reply settled.
186struct Info {
187  max_payload: usize,
188  /// Requests that may be outstanding at once.
189  limit: usize,
190  /// Capabilities the server reported. `None` when it reported none (an older server), which
191  /// allows every call.
192  caps: Option<HashSet<String>>,
193}
194
195/// One handshaken connection. Calls from many threads overlap up to the limit. Request frames are
196/// written under a mutex. One reader thread reads every frame: replies go to the waiting call by
197/// request id, notices go to the hub.
198pub(crate) struct Sock {
199  id: u64,
200  hub: Arc<Hub>,
201  /// Per-request limit, zero for none.
202  timeout: Duration,
203  writer: Mutex<UnixStream>,
204  /// Second handle on the socket. Closes the socket from another thread.
205  killer: UnixStream,
206  core: Mutex<Core>,
207  dead: AtomicBool,
208  /// Set when this side ends the connection on purpose.
209  closing: AtomicBool,
210  /// The server sent Closing, so the end that follows is expected.
211  saw_closing: AtomicBool,
212  info: OnceLock<Info>,
213  reader: Mutex<Option<JoinHandle<()>>>,
214  /// Threads that release a handle or watch created by a request that timed out.
215  releasers: Mutex<Vec<JoinHandle<()>>>,
216}
217
218impl Sock {
219  /// Connects and starts the reader. The handshake is separate so a caller can register the
220  /// socket for `close` before it blocks.
221  fn open(path: &Path, hub: &Arc<Hub>, timeout: Duration) -> Result<Arc<Sock>> {
222    let stream = UnixStream::connect(path)?;
223    if !timeout.is_zero() {
224      stream.set_write_timeout(Some(timeout))?;
225    }
226    let (rs, killer) = (stream.try_clone()?, stream.try_clone()?);
227    let sock = Arc::new(Sock {
228      id: CONN_SEQ.fetch_add(1, Ordering::SeqCst),
229      hub: hub.clone(),
230      timeout,
231      writer: Mutex::new(stream),
232      killer,
233      core: Mutex::new(Core::default()),
234      dead: AtomicBool::new(false),
235      closing: AtomicBool::new(false),
236      saw_closing: AtomicBool::new(false),
237      info: OnceLock::new(),
238      reader: Mutex::new(None),
239      releasers: Mutex::new(Vec::new()),
240    });
241    let (rsock, guard) = (sock.clone(), hub.thread_guard());
242    let h = std::thread::Builder::new()
243      .name("mountos-reader".into())
244      .spawn(move || {
245        let _guard = guard;
246        read_loop(rs, &rsock)
247      })?;
248    *lock(&sock.reader) = Some(h);
249    Ok(sock)
250  }
251
252  fn handshake(&self, name: &str, max_inflight: usize) -> Result<()> {
253    let req = HelloRequest {
254      client_name: name.into(),
255      min_version: 1,
256      max_version: 1,
257      capabilities: vec!["pipelining".into()],
258    };
259    let (resp, _): (HelloResponse, _) = self.call_msg(method::HELLO, &req, &[])?;
260    if resp.version != 1 {
261      return Err(Error::Protocol(format!("server chose version {}", resp.version)));
262    }
263    let mut max_payload = MAX_PAYLOAD_BYTES as usize;
264    if resp.max_payload_bytes > 0 {
265      max_payload = max_payload.min(resp.max_payload_bytes as usize);
266    }
267    let pipelined = resp.capabilities.iter().any(|c| c == "pipelining");
268    let limit = if pipelined {
269      max_inflight.min(resp.max_inflight as usize).max(1)
270    } else {
271      1
272    };
273    let caps = (!resp.capabilities.is_empty()).then(|| resp.capabilities.into_iter().collect());
274    let _ = self.info.set(Info {
275      max_payload,
276      limit,
277      caps,
278    });
279    Ok(())
280  }
281
282  pub(crate) fn max_payload(&self) -> usize {
283    self.info.get().map_or(MAX_PAYLOAD_BYTES as usize, |i| i.max_payload)
284  }
285
286  fn limit(&self) -> usize {
287    self.info.get().map_or(1, |i| i.limit)
288  }
289
290  fn is_dead(&self) -> bool {
291    self.dead.load(Ordering::SeqCst)
292  }
293
294  /// Ends the connection once: the first reason wins. Every waiting call gets `end`.
295  fn fail(&self, end: Error, report: bool) {
296    let waiters: Vec<Arc<Waiter>> = {
297      let mut core = lock(&self.core);
298      if core.end.is_some() {
299        return;
300      }
301      core.end = Some(end.dup());
302      self.dead.store(true, Ordering::SeqCst);
303      core.abandoned.clear();
304      core.pending.drain().map(|(_, w)| w).collect()
305    };
306    let _ = self.killer.shutdown(Shutdown::Both);
307    for w in waiters {
308      w.set(Err(end.dup()));
309    }
310    self.hub.conn_lost(self.id);
311    let expected = self.closing.load(Ordering::SeqCst) || self.saw_closing.load(Ordering::SeqCst);
312    if report && !expected {
313      self
314        .hub
315        .publish(None, Event::local(EventKind::ConnectionLost, 0, Some(end.dup())));
316    }
317  }
318
319  /// Ends the connection on purpose.
320  pub(crate) fn kill(&self) {
321    self.closing.store(true, Ordering::SeqCst);
322    self.fail(aborted("connection closed"), false);
323  }
324
325  /// Ends the connection because of a local fault. Waiting calls get a copy of `e`.
326  fn kill_with(&self, e: &Error) {
327    self.closing.store(true, Ordering::SeqCst);
328    self.fail(e.dup(), false);
329  }
330
331  /// Ends the connection and joins its threads.
332  fn finish(&self) {
333    self.kill();
334    let reader = lock(&self.reader).take();
335    if let Some(h) = reader {
336      join_other(h);
337    }
338    let releasers = std::mem::take(&mut *lock(&self.releasers));
339    for h in releasers {
340      join_other(h);
341    }
342  }
343
344  fn forget(&self, id: u64) {
345    lock(&self.core).pending.remove(&id);
346  }
347
348  /// Sends one request and waits for its response frame. The sizes and the capability are
349  /// checked before anything is sent, so those failures leave the connection intact.
350  fn call(&self, method: u16, req: &impl Message, payload: &[u8], watch: Option<Arc<Chan>>) -> Result<Frame> {
351    if let Some(cap) = required_capability(method) {
352      if self
353        .info
354        .get()
355        .and_then(|i| i.caps.as_ref())
356        .is_some_and(|c| !c.contains(cap))
357      {
358        return Err(Error::server(
359          "UNSUPPORTED_OPERATION",
360          &format!("the server does not report capability {cap}"),
361        ));
362      }
363    }
364    let meta = req.encode_to_vec();
365    frame::check_limits(meta.len(), payload.len())?;
366    let w = Arc::new(Waiter {
367      method,
368      watch,
369      out: Mutex::new(None),
370      cv: Condvar::new(),
371    });
372    let id = {
373      let mut core = lock(&self.core);
374      if let Some(e) = &core.end {
375        return Err(e.dup());
376      }
377      core.next_id += 1;
378      let id = core.next_id;
379      core.pending.insert(id, w.clone());
380      id
381    };
382    let sent = {
383      let mut s = lock(&self.writer);
384      frame::write_parts(&mut *s, 0, method, id, &meta, payload).map_err(write_timeout)
385    };
386    if let Err(e) = sent {
387      // A failed write may leave half a frame on the wire, so the connection is unusable.
388      self.forget(id);
389      self.kill_with(&aborted(&format!("send failed: {e}")));
390      return Err(e);
391    }
392    let deadline = (!self.timeout.is_zero()).then(|| Instant::now() + self.timeout);
393    let resp = match w.wait(deadline) {
394      Some(r) => r?,
395      None => self.give_up(id, method, &w)?,
396    };
397    if resp.flags & FLAG_ERROR != 0 {
398      let e = match WireError::decode(&resp.meta[..]) {
399        Ok(e) => e,
400        Err(e) => {
401          let e = Error::Protocol(format!("bad error meta: {e}"));
402          self.kill_with(&e);
403          return Err(e);
404        }
405      };
406      return Err(Error::Server {
407        code: e.code,
408        message: e.message,
409      });
410    }
411    Ok(resp)
412  }
413
414  /// Handles a call whose wait ran out. With room in the abandoned set the connection stays up
415  /// and the late reply is dropped. Otherwise the connection is cut.
416  fn give_up(&self, id: u64, method: u16, w: &Waiter) -> Result<Frame> {
417    let limit = self.limit();
418    let kept = {
419      let mut core = lock(&self.core);
420      if core.pending.remove(&id).is_none() {
421        None
422      } else if limit > 1 && core.abandoned.len() < limit * 4 {
423        core.abandoned.insert(id, method);
424        Some(true)
425      } else {
426        Some(false)
427      }
428    };
429    match kept {
430      // The reply or the failure won the race and is being delivered.
431      None => w.wait(None).unwrap_or_else(|| Err(aborted("connection closed"))),
432      Some(keep) => {
433        if !keep {
434          self.kill();
435        }
436        Err(Error::Timeout(format!(
437          "method {method} did not finish within {:?}",
438          self.timeout
439        )))
440      }
441    }
442  }
443
444  /// Like `call`, decoding the meta as `R` and returning the reply payload.
445  pub(crate) fn call_msg<R: Message + Default>(
446    &self,
447    method: u16,
448    req: &impl Message,
449    payload: &[u8],
450  ) -> Result<(R, Vec<u8>)> {
451    self.decode(self.call(method, req, payload, None)?)
452  }
453
454  /// Starts a watch. The reader routes the notices of the new watch to `chan` before the call returns.
455  pub(crate) fn call_watch(&self, req: &WatchRequest, chan: Arc<Chan>) -> Result<WatchResponse> {
456    Ok(self.decode(self.call(method::WATCH, req, &[], Some(chan))?)?.0)
457  }
458
459  fn decode<R: Message + Default>(&self, resp: Frame) -> Result<(R, Vec<u8>)> {
460    match R::decode(&resp.meta[..]) {
461      Ok(msg) => Ok((msg, resp.payload)),
462      Err(e) => {
463        let e = Error::Protocol(format!("bad response meta: {e}"));
464        self.kill_with(&e);
465        Err(e)
466      }
467    }
468  }
469
470  /// Routes one non-notice frame from the reader. An error is a protocol violation.
471  fn deliver(self: &Arc<Self>, hub: &Hub, f: Frame) -> Result<()> {
472    let unexpected = |f: &Frame| Error::Protocol(format!("unexpected frame: method {} id {}", f.method, f.request_id));
473    if f.flags & FLAG_RESPONSE == 0 {
474      return Err(unexpected(&f));
475    }
476    let waiter = {
477      let mut core = lock(&self.core);
478      match core.pending.get(&f.request_id).map(|w| w.method) {
479        Some(m) if m == f.method => core.pending.remove(&f.request_id),
480        Some(_) => return Err(unexpected(&f)),
481        None => {
482          if core.abandoned.get(&f.request_id) != Some(&f.method) {
483            return Err(unexpected(&f));
484          }
485          core.abandoned.remove(&f.request_id);
486          None
487        }
488      }
489    };
490    let ok = f.flags & (FLAG_RESPONSE | FLAG_ERROR) == FLAG_RESPONSE;
491    match waiter {
492      Some(w) => {
493        if ok && f.method == method::WATCH {
494          if let (Ok(r), Some(chan)) = (WatchResponse::decode(&f.meta[..]), &w.watch) {
495            hub.add_watch(r.watch_id, self.id, chan.clone());
496          }
497        }
498        w.set(Ok(f));
499      }
500      None if ok => self.release_late(f),
501      None => {}
502    }
503    Ok(())
504  }
505
506  /// A reply arrived for a request nobody waits for. An Open, Opendir or Watch created a server
507  /// resource, so a thread frees it. The reader never writes: it must keep reading.
508  fn release_late(self: &Arc<Self>, f: Frame) {
509    let job: Box<dyn FnOnce(&Sock) + Send> = match f.method {
510      method::OPEN => match OpenResponse::decode(&f.meta[..]) {
511        Ok(r) => Box::new(move |s| drop(s.call_msg::<Empty>(method::CLOSE, &CloseRequest { handle: r.handle }, &[]))),
512        Err(_) => return,
513      },
514      method::OPENDIR => match OpendirResponse::decode(&f.meta[..]) {
515        Ok(r) => {
516          Box::new(move |s| drop(s.call_msg::<Empty>(method::CLOSEDIR, &ClosedirRequest { handle: r.handle }, &[])))
517        }
518        Err(_) => return,
519      },
520      method::WATCH => match WatchResponse::decode(&f.meta[..]) {
521        Ok(r) => {
522          Box::new(move |s| drop(s.call_msg::<Empty>(method::UNWATCH, &UnwatchRequest { watch_id: r.watch_id }, &[])))
523        }
524        Err(_) => return,
525      },
526      _ => return,
527    };
528    if self.is_dead() {
529      return;
530    }
531    let (sock, guard) = (self.clone(), self.hub.thread_guard());
532    let spawned = std::thread::Builder::new()
533      .name("mountos-release".into())
534      .spawn(move || {
535        let _guard = guard;
536        job(&sock)
537      });
538    match spawned {
539      Ok(h) => {
540        let mut rs = lock(&self.releasers);
541        rs.retain(|h| !h.is_finished());
542        rs.push(h);
543      }
544      Err(e) => self.hub.log(&format!("could not start release of a late reply: {e}")),
545    }
546  }
547}
548
549/// Reads frames until the stream ends. Replies go to the waiting call, notices to the hub.
550fn read_loop(mut s: UnixStream, sock: &Arc<Sock>) {
551  let hub = sock.hub.clone();
552  let end = loop {
553    match frame::read(&mut s) {
554      Ok(Some(f)) if f.flags & FLAG_NOTIFY != 0 => on_notice(f, &hub, sock),
555      Ok(Some(f)) => {
556        if let Err(e) = sock.deliver(&hub, f) {
557          break e;
558        }
559      }
560      Ok(None) => break aborted("server closed the connection"),
561      Err(e) => break e,
562    }
563  };
564  let _ = s.shutdown(Shutdown::Both);
565  sock.fail(end, true);
566}
567
568fn on_notice(f: Frame, hub: &Hub, sock: &Sock) {
569  if f.method != method::NOTICE {
570    hub.log(&format!("ignored notify frame with method {}", f.method));
571    return;
572  }
573  let ev = match Notice::decode(&f.meta[..]) {
574    Ok(m) => match Event::from_wire(m) {
575      Some(ev) => ev,
576      None => {
577        hub.log("ignored notice of unknown kind");
578        return;
579      }
580    },
581    Err(e) => {
582      hub.log(&format!("ignored undecodable notice: {e}"));
583      return;
584    }
585  };
586  if ev.kind == EventKind::Closing {
587    sock.saw_closing.store(true, Ordering::SeqCst);
588  }
589  hub.publish(Some(sock.id), ev);
590}
591
592struct SlotState {
593  sock: Option<Arc<Sock>>,
594  /// Counts connects. A file remembers it to detect that its handle died with the old connection.
595  epoch: u64,
596}
597
598/// Wakes callers that wait for a free connection. Every release bumps the generation, so a
599/// waiter that read the generation before it scanned the pool cannot miss a release.
600#[derive(Default)]
601pub(crate) struct Gate {
602  generation: Mutex<u64>,
603  cv: Condvar,
604  /// Callers that found every connection busy and wait for the first to free.
605  waiting: AtomicUsize,
606}
607
608/// Marks a caller as waiting for any free connection until dropped.
609struct Waiting<'a>(&'a Gate);
610
611impl Drop for Waiting<'_> {
612  fn drop(&mut self) {
613    self.0.waiting.fetch_sub(1, Ordering::SeqCst);
614    self.0.bump();
615  }
616}
617
618impl Gate {
619  fn generation(&self) -> u64 {
620    *lock(&self.generation)
621  }
622
623  fn bump(&self) {
624    *lock(&self.generation) += 1;
625    self.cv.notify_all();
626  }
627
628  fn wait_change(&self, seen: u64) {
629    let mut g = lock(&self.generation);
630    while *g == seen {
631      g = self.cv.wait(g).unwrap_or_else(|e| e.into_inner());
632    }
633  }
634
635  fn wait_for_free(&self) -> Waiting<'_> {
636    self.waiting.fetch_add(1, Ordering::SeqCst);
637    Waiting(self)
638  }
639
640  /// Holds back a caller bound to one connection while others wait for any free one, so a long
641  /// operation that goes request after request cannot starve a small call.
642  fn let_waiters_pass(&self) {
643    loop {
644      let seen = self.generation();
645      if self.waiting.load(Ordering::SeqCst) == 0 {
646        return;
647      }
648      self.wait_change(seen);
649    }
650  }
651}
652
653/// Holds one of a slot's request places until dropped, then wakes callers that wait for room.
654struct Permit<'a>(&'a Slot);
655
656impl Drop for Permit<'_> {
657  fn drop(&mut self) {
658    self.0.outstanding.fetch_sub(1, Ordering::SeqCst);
659    self.0.gate.bump();
660  }
661}
662
663/// A lazily connected pool entry. Up to `limit` requests run on its connection at once. A
664/// request owns a place for one round trip only, never across the chunks of a large operation.
665pub(crate) struct Slot {
666  path: PathBuf,
667  name: String,
668  timeout: Duration,
669  max_inflight: usize,
670  hub: Arc<Hub>,
671  gate: Arc<Gate>,
672  /// Requests that hold a place.
673  outstanding: AtomicUsize,
674  /// Places available. One until the Hello reply says more.
675  limit: AtomicUsize,
676  closed: AtomicBool,
677  /// The current connection, reachable without the state lock so `close` can cut a dial or a
678  /// call in flight.
679  live: Mutex<Option<Arc<Sock>>>,
680  state: Mutex<SlotState>,
681}
682
683impl Slot {
684  fn try_reserve(&self) -> Option<Permit<'_>> {
685    let limit = self.limit.load(Ordering::SeqCst);
686    let mut cur = self.outstanding.load(Ordering::SeqCst);
687    loop {
688      if cur >= limit {
689        return None;
690      }
691      match self
692        .outstanding
693        .compare_exchange_weak(cur, cur + 1, Ordering::SeqCst, Ordering::SeqCst)
694      {
695        Ok(_) => return Some(Permit(self)),
696        Err(c) => cur = c,
697      }
698    }
699  }
700
701  /// Runs `f` on the connection once a place is free. With `want`, fails if the connection is
702  /// not the one with that epoch. A broken connection is replaced on the next call.
703  pub(crate) fn run<T>(&self, want: Option<u64>, f: impl FnOnce(&Sock) -> Result<T>) -> Result<(T, u64)> {
704    self.gate.let_waiters_pass();
705    let permit = loop {
706      let seen = self.gate.generation();
707      if self.closed.load(Ordering::SeqCst) {
708        return Err(aborted("client closed"));
709      }
710      if let Some(p) = self.try_reserve() {
711        break p;
712      }
713      self.gate.wait_change(seen);
714    };
715    self.exec(permit, want, f)
716  }
717
718  /// Runs `f` for a caller that already holds a place and releases it at the end.
719  fn exec<T>(&self, _permit: Permit<'_>, want: Option<u64>, f: impl FnOnce(&Sock) -> Result<T>) -> Result<(T, u64)> {
720    let (sock, epoch) = self.sock_for(want)?;
721    let r = f(&sock);
722    if matches!(r, Err(Error::Io(_)) | Err(Error::Protocol(_))) {
723      sock.kill();
724    }
725    r.map(|v| (v, epoch))
726  }
727
728  /// The live connection, dialed when there is none.
729  fn sock_for(&self, want: Option<u64>) -> Result<(Arc<Sock>, u64)> {
730    let mut st = lock(&self.state);
731    if self.closed.load(Ordering::SeqCst) {
732      return Err(aborted("client closed"));
733    }
734    let alive = st.sock.as_ref().is_some_and(|s| !s.is_dead());
735    if want.is_some_and(|e| !alive || st.epoch != e) {
736      return Err(aborted("connection lost, file handle is gone"));
737    }
738    if !alive {
739      if let Some(old) = st.sock.take() {
740        old.finish();
741      }
742      let s = Sock::open(&self.path, &self.hub, self.timeout)?;
743      *lock(&self.live) = Some(s.clone());
744      let shaken = if self.closed.load(Ordering::SeqCst) {
745        Err(aborted("client closed"))
746      } else {
747        s.handshake(&self.name, self.max_inflight)
748      };
749      if let Err(e) = shaken {
750        s.finish();
751        return Err(e);
752      }
753      self.limit.store(s.limit(), Ordering::SeqCst);
754      st.sock = Some(s);
755      st.epoch += 1;
756      self.gate.bump();
757    }
758    Ok((st.sock.clone().expect("connected above"), st.epoch))
759  }
760
761  /// Refuses new calls and cuts the connection, which ends the calls in flight.
762  fn close_start(&self) {
763    self.closed.store(true, Ordering::SeqCst);
764    if let Some(s) = lock(&self.live).as_ref() {
765      s.kill();
766    }
767    self.gate.bump();
768  }
769
770  /// Stops the connection's threads.
771  fn close_finish(&self) {
772    let s = lock(&self.state).sock.take();
773    if let Some(s) = s {
774      s.finish();
775    }
776  }
777}
778
779pub(crate) struct Inner {
780  slots: Vec<Arc<Slot>>,
781  gate: Arc<Gate>,
782  next: AtomicUsize,
783  pub(crate) hub: Arc<Hub>,
784  dispatcher: Mutex<Option<JoinHandle<()>>>,
785}
786
787impl Inner {
788  /// Ends every connection, reader, watch and the dispatcher. Safe to call twice.
789  fn shutdown(&self) {
790    for s in &self.slots {
791      s.close_start();
792    }
793    for s in &self.slots {
794      s.close_finish();
795    }
796    self.hub.shutdown();
797    let d = lock(&self.dispatcher).take();
798    if let Some(h) = d {
799      join_other(h);
800    }
801    self.hub.clear_listeners();
802  }
803}
804
805impl Drop for Inner {
806  fn drop(&mut self) {
807    self.shutdown();
808  }
809}
810
811/// Client for one mount. Cheap to clone, clones share the pool, the listeners and the event
812/// dispatcher. The last clone to drop closes everything. `close` does it at once for all clones.
813#[derive(Clone)]
814pub struct Client {
815  pub(crate) inner: Arc<Inner>,
816}
817
818impl Client {
819  /// Connects with default options (4 connections).
820  pub fn connect(path: impl AsRef<Path>) -> Result<Client> {
821    Client::connect_with(path, Options::default())
822  }
823
824  /// Connects with the given options. The first connection and handshake happen now,
825  /// so a bad socket or version mismatch fails here.
826  pub fn connect_with(path: impl AsRef<Path>, opts: Options) -> Result<Client> {
827    let n = opts.pool_size.max(1);
828    let hub = Arc::new(Hub::new(opts.logger.clone()));
829    let gate = Arc::new(Gate::default());
830    let slots: Vec<_> = (0..n)
831      .map(|_| {
832        Arc::new(Slot {
833          path: path.as_ref().to_path_buf(),
834          name: opts.client_name.clone(),
835          timeout: opts.call_timeout,
836          max_inflight: opts.max_inflight.clamp(1, MAX_INFLIGHT_CEILING),
837          hub: hub.clone(),
838          gate: gate.clone(),
839          outstanding: AtomicUsize::new(0),
840          limit: AtomicUsize::new(1),
841          closed: AtomicBool::new(false),
842          live: Mutex::new(None),
843          state: Mutex::new(SlotState { sock: None, epoch: 0 }),
844        })
845      })
846      .collect();
847    let (h, guard) = (hub.clone(), hub.thread_guard());
848    let dispatcher = std::thread::Builder::new()
849      .name("mountos-dispatch".into())
850      .spawn(move || {
851        let _guard = guard;
852        h.dispatch_loop()
853      })?;
854    let inner = Inner {
855      slots,
856      gate,
857      next: AtomicUsize::new(0),
858      hub,
859      dispatcher: Mutex::new(Some(dispatcher)),
860    };
861    // On failure, dropping `inner` stops the dispatcher and any reader.
862    inner.slots[0].run(None, |_| Ok(()))?;
863    Ok(Client { inner: Arc::new(inner) })
864  }
865
866  /// Ends all connections, watches and background threads. Later calls fail with an I/O error
867  /// of kind `ConnectionAborted`. Dropping the last clone does the same.
868  pub fn close(&self) {
869    self.inner.shutdown();
870  }
871
872  pub(crate) fn pool_size(&self) -> usize {
873    self.inner.slots.len()
874  }
875
876  /// Runs `f` on the connection with the fewest requests outstanding that has room. The scan
877  /// starts at a rotating position so equal choices spread out. When all are full it waits for whichever frees first. Returns the slot
878  /// and epoch the call ran on, for callers that bind a handle to it.
879  pub(crate) fn run_any<T>(&self, f: impl FnOnce(&Sock) -> Result<T>) -> Result<(T, &Arc<Slot>, u64)> {
880    let inner = &*self.inner;
881    let n = inner.slots.len();
882    let mut waiter = None;
883    loop {
884      let seen = inner.gate.generation();
885      let start = inner.next.fetch_add(1, Ordering::Relaxed) % n;
886      let mut best: Option<(&Arc<Slot>, usize)> = None;
887      for i in 0..n {
888        let slot = &inner.slots[(start + i) % n];
889        let out = slot.outstanding.load(Ordering::SeqCst);
890        if out >= slot.limit.load(Ordering::SeqCst) {
891          continue;
892        }
893        if best.as_ref().is_none_or(|(_, k)| out < *k) {
894          best = Some((slot, out));
895        }
896      }
897      if let Some((slot, _)) = best {
898        // Losing the race for the place means another caller took it, so scan again.
899        if let Some(permit) = slot.try_reserve() {
900          drop(waiter);
901          let (v, epoch) = slot.exec(permit, None, f)?;
902          return Ok((v, slot, epoch));
903        }
904        continue;
905      }
906      if waiter.is_none() {
907        // Register, then scan once more: a place may have freed in between.
908        waiter = Some(inner.gate.wait_for_free());
909        continue;
910      }
911      inner.gate.wait_change(seen);
912    }
913  }
914
915  pub(crate) fn unary<R: Message + Default>(&self, m: u16, req: &impl Message) -> Result<R> {
916    Ok(self.run_any(|c| c.call_msg::<R>(m, req, &[]))?.0 .0)
917  }
918
919  /// Opens a file. `flags` combine `open_flag` values. The file stays bound to the connection that opened it.
920  pub fn open(&self, path: &str, flags: u32, mode: u32) -> Result<File> {
921    let ((r, _), slot, epoch) = self.run_any(|c| {
922      c.call_msg::<OpenResponse>(
923        method::OPEN,
924        &OpenRequest {
925          path: path.into(),
926          flags,
927          mode,
928        },
929        &[],
930      )
931    })?;
932    Ok(File::new(slot.clone(), r.handle, epoch))
933  }
934
935  /// Sets times in nanoseconds since the epoch. `None` leaves that time unchanged.
936  pub fn utimens(&self, path: &str, atime_ns: Option<i64>, mtime_ns: Option<i64>) -> Result<()> {
937    self
938      .unary::<Empty>(
939        method::UTIMENS,
940        &UtimensRequest {
941          path: path.into(),
942          atime_ns: atime_ns.unwrap_or(0),
943          mtime_ns: mtime_ns.unwrap_or(0),
944          set_atime: atime_ns.is_some(),
945          set_mtime: mtime_ns.is_some(),
946        },
947      )
948      .map(drop)
949  }
950
951  /// Opens a directory for paged listing. The directory stays bound to the connection that opened it.
952  pub fn opendir(&self, path: &str) -> Result<Dir> {
953    let ((r, _), slot, epoch) =
954      self.run_any(|c| c.call_msg::<OpendirResponse>(method::OPENDIR, &OpendirRequest { path: path.into() }, &[]))?;
955    Ok(Dir::new(slot.clone(), r.handle, epoch))
956  }
957
958  /// Lists up to `max_entries` entries with their attributes. Pass an empty `cursor` to start,
959  /// then the returned cursor to continue. An empty returned cursor means the listing is complete.
960  pub fn ls(&self, path: &str, max_entries: u32, cursor: &str) -> Result<(Vec<DirEntry>, String)> {
961    let r: LsResponse = self.unary(
962      method::LS,
963      &LsRequest {
964        path: path.into(),
965        max_entries,
966        cursor: cursor.into(),
967      },
968    )?;
969    Ok((r.entries, r.next_cursor))
970  }
971}