Files
tessera/crates/tessera-providers/src/postgres_restore.rs
Adnan Zahir 6320b6f244 feat: add managed database capture and operator restore
PostgreSQL and MySQL backups run through paired outposts, with operator sign-in, off-site copies, and legacy import. Retention stays on each orbit, so the unused retention console is removed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 23:26:49 +07:00

266 lines
9.3 KiB
Rust

use crate::PostgresSource;
use anyhow::{ensure, Context, Result};
use serde::Deserialize;
use std::{
fs::{self, File},
io::{self, BufRead, BufReader, Read, Seek, SeekFrom, Write},
path::PathBuf,
process::Stdio,
};
use tessera_core::{
job::CaptureFormat,
restore::{DatabaseIdentity, Engine},
};
use tokio::process::Command;
#[derive(Deserialize)]
#[serde(tag = "reset", rename_all = "snake_case", deny_unknown_fields)]
pub enum PostgresReset {
Schema {
#[serde(default = "public")]
schema: String,
},
RecreateDatabase,
}
fn public() -> String {
"public".into()
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PostgresRestore {
pub connection: PostgresSource,
pub mode: PostgresReset,
pub post_restore_sql: Option<PathBuf>,
#[serde(default)]
pub omit_transaction_timeout: bool,
#[serde(default)]
pub omit_pg_stat_statements: bool,
}
impl PostgresRestore {
pub async fn prepare(
&self,
mut dump: File,
format: CaptureFormat,
expected: &DatabaseIdentity,
) -> Result<File> {
ensure!(
expected.valid(Engine::Postgres) && expected.database == self.connection.database,
"PostgreSQL target identity does not match the local profile"
);
ensure!(
!matches!(
expected.database.as_str(),
"postgres" | "template0" | "template1"
),
"system database restore is forbidden"
);
let help = Command::new("psql")
.arg("--help=commands")
.kill_on_drop(true)
.output()
.await?;
ensure!(
help.status.success()
&& help
.stdout
.windows(b"\\restrict".len())
.any(|word| word == b"\\restrict"),
"PostgreSQL restore requires a psql client with restricted mode"
);
dump.seek(SeekFrom::Start(0))?;
let mut data = match format {
CaptureFormat::PostgresCustom => {
convert(
dump,
"pg_restore",
&["--no-owner", "--no-privileges", "--file=-"],
)
.await?
}
CaptureFormat::PostgresSql => {
let mut signature = [0; 2];
dump.read_exact(&mut signature)?;
dump.seek(SeekFrom::Start(0))?;
if signature == [0x1f, 0x8b] {
convert(dump, "gzip", &["-dc"]).await?
} else {
dump
}
}
_ => anyhow::bail!("invalid PostgreSQL dump format"),
};
data.seek(SeekFrom::Start(0))?;
let mut script = tempfile::tempfile()?;
writeln!(script, "SET standard_conforming_strings = on;")?;
let instance = literal(&expected.instance);
let database = literal(&expected.database);
match &self.mode {
PostgresReset::Schema { schema } => {
ensure!(
!schema.is_empty()
&& schema.len() <= 63
&& !schema.chars().any(char::is_control)
&& schema != "information_schema"
&& !schema.starts_with("pg_"),
"invalid target schema"
);
writeln!(script, "BEGIN;")?;
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND pg_catalog.current_database() = {database})::int) FROM pg_catalog.pg_control_system();")?;
writeln!(
script,
"DROP SCHEMA IF EXISTS {} CASCADE;",
identifier(schema)
)?;
if schema == "public" {
writeln!(script, "CREATE SCHEMA public;")?;
}
}
PostgresReset::RecreateDatabase => {
ensure!(
expected
.database
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_'),
"recreate mode requires an alphanumeric database identifier"
);
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND EXISTS (SELECT 1 FROM pg_catalog.pg_database WHERE datname = {database}))::int) FROM pg_catalog.pg_control_system();")?;
let name = identifier(&expected.database);
writeln!(
script,
"DROP DATABASE {name};\nCREATE DATABASE {name};\n\\connect {}",
expected.database
)?;
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND pg_catalog.current_database() = {database})::int) FROM pg_catalog.pg_control_system();")?;
writeln!(script, "BEGIN;")?;
}
}
let key = uuid::Uuid::new_v4().simple();
writeln!(script, "\\restrict {key}")?;
let skip_timeout = self.omit_transaction_timeout;
let skip_extension = self.omit_pg_stat_statements;
let create_public =
matches!(&self.mode, PostgresReset::Schema { schema } if schema == "public");
let post_sql = self.post_restore_sql.clone();
tokio::task::spawn_blocking(move || {
append_dump(
data,
&mut script,
skip_timeout,
skip_extension,
create_public,
)?;
if let Some(path) = post_sql {
io::copy(
&mut fs::File::open(path).context("read local post-restore SQL")?,
&mut script,
)?;
}
writeln!(script, "\nCOMMIT;\n\\unrestrict {key}")?;
script.seek(SeekFrom::Start(0))?;
Ok(script)
})
.await?
}
pub async fn apply(&self, script: File) -> Result<()> {
let database = match self.mode {
PostgresReset::RecreateDatabase => Some("postgres"),
PostgresReset::Schema { .. } => None,
};
let args = ["-X", "-w", "-q", "-v", "ON_ERROR_STOP=1", "-f", "-"].map(String::from);
self.connection
.run("psql", &args, database, Stdio::from(script), Stdio::null())
.await?;
Ok(())
}
}
fn literal(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}
fn identifier(value: &str) -> String {
format!("\"{}\"", value.replace('"', "\"\""))
}
async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> {
let file = tempfile::tempfile()?;
let status = Command::new(executable)
.args(args)
.stdin(Stdio::from(input))
.stdout(Stdio::from(file.try_clone()?))
.stderr(Stdio::null())
.kill_on_drop(true)
.status()
.await
.context("prepare PostgreSQL restore script")?;
ensure!(
status.success(),
"{executable} rejected the restore archive"
);
ensure!(
file.metadata()?.len() > 0,
"empty PostgreSQL restore script"
);
Ok(file)
}
fn append_dump(
data: File,
script: &mut File,
skip_timeout: bool,
skip_extension: bool,
create_public: bool,
) -> Result<()> {
let mut input = BufReader::new(data);
let mut header = true;
let mut extension_statement = false;
let mut copy_data = false;
let mut line = Vec::new();
while input.read_until(b'\n', &mut line)? > 0 {
let text = line.strip_suffix(b"\n").unwrap_or(&line);
if copy_data {
script.write_all(&line)?;
copy_data = text != b"\\.";
line.clear();
continue;
}
if text.starts_with(b"-- Name: ") {
extension_statement = skip_extension
&& (text.starts_with(b"-- Name: pg_stat_statements; Type: EXTENSION;")
|| text.starts_with(b"-- Name: EXTENSION pg_stat_statements; Type: COMMENT;"));
header = false;
}
// Tessera installs its own restricted-mode key. Archive-generated keys are redundant.
let own_restriction = [b"\\restrict ".as_slice(), b"\\unrestrict ".as_slice()]
.iter()
.any(|prefix| {
text.strip_prefix(*prefix)
.is_some_and(|key| !key.is_empty() && key.iter().all(u8::is_ascii_alphanumeric))
});
let extension = extension_statement
&& (text
.starts_with(b"CREATE EXTENSION IF NOT EXISTS pg_stat_statements WITH SCHEMA ")
|| text.starts_with(b"COMMENT ON EXTENSION pg_stat_statements IS "));
if !text.is_empty() && !text.starts_with(b"--") {
extension_statement = false;
}
if !(own_restriction
|| extension
|| header && skip_timeout && text == b"SET transaction_timeout = 0;")
{
if create_public && text == b"CREATE SCHEMA public;" {
writeln!(script, "CREATE SCHEMA IF NOT EXISTS public;")?;
} else {
script.write_all(&line)?;
}
}
copy_data = text.starts_with(b"COPY ") && text.ends_with(b" FROM stdin;");
line.clear();
}
Ok(())
}