use crate::error::{ForgeError, Result};
use postgresql_embedded::{PostgreSQL, Settings, VersionReq};
use rand_core::RngCore;
use std::fmt::Write as _;
use std::path::Path;
use std::time::Duration;
const EMBEDDED_PG_VERSION: &str = "=18";
const EMBEDDED_DATABASE: &str = "forge";
const COMMAND_TIMEOUT: Duration = Duration::from_secs(120);
pub(crate) struct EmbeddedPg {
_server: PostgreSQL,
}
pub(crate) async fn start(dir: &Path) -> Result<(EmbeddedPg, String)> {
let version = VersionReq::parse(EMBEDDED_PG_VERSION).map_err(|e| {
ForgeError::config(format!(
"invalid embedded postgres version requirement: {e}"
))
})?;
std::fs::create_dir_all(dir).map_err(|e| {
ForgeError::config(format!(
"could not create embedded postgres directory {}: {e}",
dir.display()
))
})?;
let data_dir = dir.join("data");
let password_file = dir.join("pwfile");
let password = load_or_create_password(&password_file, &data_dir)?;
let settings = Settings {
version,
data_dir,
password_file,
password,
temporary: false,
port: 0,
timeout: Some(COMMAND_TIMEOUT),
..Settings::default()
};
let mut server = PostgreSQL::new(settings);
server.setup().await.map_err(|e| {
ForgeError::config(format!(
"could not install/initialize embedded postgres in {}: {e}",
dir.display()
))
})?;
server.start().await.map_err(|e| {
ForgeError::config(format!(
"could not start embedded postgres in {dir}: {e}. If another process is \
using this data directory, stop it; if a previous run crashed, delete \
{dir} to reset (this discards the embedded data)",
dir = dir.display()
))
})?;
let exists = server
.database_exists(EMBEDDED_DATABASE)
.await
.map_err(|e| embedded_db_err(&server, e))?;
if !exists {
server
.create_database(EMBEDDED_DATABASE)
.await
.map_err(|e| embedded_db_err(&server, e))?;
}
let url = server.settings().url(EMBEDDED_DATABASE);
Ok((EmbeddedPg { _server: server }, url))
}
fn embedded_db_err(server: &PostgreSQL, e: postgresql_embedded::Error) -> ForgeError {
ForgeError::config(format!(
"could not prepare the '{EMBEDDED_DATABASE}' database on the embedded postgres \
(data dir {}): {e}",
server.settings().data_dir.display()
))
}
fn load_or_create_password(password_file: &Path, data_dir: &Path) -> Result<String> {
if password_file.exists() {
let password = std::fs::read_to_string(password_file)
.map_err(|e| {
ForgeError::config(format!(
"could not read embedded postgres password file {}: {e}",
password_file.display()
))
})?
.trim()
.to_string();
if password.is_empty() {
return Err(ForgeError::config(format!(
"embedded postgres password file {} is empty; delete the embedded \
directory to reset (this discards the embedded data)",
password_file.display()
)));
}
return Ok(password);
}
if data_dir.join("postgresql.conf").exists() {
return Err(ForgeError::config(format!(
"embedded postgres data directory {} is initialized but its password file \
{} is missing; delete the embedded directory to reset (this discards the \
embedded data)",
data_dir.display(),
password_file.display()
)));
}
let mut bytes = [0u8; 24];
rand_core::OsRng
.try_fill_bytes(&mut bytes)
.map_err(|e| ForgeError::config(format!("could not generate a password: {e}")))?;
let mut password = String::with_capacity(bytes.len() * 2);
for b in bytes {
let _ = write!(password, "{b:02x}");
}
std::fs::write(password_file, &password).map_err(|e| {
ForgeError::config(format!(
"could not write embedded postgres password file {}: {e}",
password_file.display()
))
})?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(password_file, std::fs::Permissions::from_mode(0o600));
}
Ok(password)
}