1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
use std::collections::VecDeque;
use std::env;
use std::path::{Path, PathBuf};

use super::{constraint::Constraint, Runtime};

pub type Runtimes<'a> = Box<dyn Iterator<Item = Runtime> + 'a>;

/// A strategy for finding PostgreSQL runtimes.
///
/// There are a few questions we want to answer:
///
/// 1. What runtimes are available?
/// 2. Which of those runtimes is best suited to running a given cluster?
/// 3. When there are no constraints, what runtime should we use?
///
/// This trait models those questions, and provides default implementations for
/// #2 and #3.
///
/// However, a good place to start is the [`Default`] implementation of
/// [`Strategy`]. It might do what you need.
pub trait StrategyLike: std::fmt::Debug + std::panic::RefUnwindSafe + 'static {
    /// Find all runtimes that this strategy knows about.
    fn runtimes(&self) -> Runtimes;

    /// Determine the most appropriate runtime known to this strategy for the
    /// given constraint.
    ///
    /// The default implementation narrows the list of runtimes to those that
    /// match the given constraint, then chooses the one with the highest
    /// version number. It might return [`None`].
    fn select(&self, constraint: &Constraint) -> Option<Runtime> {
        self.runtimes()
            .filter(|runtime| constraint.matches(runtime))
            .max_by(|ra, rb| ra.version.cmp(&rb.version))
    }

    /// The runtime to use when there are no constraints, e.g. when creating a
    /// new cluster.
    ///
    /// The default implementation selects the runtime with the highest version
    /// number.
    fn fallback(&self) -> Option<Runtime> {
        self.runtimes().max_by(|ra, rb| ra.version.cmp(&rb.version))
    }
}

/// Find runtimes on a given path.
///
/// Parses input according to platform conventions for the `PATH` environment
/// variable. See [`env::split_paths`] for details.
#[derive(Clone, Debug)]
pub struct RuntimesOnPath(PathBuf);

impl StrategyLike for RuntimesOnPath {
    fn runtimes(&self) -> Runtimes {
        Box::new(
            env::split_paths(&self.0)
                .filter(|bindir| bindir.join("pg_ctl").exists())
                // Throw away runtimes that we can't determine the version for.
                .filter_map(|bindir| Runtime::new(bindir).ok()),
        )
    }
}

/// Find runtimes on `PATH` (from the environment).
#[derive(Clone, Debug)]
pub struct RuntimesOnPathEnv;

impl StrategyLike for RuntimesOnPathEnv {
    fn runtimes(&self) -> Runtimes {
        Box::new(
            env::var_os("PATH")
                .map(|path| {
                    env::split_paths(&path)
                        .filter(|bindir| bindir.join("pg_ctl").exists())
                        // Throw away runtimes that we can't determine the version for.
                        .filter_map(|bindir| Runtime::new(bindir).ok())
                        .collect::<Vec<_>>()
                })
                .unwrap_or_default()
                .into_iter(),
        )
    }
}

/// Find runtimes using platform-specific knowledge.
///
/// For example:
/// - on Debian and Ubuntu, check subdirectories of `/usr/lib/postgresql`.
/// - on macOS, check Homebrew.
///
/// More platform-specific knowledge may be added to this strategy in the
/// future.
#[derive(Clone, Debug)]
pub struct RuntimesOnPlatform;

