isothrum_client/pool.rs
1//! One connection per home, kept for every call of a process, and made again once when it breaks:
2//! a service killed or restarted since the connection was made answers a broken pipe, not a
3//! refusal, and the call is worth one more try on a new connection (the service started again
4//! when none runs). Only a second failure is the caller's. An operation whose sending went
5//! unanswered isn't sent again but followed again ([`Pool::follow`]): the service may have
6//! queued it.
7
8use std::collections::HashMap;
9use std::future::Future;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12
13use isothrum_runner::BoxFuture;
14use tokio::sync::Mutex;
15
16use crate::proto::Command;
17use crate::{Client, ClientError, Followed};
18
19/// Makes a connection to a home's service.
20type Connect<C> = Box<dyn Fn(PathBuf) -> BoxFuture<'static, Result<C, ClientError>> + Send + Sync>;
21
22/// The connections of a process to its homes' services, one per home ([`Pool::new`]: real
23/// [`Client`]s; a test hands its own connection type to [`Pool::with`]).
24pub struct Pool<C = Client> {
25 clients: Mutex<HashMap<PathBuf, Arc<C>>>,
26 connect: Connect<C>,
27}
28
29impl<C> std::fmt::Debug for Pool<C> {
30 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 f.debug_struct("Pool").finish_non_exhaustive()
32 }
33}
34
35impl Pool<Client> {
36 /// Connections made with [`Client::connect_exact`]: the service of this release, started
37 /// (`binary`, else the `isothrum` beside this program, else the one on `PATH`) when none
38 /// runs.
39 #[must_use]
40 pub fn new(binary: Option<PathBuf>) -> Pool<Client> {
41 Pool::with(move |home| {
42 let binary = binary.clone();
43 Box::pin(async move { Client::connect_exact(&home, binary.as_deref()).await })
44 })
45 }
46}
47
48impl<C: Send + Sync + 'static> Pool<C> {
49 /// Connections made by `connect`, given the home.
50 pub fn with(connect: impl Fn(PathBuf) -> BoxFuture<'static, Result<C, ClientError>> + Send + Sync + 'static) -> Pool<C> {
51 Pool {
52 clients: Mutex::new(HashMap::new()),
53 connect: Box::new(connect),
54 }
55 }
56
57 /// `home`'s connection: the one kept, else a new one, kept.
58 ///
59 /// # Errors
60 ///
61 /// The connection couldn't be made (no service answers and none could be started).
62 pub async fn client(&self, home: &Path) -> Result<Arc<C>, ClientError> {
63 let mut clients = self.clients.lock().await;
64 if let Some(client) = clients.get(home) {
65 return Ok(Arc::clone(client));
66 }
67 let client = Arc::new((self.connect)(home.to_path_buf()).await?);
68 clients.insert(home.to_path_buf(), Arc::clone(&client));
69 Ok(client)
70 }
71
72 /// Forgets `home`'s connection: the next call makes a new one.
73 pub async fn forget(&self, home: &Path) {
74 self.clients.lock().await.remove(home);
75 }
76
77 /// Forgets every connection kept but those of the homes `keep` keeps.
78 pub async fn retain(&self, keep: impl Fn(&Path) -> bool) {
79 self.clients.lock().await.retain(|home, _| keep(home));
80 }
81
82 /// `ask` of `home`'s service. A connection found broken ([`ClientError::is_broken`]) is
83 /// forgotten and made again, and `ask` tried once more on the new one; a second broken one is
84 /// forgotten too, for the next call. For a question; an operation is [`Pool::follow`]ed.
85 ///
86 /// # Errors
87 ///
88 /// No connection could be made; the service refused or failed; the connection broke twice.
89 pub async fn call<T, F>(&self, home: &Path, ask: impl Fn(Arc<C>) -> F) -> Result<T, ClientError>
90 where
91 F: Future<Output = Result<T, ClientError>>,
92 {
93 self.call_then(home, &ask, |client, _| ask(client)).await
94 }
95
96 /// `ask` of `home`'s service; a connection found broken is forgotten and made again, and
97 /// `again` asked on the new one, told why the first broke; a second broken one is forgotten
98 /// too.
99 async fn call_then<T, F, G>(&self, home: &Path, ask: impl FnOnce(Arc<C>) -> F, again: impl FnOnce(Arc<C>, ClientError) -> G) -> Result<T, ClientError>
100 where
101 F: Future<Output = Result<T, ClientError>>,
102 G: Future<Output = Result<T, ClientError>>,
103 {
104 match ask(self.client(home).await?).await {
105 Err(e) if e.is_broken() => {
106 tracing::info!(home = %home.display(), error = %e, "the service's connection broke: connecting again");
107 self.forget(home).await;
108 let again = again(self.client(home).await?, e).await;
109 if again.as_ref().is_err_and(ClientError::is_broken) {
110 self.forget(home).await;
111 }
112 again
113 }
114 done => done,
115 }
116 }
117}
118
119impl Pool<Client> {
120 /// Queues the operation `command` with `home`'s service and follows it
121 /// ([`Client::follow`]), on a connection made again once when found broken, as
122 /// [`Pool::call`] does. A sending the connection ended before the service answered
123 /// ([`ClientError::Unanswered`]) may have been queued: it is followed again
124 /// ([`Client::follow_again`]), not sent again, which would queue a second one behind it, or
125 /// be refused as the run's operation already queued.
126 ///
127 /// # Errors
128 ///
129 /// As [`Pool::call`] and [`Client::follow`].
130 pub async fn follow(&self, home: &Path, command: Command) -> Result<Followed, ClientError> {
131 let first = command.clone();
132 self.call_then(
133 home,
134 |client| async move { client.follow(first).await },
135 |client, why| async move {
136 match why {
137 ClientError::Unanswered => client.follow_again(command).await,
138 _ => client.follow(command).await,
139 }
140 },
141 )
142 .await
143 }
144}
145
146#[cfg(test)]
147mod tests;