Skip to main content

pgdo/runtime/
strategy.rs

1use std::collections::VecDeque;
2use std::env;
3use std::path::{Path, PathBuf};
4
5use super::{constraint::Constraint, Runtime};
6
7pub type Runtimes<'a> = Box<dyn Iterator<Item = Runtime> + 'a>;
8
9/// A strategy for finding PostgreSQL runtimes.
10///
11/// There are a few questions we want to answer:
12///
13/// 1. What runtimes are available?
14/// 2. Which of those runtimes is best suited to running a given cluster?
15/// 3. When there are no constraints, what runtime should we use?
16///
17/// This trait models those questions, and provides default implementations for
18/// #2 and #3.
19///
20/// However, a good place to start is the [`Default`] implementation of
21/// [`Strategy`]. It might do what you need.
22pub trait StrategyLike: std::fmt::Debug + 'static {
23    /// Find all runtimes that this strategy knows about.
24    fn runtimes(&self) -> Runtimes<'_>;
25
26    /// Determine the most appropriate runtime known to this strategy for the
27    /// given constraint.
28    ///
29    /// The default implementation narrows the list of runtimes to those that
30    /// match the given constraint, then chooses the one with the highest
31    /// version number. It might return [`None`].
32    fn select(&self, constraint: &Constraint) -> Option<Runtime> {
33        self.runtimes()
34            .filter(|runtime| constraint.matches(runtime))
35            .max_by(|ra, rb| ra.version.cmp(&rb.version))
36    }
37
38    /// The runtime to use when there are no constraints, e.g. when creating a
39    /// new cluster.
40    ///
41    /// The default implementation selects the runtime with the highest version
42    /// number.
43    fn fallback(&self) -> Option<Runtime> {
44        self.runtimes().max_by(|ra, rb| ra.version.cmp(&rb.version))
45    }
46}
47
48/// Find runtimes on a given path.
49///
50/// Parses input according to platform conventions for the `PATH` environment
51/// variable. See [`env::split_paths`] for details.
52#[derive(Clone, Debug)]
53pub struct RuntimesOnPath(PathBuf);
54
55impl StrategyLike for RuntimesOnPath {
56    fn runtimes(&self) -> Runtimes<'_> {
57        Box::new(
58            env::split_paths(&self.0)
59                .filter(|bindir| bindir.join("pg_ctl").exists())
60                // Throw away runtimes that we can't determine the version for,
61                // and those that pgdo does not support.
62                .filter_map(|bindir| Runtime::new(bindir).ok())
63                .filter(Runtime::is_supported),
64        )
65    }
66}
67
68/// Find runtimes on `PATH` (from the environment).
69#[derive(Clone, Debug)]
70pub struct RuntimesOnPathEnv;
71
72impl StrategyLike for RuntimesOnPathEnv {
73    fn runtimes(&self) -> Runtimes<'_> {
74        Box::new(
75            env::var_os("PATH")
76                .map_or_default(|path| {
77                    env::split_paths(&path)
78                        .filter(|bindir| bindir.join("pg_ctl").exists())
79                        // Throw away runtimes that we can't determine the
80                        // version for, and those that pgdo does not support.
81                        .filter_map(|bindir| Runtime::new(bindir).ok())
82                        .filter(Runtime::is_supported)
83                        .collect::<Vec<_>>()
84                })
85                .into_iter(),
86        )
87    }
88}
89
90/// Find runtimes using platform-specific knowledge.
91///
92/// For example:
93/// - on Debian and Ubuntu, check subdirectories of `/usr/lib/postgresql`.
94/// - on macOS, check Homebrew.
95///
96/// More platform-specific knowledge may be added to this strategy in the
97/// future.
98#[derive(Clone, Debug)]
99pub struct RuntimesOnPlatform;
100
101impl RuntimesOnPlatform {
102    /// Find runtimes using platform-specific knowledge (Linux).
103    ///
104    /// For example: on Debian and Ubuntu, check `/usr/lib/postgresql`.
105    #[cfg(any(doc, target_os = "linux"))]
106    pub fn find() -> Vec<PathBuf> {
107        glob::glob("/usr/lib/postgresql/*/bin/pg_ctl")
108            .ok()
109            .map_or_default(|entries| {
110                entries
111                    .filter_map(Result::ok)
112                    .filter(|path| path.is_file())
113                    .filter_map(|path| path.parent().map(Path::to_owned))
114                    .collect()
115            })
116    }
117
118    /// Find runtimes using platform-specific knowledge (macOS).
119    ///
120    /// For example: check Homebrew.
121    #[cfg(any(doc, target_os = "macos"))]
122    pub fn find() -> Vec<PathBuf> {
123        use std::ffi::OsString;
124        use std::os::unix::ffi::OsStringExt;
125
126        std::process::Command::new("brew")
127            .arg("--prefix")
128            .output()
129            .ok()
130            .and_then(|output| {
131                if output.status.success() {
132                    Some(OsString::from_vec(output.stdout))
133                } else {
134                    None
135                }
136            })
137            .and_then(|brew_prefix| {
138                glob::glob(&format!(
139                    "{}/Cellar/postgresql@*/*/bin/pg_ctl",
140                    brew_prefix.to_string_lossy().trim_end()
141                ))
142                .ok()
143            })
144            .map_or_default(|entries| {
145                entries
146                    .filter_map(Result::ok)
147                    .filter(|path| path.is_file())
148                    .filter_map(|path| path.parent().map(Path::to_owned))
149                    .collect()
150            })
151    }
152}
153
154impl StrategyLike for RuntimesOnPlatform {
155    fn runtimes(&self) -> Runtimes<'_> {
156        Box::new(
157            Self::find()
158                .into_iter()
159                // Throw away runtimes that we can't determine the version for,
160                // and those that pgdo does not support.
161                .filter_map(|bindir| Runtime::new(bindir).ok())
162                .filter(Runtime::is_supported),
163        )
164    }
165}
166
167/// Compose strategies for finding PostgreSQL runtimes.
168#[derive(Debug)]
169pub enum Strategy {
170    /// Each strategy is consulted in turn.
171    Chain(VecDeque<Strategy>),
172    /// Delegate to another strategy; needed when implementing [`StrategyLike`].
173    Delegated(Box<dyn StrategyLike + Send + Sync>),
174    /// A single runtime; it always picks itself.
175    Single(Runtime),
176}
177
178impl Strategy {
179    /// Push the given strategy to the front of the chain.
180    ///
181    /// If this isn't already, it is converted into a [`Strategy::Chain`].
182    #[must_use]
183    pub fn push_front<S: Into<Strategy>>(mut self, strategy: S) -> Self {
184        match self {
185            Self::Chain(ref mut chain) => {
186                chain.push_front(strategy.into());
187                self
188            }
189            Self::Delegated(_) | Self::Single(_) => {
190                let mut chain: VecDeque<Strategy> = VecDeque::new();
191                chain.push_front(strategy.into());
192                chain.push_back(self);
193                Self::Chain(chain)
194            }
195        }
196    }
197
198    /// Push the given strategy to the back of the chain.
199    ///
200    /// If this isn't already, it is converted into a [`Strategy::Chain`].
201    #[must_use]
202    pub fn push_back<S: Into<Strategy>>(mut self, strategy: S) -> Self {
203        match self {
204            Self::Chain(ref mut chain) => {
205                chain.push_back(strategy.into());
206                self
207            }
208            Self::Delegated(_) | Self::Single(_) => {
209                let mut chain: VecDeque<Strategy> = VecDeque::new();
210                chain.push_front(self);
211                chain.push_back(strategy.into());
212                Self::Chain(chain)
213            }
214        }
215    }
216}
217
218impl Default for Strategy {
219    /// Select runtimes from on `PATH` followed by platform-specific runtimes.
220    fn default() -> Self {
221        Self::Chain(VecDeque::new())
222            .push_front(RuntimesOnPathEnv)
223            .push_back(RuntimesOnPlatform)
224    }
225}
226
227impl StrategyLike for Strategy {
228    /// - For a [`Strategy::Chain`], yields runtimes known to all strategies, in
229    ///   the same order as each strategy returns them.
230    /// - For a [`Strategy::Delegated`], calls through to the wrapped strategy.
231    /// - For a [`Strategy::Single`], yields the runtime it's holding.
232    ///
233    /// **Note** that for the first two, runtimes are deduplicated by version
234    /// number, i.e. if a runtime with the same version number is yielded by
235    /// multiple strategies, or is yielded multiple times by a single strategy,
236    /// it will only be returned the first time it is seen.
237    fn runtimes(&self) -> Runtimes<'_> {
238        match self {
239            Self::Chain(chain) => {
240                let mut seen = std::collections::HashSet::new();
241                Box::new(
242                    chain
243                        .iter()
244                        .flat_map(|strategy| strategy.runtimes())
245                        .filter(move |runtime| seen.insert(runtime.version)),
246                )
247            }
248            Self::Delegated(strategy) => {
249                let mut seen = std::collections::HashSet::new();
250                Box::new(
251                    strategy
252                        .runtimes()
253                        .filter(move |runtime| seen.insert(runtime.version)),
254                )
255            }
256            Self::Single(runtime) => Box::new(std::iter::once(runtime.clone())),
257        }
258    }
259
260    /// - For a [`Strategy::Chain`], asks each strategy in turn to select a
261    ///   runtime. The first non-[`None`] answer is selected.
262    /// - For a [`Strategy::Delegated`], calls through to the wrapped strategy.
263    /// - For a [`Strategy::Single`], returns the runtime if it's compatible.
264    fn select(&self, constraint: &Constraint) -> Option<Runtime> {
265        match self {
266            Self::Chain(c) => c.iter().find_map(|strategy| strategy.select(constraint)),
267            Self::Delegated(strategy) => strategy.select(constraint),
268            Self::Single(runtime) if constraint.matches(runtime) => Some(runtime.clone()),
269            Self::Single(_) => None,
270        }
271    }
272
273    /// - For a [`Strategy::Chain`], asks each strategy in turn for a fallback
274    ///   runtime. The first non-[`None`] answer is selected.
275    /// - For a [`Strategy::Delegated`], calls through to the wrapped strategy.
276    /// - For a [`Strategy::Single`], returns the runtime it's holding.
277    fn fallback(&self) -> Option<Runtime> {
278        match self {
279            Self::Chain(chain) => chain.iter().find_map(Strategy::fallback),
280            Self::Delegated(strategy) => strategy.fallback(),
281            Self::Single(runtime) => Some(runtime.clone()),
282        }
283    }
284}
285
286impl From<RuntimesOnPath> for Strategy {
287    /// Converts the given strategy into a [`Strategy::Delegated`].
288    fn from(strategy: RuntimesOnPath) -> Self {
289        Self::Delegated(Box::new(strategy))
290    }
291}
292
293impl From<RuntimesOnPathEnv> for Strategy {
294    /// Converts the given strategy into a [`Strategy::Delegated`].
295    fn from(strategy: RuntimesOnPathEnv) -> Self {
296        Self::Delegated(Box::new(strategy))
297    }
298}
299
300impl From<RuntimesOnPlatform> for Strategy {
301    /// Converts the given strategy into a [`Strategy::Delegated`].
302    fn from(strategy: RuntimesOnPlatform) -> Self {
303        Self::Delegated(Box::new(strategy))
304    }
305}
306
307impl From<Runtime> for Strategy {
308    /// Converts the given runtime into a [`Strategy::Single`].
309    fn from(runtime: Runtime) -> Self {
310        Self::Single(runtime)
311    }
312}
313
314#[cfg(test)]
315mod tests {
316    use std::env;
317
318    use super::{RuntimesOnPath, RuntimesOnPathEnv, RuntimesOnPlatform, Strategy, StrategyLike};
319
320    /// This will fail if there are no PostgreSQL runtimes installed.
321    #[test]
322    fn runtime_find_custom_path() {
323        let path = env::var_os("PATH").expect("PATH not set");
324        let strategy = RuntimesOnPath(path.into());
325        let runtimes = strategy.runtimes();
326        assert_ne!(0, runtimes.count());
327    }
328
329    /// This will fail if there are no PostgreSQL runtimes installed.
330    #[test]
331    fn runtime_find_env_path() {
332        let runtimes = RuntimesOnPathEnv.runtimes();
333        assert_ne!(0, runtimes.count());
334    }
335
336    /// This will fail if there are no PostgreSQL runtimes installed.
337    #[test]
338    #[cfg(any(target_os = "linux", target_os = "macos"))]
339    fn runtime_find_on_platform() {
340        let runtimes = RuntimesOnPlatform.runtimes();
341        assert_ne!(0, runtimes.count());
342    }
343
344    /// This will fail if there are no PostgreSQL runtimes installed. It's also
345    /// somewhat fragile because it relies upon knowing the implementation of
346    /// the strategies of which the default [`StrategySet`] is composed.
347    #[test]
348    fn runtime_strategy_set_default() {
349        let strategy = Strategy::default();
350        // There is at least one runtime available.
351        let runtimes = strategy.runtimes();
352        assert_ne!(0, runtimes.count());
353        // There is always a fallback.
354        assert!(strategy.fallback().is_some());
355    }
356}