impl RuntimesOnPlatform {
    /// Find runtimes using platform-specific knowledge (Linux).
    ///
    /// For example: on Debian and Ubuntu, check `/usr/lib/postgresql`.
    #[cfg(any(doc, target_os = "linux"))]
    pub fn find() -> Vec<PathBuf> {
        glob::glob("/usr/lib/postgresql/*/bin/pg_ctl")
            .ok()
            .map(|entries| {
                entries
                    .filter_map(Result::ok)
                    .filter(|path| path.is_file())
                    .filter_map(|path| path.parent().map(Path::to_owned))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Find runtimes using platform-specific knowledge (macOS).
    ///
    /// For example: check Homebrew.
    #[cfg(any(doc, target_os = "macos"))]
    pub fn find() -> Vec<PathBuf> {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        std::process::Command::new("brew")
            .arg("--prefix")
            .output()
            .ok()
            .and_then(|output| {
                if output.status.success() {
                    Some(OsString::from_vec(output.stdout))
                } else {
                    None
                }
            })
            .and_then(|brew_prefix| {
                glob::glob(&format!(
                    "{}/Cellar/postgresql@*/*/bin/pg_ctl",
                    brew_prefix.to_string_lossy().trim_end()
                ))
                .ok()
            })
            .map(|entries| {
                entries
                    .filter_map(Result::ok)
                    .filter(|path| path.is_file())
                    .filter_map(|path| path.parent().map(Path::to_owned))
                    .collect()
            })
            .unwrap_or_default()
    }
}

impl StrategyLike for RuntimesOnPlatform {
    fn runtimes(&self) -> Runtimes {
        Box::new(
            Self::find()
                .into_iter()
                // Throw away runtimes that we can't determine the version for.
                .filter_map(|bindir| Runtime::new(bindir).ok()),
        )
    }
}

/// Compose strategies for finding PostgreSQL runtimes.
#[derive(Debug)]
pub enum Strategy {
    /// Each strategy is consulted in turn.
    Chain(VecDeque<Strategy>),
    /// Delegate to another strategy; needed when implementing [`StrategyLike`].
    Delegated(Box<dyn StrategyLike + Send + Sync>),
    /// A single runtime; it always picks itself.
    Single(Runtime),
}

impl Strategy {
    /// Push the given strategy to the front of the chain.
    ///
    /// If this isn't already, it is converted into a [`Strategy::Chain`].
    #[must_use]
    pub fn push_front<S: Into<Strategy>>(mut self, strategy: S) -> Self {
        match self {
            Self::Chain(ref mut chain) => {
                chain.push_front(strategy.into());
                self
            }
            Self::Delegated(_) | Self::Single(_) => {
                let mut chain: VecDeque<Strategy> = VecDeque::new();
                chain.push_front(strategy.into());
                chain.push_back(self);
                Self::Chain(chain)
            }
        }
    }

    /// Push the given strategy to the back of the chain.
    ///
    /// If this isn't already, it is converted into a [`Strategy::Chain`].
    #[must_use]
    pub fn push_back<S: Into<Strategy>>(mut self, strategy: S) -> Self {
        match self {
            Self::Chain(ref mut chain) => {
                chain.push_back(strategy.into());
                self
            }
            Self::Delegated(_) | Self::Single(_) => {
                let mut chain: VecDeque<Strategy> = VecDeque::new();
                chain.push_front(self);
                chain.push_back(strategy.into());
                Self::Chain(chain)
            }
        }
    }
}

impl Default for Strategy {
    /// Select runtimes from on `PATH` followed by platform-specific runtimes.
    fn default() -> Self {
        Self::Chain(VecDeque::new())
            .push_front(RuntimesOnPathEnv)
            .push_back(RuntimesOnPlatform)
    }
}

impl StrategyLike for Strategy {
    /// - For a [`Strategy::Chain`], yields runtimes known to all strategies, in
    ///   the same order as each strategy returns them.
    /// - For a [`Strategy::Delegated`], calls through to the wrapped strategy.
    /// - For a [`Strategy::Single`], yields the runtime it's holding.
    ///
    /// **Note** that for the first two, runtimes are deduplicated by version
    /// number, i.e. if a runtime with the same version number is yielded by
    /// multiple strategies, or is yielded multiple times by a single strategy,
    /// it will only be returned the first time it is seen.
    fn runtimes(&self) -> Runtimes {
        match self {
            Self::Chain(chain) => {
                let mut seen = std::collections::HashSet::new();
                Box::new(
                    chain
                        .iter()
                        .flat_map(|strategy| strategy.runtimes())
                        .filter(move |runtime| seen.insert(runtime.version)),
                )
            }
            Self::Delegated(strategy) => {
                let mut seen = std::collections::HashSet::new();
                Box::new(
                    strategy
                        .runtimes()
                        .filter(move |runtime| seen.insert(runtime.version)),
                )
            }
            Self::Single(runtime) => Box::new(std::iter::once(runtime.clone())),
        }
    }

    /// - For a [`Strategy::Chain`], asks each strategy in turn to select a
    ///   runtime. The first non-[`None`] answer is selected.
    /// - For a [`Strategy::Delegated`], calls through to the wrapped strategy.
    /// - For a [`Strategy::Single`], returns the runtime if it's compatible.
    fn select(&self, constraint: &Constraint) -> Option<Runtime> {
        match self {
            Self::Chain(c) => c.iter().find_map(|strategy| strategy.select(constraint)),
            Self::Delegated(strategy) => strategy.select(constraint),
            Self::Single(runtime) if constraint.matches(runtime) => Some(runtime.clone()),
            Self::Single(_) => None,
        }
    }

    /// - For a [`Strategy::Chain`], asks each strategy in turn for a fallback
    ///   runtime. The first non-[`None`] answer is selected.
    /// - For a [`Strategy::Delegated`], calls through to the wrapped strategy.
    /// - For a [`Strategy::Single`], returns the runtime it's holding.
    fn fallback(&self) -> Option<Runtime> {
        match self {
            Self::Chain(chain) => chain.iter().find_map(Strategy::fallback),
            Self::Delegated(strategy) => strategy.fallback(),
            Self::Single(runtime) => Some(runtime.clone()),
        }
    }
}

impl From<RuntimesOnPath> for Strategy {
    /// Converts the given strategy into a [`Strategy::Delegated`].
    fn from(strategy: RuntimesOnPath) -> Self {
        Self::Delegated(Box::new(strategy))
    }
}

impl From<RuntimesOnPathEnv> for Strategy {
    /// Converts the given strategy into a [`Strategy::Delegated`].
    fn from(strategy: RuntimesOnPathEnv) -> Self {
        Self::Delegated(Box::new(strategy))
    }
}

impl From<RuntimesOnPlatform> for Strategy {
    /// Converts the given strategy into a [`Strategy::Delegated`].
    fn from(strategy: RuntimesOnPlatform) -> Self {
        Self::Delegated(Box::new(strategy))
    }
}

impl From<Runtime> for Strategy {
    /// Converts the given runtime into a [`Strategy::Single`].
    fn from(runtime: Runtime) -> Self {
        Self::Single(runtime)
    }
}

#[cfg(test)]
mod tests {
    use std::env;

    use super::{RuntimesOnPath, RuntimesOnPathEnv, RuntimesOnPlatform, Strategy, StrategyLike};

    /// This will fail if there are no PostgreSQL runtimes installed.
    #[test]
    fn runtime_find_custom_path() {
        let path = env::var_os("PATH").expect("PATH not set");
        let strategy = RuntimesOnPath(path.into());
        let runtimes = strategy.runtimes();
        assert_ne!(0, runtimes.count());
    }

    /// This will fail if there are no PostgreSQL runtimes installed.
    #[test]
    fn runtime_find_env_path() {
        let runtimes = RuntimesOnPathEnv.runtimes();
        assert_ne!(0, runtimes.count());
    }

    /// This will fail if there are no PostgreSQL runtimes installed.
    #[test]
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    fn runtime_find_on_platform() {
        let runtimes = RuntimesOnPlatform.runtimes();
        assert_ne!(0, runtimes.count());
    }

    /// This will fail if there are no PostgreSQL runtimes installed. It's also
    /// somewhat fragile because it relies upon knowing the implementation of
    /// the strategies of which the default [`StrategySet`] is composed.
    #[test]
    fn runtime_strategy_set_default() {
        let strategy = Strategy::default();
        // There is at least one runtime available.
        let runtimes = strategy.runtimes();
        assert_ne!(0, runtimes.count());
        // There is always a fallback.
        assert!(strategy.fallback().is_some());
    }
}