pg-ephemeral 0.1.3

Ephemeral PostgreSQL instances for testing
Documentation
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use crate::config::Config;
use crate::{InstanceMap, InstanceName};

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Command(#[from] cmd_proc::CommandError),
    #[error(transparent)]
    Config(#[from] crate::config::Error),
    #[error(transparent)]
    Container(#[from] crate::container::Error),
    #[error("Unknown instance: {0}")]
    UnknownInstance(InstanceName),
}

#[derive(Clone, Debug, Default)]
pub enum ConfigFileSource {
    #[default]
    Implicit,
    Explicit(std::path::PathBuf),
    None,
}

impl ConfigFileSource {
    fn from_arguments(config_file: Option<std::path::PathBuf>, no_config_file: bool) -> Self {
        match (config_file, no_config_file) {
            (Some(path), false) => Self::Explicit(path),
            (None, true) => Self::None,
            (None, false) => Self::Implicit,
            (Some(_), true) => unreachable!("clap conflicts_with prevents this"),
        }
    }
}

#[derive(Clone, Debug, clap::Parser)]
#[command(after_help = "INSTANCE SELECTION:
    All commands target the \"main\" instance by default.
    Use --instance <NAME> to target a different instance.")]
#[command(version = crate::VERSION_STR)]
pub struct App {
    /// Config file to use, defaults to attempt to load database.toml
    ///
    /// If absent on default location a single "main" database is assumed on
    /// autodetected backend with latest postgres and no other configuration.
    #[arg(long, conflicts_with = "no_config_file")]
    config_file: Option<std::path::PathBuf>,
    /// Do not load any config file, use default instance map
    #[arg(long, conflicts_with = "config_file")]
    no_config_file: bool,
    /// Overwrite backend
    ///
    /// If not specified on the CLI and not in the config file will be autodetected:
    /// first based on env variable OCIMAN_BACKEND, then on installed tools.
    /// If the autodetection fails exits with an error.
    #[arg(long)]
    backend: Option<ociman::backend::Selection>,
    /// Overwrite image
    #[arg(long)]
    image: Option<crate::image::Image>,
    /// Enable SSL with the specified hostname
    #[arg(long)]
    ssl_hostname: Option<pg_client::config::HostName>,
    #[clap(subcommand)]
    command: Option<Command>,
}

impl App {
    pub async fn run(&self) -> Result<(), Error> {
        let overwrites = crate::config::InstanceDefinition {
            backend: self.backend,
            image: self.image.clone(),
            seeds: indexmap::IndexMap::new(),
            ssl_config: self
                .ssl_hostname
                .clone()
                .map(|hostname| crate::config::SslConfigDefinition { hostname }),
            wait_available_timeout: None,
        };

        let config_file_source =
            ConfigFileSource::from_arguments(self.config_file.clone(), self.no_config_file);

        let instance_map = match config_file_source {
            ConfigFileSource::Explicit(config_file) => {
                Config::load_toml_file(&config_file, &overwrites)?
            }
            ConfigFileSource::None => {
                log::debug!("--no-config-file specified, using default instance map");
                crate::Config::default().instance_map(&overwrites)?
            }
            ConfigFileSource::Implicit => {
                log::debug!("No config file specified, trying to load from default location");

                match Config::load_toml_file("database.toml", &overwrites) {
                    Ok(value) => value,
                    Err(crate::config::Error::IO(crate::config::IoError(
                        std::io::ErrorKind::NotFound,
                    ))) => {
                        log::debug!(
                            "Config file does not exist in default location, using default instance map"
                        );
                        crate::Config::default().instance_map(&overwrites)?
                    }
                    Err(error) => return Err(error.into()),
                }
            }
        };

        self.command
            .clone()
            .unwrap_or_default()
            .run(&instance_map)
            .await?;

        Ok(())
    }
}

#[derive(Clone, Debug, clap::Parser)]
pub enum CacheCommand {
    /// Print cache status for seeds
    Status {
        /// Output as JSON with full details
        #[arg(long)]
        json: bool,
    },
    /// Remove cached images for the instance
    Reset {
        /// Force removal even if images are in use by stopped containers
        #[arg(long)]
        force: bool,
    },
    /// Populate cache by running seeds and committing at each cacheable point
    Populate,
}

#[derive(Clone, Debug, clap::Parser)]
pub enum Command {
    /// Cache related commands
    Cache {
        /// Target instance name
        #[arg(long = "instance", default_value_t)]
        instance_name: InstanceName,
        #[clap(subcommand)]
        command: CacheCommand,
    },
    /// Run interactive psql session on the container
    #[command(name = "container-psql")]
    ContainerPsql {
        /// Target instance name
        #[arg(long = "instance", default_value_t)]
        instance_name: InstanceName,
    },
    /// List defined instances
    List,
    /// Run schema dump from the container
    #[command(name = "container-schema-dump")]
    ContainerSchemaDump {
        /// Target instance name
        #[arg(long = "instance", default_value_t)]
        instance_name: InstanceName,
    },
    /// Run interactive shell on the container
    #[command(name = "container-shell")]
    ContainerShell {
        /// Target instance name
        #[arg(long = "instance", default_value_t)]
        instance_name: InstanceName,
    },
    /// Run integration server
    ///
    /// Intent to be used for automation with other languages wrapping pg-ephemeral.
    ///
    /// After successful boot connects to the inherited pipe file descriptors,
    /// writes a single JSON line with connection details to --result-fd,
    /// then waits for EOF on --control-fd before shutting down.
    #[command(name = "integration-server")]
    IntegrationServer {
        /// Target instance name
        #[arg(long = "instance", default_value_t)]
        instance_name: InstanceName,
        /// File descriptor for writing the result JSON
        #[arg(long)]
        result_fd: std::os::fd::RawFd,
        /// File descriptor for reading the control signal (EOF = shutdown)
        #[arg(long)]
        control_fd: std::os::fd::RawFd,
    },
    /// Run interactive psql on the host
    Psql {
        /// Target instance name
        #[arg(long = "instance", default_value_t)]
        instance_name: InstanceName,
    },
    /// Run shell command with environment variables for PostgreSQL connection
    ///
    /// Sets all PostgreSQL-related environment variables:
    /// - libpq-style PG* environment variables (PGHOST, PGPORT, PGUSER, PGDATABASE, PGPASSWORD, PGSSLMODE, etc.)
    /// - DATABASE_URL in PostgreSQL URL format
    RunEnv {
        /// Target instance name
        #[arg(long = "instance", default_value_t)]
        instance_name: InstanceName,
        /// The command to run
        command: String,
        /// Arguments to pass to the command
        arguments: Vec<String>,
    },
    /// Platform related commands
    #[command(name = "platform")]
    Platform {
        #[clap(subcommand)]
        command: PlatformCommand,
    },
}

#[derive(Clone, Debug, clap::Parser)]
pub enum PlatformCommand {
    /// Check if the current platform is supported
    ///
    /// Exits with status 0 if platform is supported.
    /// Exits with status 1 if platform is not supported.
    Support,
    /// Trigger a panic to test backtrace quality
    ///
    /// Used by integration tests to verify that backtraces
    /// contain file paths and line numbers in release builds.
    TestBacktrace,
}

impl PlatformCommand {
    fn run(&self) {
        match self {
            Self::Support => match ociman::platform::support() {
                Ok(()) => {
                    std::process::exit(0);
                }
                Err(error) => {
                    log::info!("pg-ephemeral is not supported on this platform: {error}");
                    std::process::exit(1);
                }
            },
            Self::TestBacktrace => {
                trigger_test_panic();
            }
        }
    }
}

#[inline(never)]
fn trigger_test_panic() {
    inner_function_for_backtrace_test();
}

#[inline(never)]
fn inner_function_for_backtrace_test() {
    panic!("intentional panic for backtrace testing");
}

impl Default for Command {
    fn default() -> Self {
        Self::Psql {
            instance_name: InstanceName::default(),
        }
    }
}

impl Command {
    pub async fn run(&self, instance_map: &InstanceMap) -> Result<(), Error> {
        match self {
            Self::Cache {
                instance_name,
                command,
            } => match command {
                CacheCommand::Status { json } => {
                    let definition = Self::get_instance(instance_map, instance_name)?
                        .definition(instance_name)
                        .await
                        .unwrap();
                    definition.print_cache_status(instance_name, *json).await?
                }
                CacheCommand::Reset { force } => {
                    let definition = Self::get_instance(instance_map, instance_name)?
                        .definition(instance_name)
                        .await
                        .unwrap();
                    let name: ociman::reference::Name =
                        format!("pg-ephemeral/{instance_name}").parse().unwrap();
                    let references = definition.backend.image_references_by_name(&name).await;
                    for reference in &references {
                        if *force {
                            definition.backend.remove_image_force(reference).await;
                        } else {
                            definition.backend.remove_image(reference).await;
                        }
                        println!("Removed: {reference}");
                    }
                }
                CacheCommand::Populate => {
                    let definition = Self::get_instance(instance_map, instance_name)?
                        .definition(instance_name)
                        .await
                        .unwrap();
                    definition.populate_cache(instance_name).await?;
                    definition.print_cache_status(instance_name, false).await?;
                }
            },
            Self::ContainerPsql { instance_name } => {
                let definition = Self::get_instance(instance_map, instance_name)?
                    .definition(instance_name)
                    .await
                    .unwrap();
                definition.with_container(container_psql).await?
            }
            Self::ContainerSchemaDump { instance_name } => {
                let definition = Self::get_instance(instance_map, instance_name)?
                    .definition(instance_name)
                    .await
                    .unwrap();
                definition.with_container(container_schema_dump).await?
            }
            Self::ContainerShell { instance_name } => {
                let definition = Self::get_instance(instance_map, instance_name)?
                    .definition(instance_name)
                    .await
                    .unwrap();
                definition.with_container(container_shell).await?
            }
            Self::IntegrationServer {
                instance_name,
                result_fd,
                control_fd,
            } => {
                let definition = Self::get_instance(instance_map, instance_name)?
                    .definition(instance_name)
                    .await
                    .unwrap();
                definition
                    .run_integration_server(*result_fd, *control_fd)
                    .await?
            }
            Self::List => {
                for instance_name in instance_map.keys() {
                    println!("{instance_name}")
                }
            }
            Self::Psql { instance_name } => {
                let definition = Self::get_instance(instance_map, instance_name)?
                    .definition(instance_name)
                    .await
                    .unwrap();
                definition.with_container(host_psql).await??
            }
            Self::RunEnv {
                instance_name,
                command,
                arguments,
            } => {
                let definition = Self::get_instance(instance_map, instance_name)?
                    .definition(instance_name)
                    .await
                    .unwrap();
                definition
                    .with_container(async |container| {
                        host_command(container, command, arguments).await
                    })
                    .await??
            }
            Self::Platform { command } => command.run(),
        }

        Ok(())
    }

    fn get_instance<'a>(
        instance_map: &'a InstanceMap,
        instance_name: &InstanceName,
    ) -> Result<&'a crate::config::Instance, Error> {
        instance_map
            .get(instance_name)
            .ok_or_else(|| Error::UnknownInstance(instance_name.clone()))
    }
}

async fn host_psql(container: &crate::container::Container) -> Result<(), cmd_proc::CommandError> {
    cmd_proc::Command::new("psql")
        .envs(container.pg_env())
        .status()
        .await
}

async fn host_command(
    container: &crate::container::Container,
    command: &str,
    arguments: &Vec<String>,
) -> Result<(), cmd_proc::CommandError> {
    cmd_proc::Command::new(command)
        .arguments(arguments)
        .envs(container.pg_env())
        .env(&crate::ENV_DATABASE_URL, container.database_url())
        .status()
        .await
}

async fn container_psql(container: &crate::container::Container) {
    container.exec_psql().await
}

async fn container_schema_dump(container: &crate::container::Container) {
    let pg_schema_dump = pg_client::PgSchemaDump::new();
    println!("{}", container.exec_schema_dump(&pg_schema_dump).await);
}

async fn container_shell(container: &crate::container::Container) {
    container.exec_container_shell().await
}