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(|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 .unwrap_or_default()
86 .into_iter(),
87 )
88 }
89}
90
91/// Find runtimes using platform-specific knowledge.
92///
93/// For example:
94/// - on Debian and Ubuntu, check subdirectories of `/usr/lib/postgresql`.
95/// - on macOS, check Homebrew.
96///
97/// More platform-specific knowledge may be added to this strategy in the
98/// future.
99#[derive(Clone, Debug)]
100pub struct RuntimesOnPlatform;
101
102impl RuntimesOnPlatform {
103 /// Find runtimes using platform-specific knowledge (Linux).
104 ///
105 /// For example: on Debian and Ubuntu, check `/usr/lib/postgresql`.
106 #[cfg(any(doc, target_os = "linux"))]
107 pub fn find() -> Vec<PathBuf> {
108 glob::glob("/usr/lib/postgresql/*/bin/pg_ctl")
109 .ok()
110 .map(|entries| {
111 entries
112 .filter_map(Result::ok)
113 .filter(|path| path.is_file())
114 .filter_map(|path| path.parent().map(Path::to_owned))
115 .collect()
116 })
117 .unwrap_or_default()
118 }
119
120 /// Find runtimes using platform-specific knowledge (macOS).
121 ///
122 /// For example: check Homebrew.
123 #[cfg(any(doc, target_os = "macos"))]
124 pub fn find() -> Vec<PathBuf> {
125 use std::ffi::OsString;
126 use std::os::unix::ffi::OsStringExt;
127
128 std::process::Command::new("brew")
129 .arg("--prefix")
130 .output()
131 .ok()
132 .and_then(|output| {
133 if output.status.success() {
134 Some(OsString::from_vec(output.stdout))
135 } else {
136 None
137 }
138 })
139 .and_then(|brew_prefix| {
140 glob::glob(&format!(
141 "{}/Cellar/postgresql@*/*/bin/pg_ctl",
142 brew_prefix.to_string_lossy().trim_end()
143 ))
144 .ok()
145 })
146 .map(|entries| {
147 entries
148 .filter_map(Result::ok)
149 .filter(|path| path.is_file())
150 .filter_map(|path| path.parent().map(Path::to_owned))
151 .collect()
152 })
153 .unwrap_or_default()
154 }
155}
156
157impl StrategyLike for RuntimesOnPlatform {
158 fn runtimes(&self) -> Runtimes<'_> {
159 Box::new(
160 Self::find()
161 .into_iter()
162 // Throw away runtimes that we can't determine the version for,
163 // and those that pgdo does not support.
164 .filter_map(|bindir| Runtime::new(bindir).ok())
165 .filter(Runtime::is_supported),
166 )
167 }
168}
169
170/// Compose strategies for finding PostgreSQL runtimes.
171#[derive(Debug)]
172pub enum Strategy {
173 /// Each strategy is consulted in turn.
174 Chain(VecDeque<Strategy>),
175 /// Delegate to another strategy; needed when implementing [`StrategyLike`].
176 Delegated(Box<dyn StrategyLike + Send + Sync>),
177 /// A single runtime; it always picks itself.
178 Single(Runtime),
179}
180
181impl Strategy {
182 /// Push the given strategy to the front of the chain.
183 ///
184 /// If this isn't already, it is converted into a [`Strategy::Chain`].
185 #[must_use]
186 pub fn push_front<S: Into<Strategy>>(mut self, strategy: S) -> Self {
187 match self {
188 Self::Chain(ref mut chain) => {
189 chain.push_front(strategy.into());
190 self
191 }
192 Self::Delegated(_) | Self::Single(_) => {
193 let mut chain: VecDeque<Strategy> = VecDeque::new();
194 chain.push_front(strategy.into());
195 chain.push_back(self);
196 Self::Chain(chain)
197 }
198 }
199 }
200
201 /// Push the given strategy to the back of the chain.
202 ///
203 /// If this isn't already, it is converted into a [`Strategy::Chain`].
204 #[must_use]
205 pub fn push_back<S: Into<Strategy>>(mut self, strategy: S) -> Self {
206 match self {
207 Self::Chain(ref mut chain) => {
208 chain.push_back(strategy.into());
209 self
210 }
211 Self::Delegated(_) | Self::Single(_) => {
212 let mut chain: VecDeque<Strategy> = VecDeque::new();
213 chain.push_front(self);
214 chain.push_back(strategy.into());
215 Self::Chain(chain)
216 }
217 }
218 }
219}
220
221impl Default for Strategy {
222 /// Select runtimes from on `PATH` followed by platform-specific runtimes.
223 fn default() -> Self {
224 Self::Chain(VecDeque::new())
225 .push_front(RuntimesOnPathEnv)
226 .push_back(RuntimesOnPlatform)
227 }
228}
229
230impl StrategyLike for Strategy {
231 /// - For a [`Strategy::Chain`], yields runtimes known to all strategies, in
232 /// the same order as each strategy returns them.
233 /// - For a [`Strategy::Delegated`], calls through to the wrapped strategy.
234 /// - For a [`Strategy::Single`], yields the runtime it's holding.
235 ///
236 /// **Note** that for the first two, runtimes are deduplicated by version
237 /// number, i.e. if a runtime with the same version number is yielded by
238 /// multiple strategies, or is yielded multiple times by a single strategy,
239 /// it will only be returned the first time it is seen.
240 fn runtimes(&self) -> Runtimes<'_> {
241 match self {
242 Self::Chain(chain) => {
243 let mut seen = std::collections::HashSet::new();
244 Box::new(
245 chain
246 .iter()
247 .flat_map(|strategy| strategy.runtimes())
248 .filter(move |runtime| seen.insert(runtime.version)),
249 )
250 }
251 Self::Delegated(strategy) => {
252 let mut seen = std::collections::HashSet::new();
253 Box::new(
254 strategy
255 .runtimes()
256 .filter(move |runtime| seen.insert(runtime.version)),
257 )
258 }
259 Self::Single(runtime) => Box::new(std::iter::once(runtime.clone())),
260 }
261 }
262
263 /// - For a [`Strategy::Chain`], asks each strategy in turn to select a
264 /// runtime. The first non-[`None`] answer is selected.
265 /// - For a [`Strategy::Delegated`], calls through to the wrapped strategy.
266 /// - For a [`Strategy::Single`], returns the runtime if it's compatible.
267 fn select(&self, constraint: &Constraint) -> Option<Runtime> {
268 match self {
269 Self::Chain(c) => c.iter().find_map(|strategy| strategy.select(constraint)),
270 Self::Delegated(strategy) => strategy.select(constraint),
271 Self::Single(runtime) if constraint.matches(runtime) => Some(runtime.clone()),
272 Self::Single(_) => None,
273 }
274 }
275
276 /// - For a [`Strategy::Chain`], asks each strategy in turn for a fallback
277 /// runtime. The first non-[`None`] answer is selected.
278 /// - For a [`Strategy::Delegated`], calls through to the wrapped strategy.
279 /// - For a [`Strategy::Single`], returns the runtime it's holding.
280 fn fallback(&self) -> Option<Runtime> {
281 match self {
282 Self::Chain(chain) => chain.iter().find_map(Strategy::fallback),
283 Self::Delegated(strategy) => strategy.fallback(),
284 Self::Single(runtime) => Some(runtime.clone()),
285 }
286 }
287}
288
289impl From<RuntimesOnPath> for Strategy {
290 /// Converts the given strategy into a [`Strategy::Delegated`].
291 fn from(strategy: RuntimesOnPath) -> Self {
292 Self::Delegated(Box::new(strategy))
293 }
294}
295
296impl From<RuntimesOnPathEnv> for Strategy {
297 /// Converts the given strategy into a [`Strategy::Delegated`].
298 fn from(strategy: RuntimesOnPathEnv) -> Self {
299 Self::Delegated(Box::new(strategy))
300 }
301}
302
303impl From<RuntimesOnPlatform> for Strategy {
304 /// Converts the given strategy into a [`Strategy::Delegated`].
305 fn from(strategy: RuntimesOnPlatform) -> Self {
306 Self::Delegated(Box::new(strategy))
307 }
308}
309
310impl From<Runtime> for Strategy {
311 /// Converts the given runtime into a [`Strategy::Single`].
312 fn from(runtime: Runtime) -> Self {
313 Self::Single(runtime)
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use std::env;
320
321 use super::{RuntimesOnPath, RuntimesOnPathEnv, RuntimesOnPlatform, Strategy, StrategyLike};
322
323 /// This will fail if there are no PostgreSQL runtimes installed.
324 #[test]
325 fn runtime_find_custom_path() {
326 let path = env::var_os("PATH").expect("PATH not set");
327 let strategy = RuntimesOnPath(path.into());
328 let runtimes = strategy.runtimes();
329 assert_ne!(0, runtimes.count());
330 }
331
332 /// This will fail if there are no PostgreSQL runtimes installed.
333 #[test]
334 fn runtime_find_env_path() {
335 let runtimes = RuntimesOnPathEnv.runtimes();
336 assert_ne!(0, runtimes.count());
337 }
338
339 /// This will fail if there are no PostgreSQL runtimes installed.
340 #[test]
341 #[cfg(any(target_os = "linux", target_os = "macos"))]
342 fn runtime_find_on_platform() {
343 let runtimes = RuntimesOnPlatform.runtimes();
344 assert_ne!(0, runtimes.count());
345 }
346
347 /// This will fail if there are no PostgreSQL runtimes installed. It's also
348 /// somewhat fragile because it relies upon knowing the implementation of
349 /// the strategies of which the default [`StrategySet`] is composed.
350 #[test]
351 fn runtime_strategy_set_default() {
352 let strategy = Strategy::default();
353 // There is at least one runtime available.
354 let runtimes = strategy.runtimes();
355 assert_ne!(0, runtimes.count());
356 // There is always a fallback.
357 assert!(strategy.fallback().is_some());
358 }
359}