database_replicator/
preflight.rs

1// ABOUTME: Pre-flight validation checks for replication prerequisites
2// ABOUTME: Validates local environment, network connectivity, and database permissions
3
4use anyhow::Result;
5
6/// Individual check result
7#[derive(Debug, Clone)]
8pub struct CheckResult {
9    pub name: String,
10    pub passed: bool,
11    pub message: String,
12    pub details: Option<String>,
13}
14
15impl CheckResult {
16    pub fn pass(name: impl Into<String>, message: impl Into<String>) -> Self {
17        Self {
18            name: name.into(),
19            passed: true,
20            message: message.into(),
21            details: None,
22        }
23    }
24
25    pub fn fail(name: impl Into<String>, message: impl Into<String>) -> Self {
26        Self {
27            name: name.into(),
28            passed: false,
29            message: message.into(),
30            details: None,
31        }
32    }
33
34    pub fn with_details(mut self, details: impl Into<String>) -> Self {
35        self.details = Some(details.into());
36        self
37    }
38}
39
40/// Issue with suggested fixes
41#[derive(Debug, Clone)]
42pub struct PreflightIssue {
43    pub title: String,
44    pub explanation: String,
45    pub fixes: Vec<String>,
46}
47
48/// Complete pre-flight results
49#[derive(Debug, Default)]
50pub struct PreflightResult {
51    pub local_env: Vec<CheckResult>,
52    pub network: Vec<CheckResult>,
53    pub source_permissions: Vec<CheckResult>,
54    pub target_permissions: Vec<CheckResult>,
55    pub issues: Vec<PreflightIssue>,
56    /// True if pg_dump version < source server version
57    pub tool_version_incompatible: bool,
58    pub local_pg_version: Option<u32>,
59    pub source_pg_version: Option<u32>,
60}
61
62impl PreflightResult {
63    pub fn new() -> Self {
64        Self::default()
65    }
66
67    pub fn all_passed(&self) -> bool {
68        self.issues.is_empty()
69    }
70
71    pub fn failed_count(&self) -> usize {
72        self.issues.len()
73    }
74
75    /// Print formatted output
76    pub fn print(&self) {
77        println!();
78        println!("Pre-flight Checks");
79        println!("{}", "═".repeat(61));
80        println!();
81
82        if !self.local_env.is_empty() {
83            println!("Local Environment:");
84            for check in &self.local_env {
85                let icon = if check.passed { "✓" } else { "✗" };
86                println!("  {} {}", icon, check.message);
87                if let Some(ref details) = check.details {
88                    println!("      {}", details);
89                }
90            }
91            println!();
92        }
93
94        if !self.network.is_empty() {
95            println!("Network Connectivity:");
96            for check in &self.network {
97                let icon = if check.passed { "✓" } else { "✗" };
98                println!("  {} {}", icon, check.message);
99                if let Some(ref details) = check.details {
100                    println!("      {}", details);
101                }
102            }
103            println!();
104        }
105
106        if !self.source_permissions.is_empty() {
107            println!("Source Permissions:");
108            for check in &self.source_permissions {
109                let icon = if check.passed { "✓" } else { "✗" };
110                println!("  {} {}", icon, check.message);
111                if let Some(ref details) = check.details {
112                    println!("      {}", details);
113                }
114            }
115            println!();
116        }
117
118        if !self.target_permissions.is_empty() {
119            println!("Target Permissions:");
120            for check in &self.target_permissions {
121                let icon = if check.passed { "✓" } else { "✗" };
122                println!("  {} {}", icon, check.message);
123                if let Some(ref details) = check.details {
124                    println!("      {}", details);
125                }
126            }
127            println!();
128        }
129
130        println!("{}", "═".repeat(61));
131        if self.all_passed() {
132            println!("PASSED: All pre-flight checks successful");
133        } else {
134            println!("FAILED: {} issue(s) must be resolved", self.failed_count());
135            println!();
136            for (i, issue) in self.issues.iter().enumerate() {
137                println!("Issue {}: {}", i + 1, issue.title);
138                println!("  {}", issue.explanation);
139                println!();
140                println!("  Fix options:");
141                for fix in &issue.fixes {
142                    println!("    • {}", fix);
143                }
144                println!();
145            }
146        }
147    }
148}
149
150/// Run all pre-flight checks
151///
152/// # Arguments
153///
154/// * `source_url` - PostgreSQL connection string for source
155/// * `target_url` - PostgreSQL connection string for target
156/// * `databases` - Optional list of databases to check permissions for
157///
158/// # Returns
159///
160/// PreflightResult containing all check results
161pub async fn run_preflight_checks(
162    source_url: &str,
163    target_url: &str,
164    _databases: Option<&[String]>,
165) -> Result<PreflightResult> {
166    let mut result = PreflightResult::new();
167
168    // 1. Check local environment (pg_dump, pg_restore, etc.)
169    check_local_environment(&mut result);
170
171    // 2. Check network connectivity
172    check_network_connectivity(&mut result, source_url, target_url).await;
173
174    // 3. Check version compatibility (only if we could connect and have local version)
175    if result.local_pg_version.is_some() && result.source_pg_version.is_some() {
176        check_version_compatibility(&mut result);
177    }
178
179    // 4. Check source permissions
180    if result
181        .network
182        .iter()
183        .any(|c| c.name == "source" && c.passed)
184    {
185        check_source_permissions(&mut result, source_url).await;
186    }
187
188    // 5. Check target permissions
189    if result
190        .network
191        .iter()
192        .any(|c| c.name == "target" && c.passed)
193    {
194        check_target_permissions(&mut result, target_url).await;
195    }
196
197    Ok(result)
198}
199
200fn check_local_environment(result: &mut PreflightResult) {
201    let tools = ["pg_dump", "pg_dumpall", "pg_restore", "psql"];
202    let mut missing = Vec::new();
203
204    for tool in tools {
205        match which::which(tool) {
206            Ok(path) => {
207                let path_str = path.display().to_string();
208                match crate::utils::get_pg_tool_version(tool) {
209                    Ok(version) => {
210                        if tool == "pg_dump" {
211                            result.local_pg_version = Some(version);
212                        }
213                        result.local_env.push(
214                            CheckResult::pass(tool, format!("{} found", tool))
215                                .with_details(format!("{} ({})", path_str, version)),
216                        );
217                    }
218                    Err(_) => {
219                        result.local_env.push(
220                            CheckResult::pass(tool, format!("{} found", tool))
221                                .with_details(path_str),
222                        );
223                    }
224                }
225            }
226            Err(_) => {
227                missing.push(tool);
228                result.local_env.push(CheckResult::fail(
229                    tool,
230                    format!("{} not found in PATH", tool),
231                ));
232            }
233        }
234    }
235
236    if !missing.is_empty() {
237        result.issues.push(PreflightIssue {
238            title: "Missing PostgreSQL client tools".to_string(),
239            explanation: format!("Required tools not found: {}", missing.join(", ")),
240            fixes: vec![
241                "Ubuntu: sudo apt install postgresql-client-17".to_string(),
242                "macOS: brew install postgresql@17".to_string(),
243                "RHEL: sudo dnf install postgresql17".to_string(),
244            ],
245        });
246    }
247}
248
249async fn check_network_connectivity(
250    result: &mut PreflightResult,
251    source_url: &str,
252    target_url: &str,
253) {
254    // Check source
255    match crate::postgres::connect_with_retry(source_url).await {
256        Ok(client) => {
257            // Also get server version while connected
258            if let Ok(row) = client.query_one("SHOW server_version", &[]).await {
259                let version_str: String = row.get(0);
260                if let Ok(version) = crate::utils::parse_pg_version_string(&version_str) {
261                    result.source_pg_version = Some(version);
262                }
263            }
264            result
265                .network
266                .push(CheckResult::pass("source", "Source database reachable"));
267        }
268        Err(e) => {
269            result.network.push(CheckResult::fail(
270                "source",
271                format!("Cannot connect to source: {}", e),
272            ));
273            result.issues.push(PreflightIssue {
274                title: "Source database unreachable".to_string(),
275                explanation: e.to_string(),
276                fixes: vec![
277                    "Verify connection string is correct".to_string(),
278                    "Check network connectivity to database host".to_string(),
279                    "Ensure firewall allows PostgreSQL port (5432)".to_string(),
280                ],
281            });
282        }
283    }
284
285    // Check target
286    match crate::postgres::connect_with_retry(target_url).await {
287        Ok(_) => {
288            result
289                .network
290                .push(CheckResult::pass("target", "Target database reachable"));
291        }
292        Err(e) => {
293            result.network.push(CheckResult::fail(
294                "target",
295                format!("Cannot connect to target: {}", e),
296            ));
297            result.issues.push(PreflightIssue {
298                title: "Target database unreachable".to_string(),
299                explanation: e.to_string(),
300                fixes: vec![
301                    "Verify connection string is correct".to_string(),
302                    "Check network connectivity to database host".to_string(),
303                ],
304            });
305        }
306    }
307}
308
309fn check_version_compatibility(result: &mut PreflightResult) {
310    let local = result.local_pg_version.unwrap();
311    let server = result.source_pg_version.unwrap();
312
313    if local < server {
314        result.tool_version_incompatible = true;
315        result.local_env.push(CheckResult::fail(
316            "version",
317            format!("pg_dump version {} < source server {}", local, server),
318        ));
319        result.issues.push(PreflightIssue {
320            title: "PostgreSQL version mismatch".to_string(),
321            explanation: format!(
322                "Local pg_dump ({}) cannot dump from server ({})",
323                local, server
324            ),
325            fixes: vec![
326                format!("Install PostgreSQL {} client tools:", server),
327                format!("  Ubuntu: sudo apt install postgresql-client-{}", server),
328                format!("  macOS: brew install postgresql@{}", server),
329                "Or use SerenAI cloud execution (recommended for SerenDB targets)".to_string(),
330            ],
331        });
332    } else {
333        result.local_env.push(CheckResult::pass(
334            "version",
335            format!("pg_dump version {} >= source server {}", local, server),
336        ));
337    }
338}
339
340async fn check_source_permissions(result: &mut PreflightResult, source_url: &str) {
341    if let Ok(client) = crate::postgres::connect_with_retry(source_url).await {
342        // Check REPLICATION privilege
343        match crate::postgres::check_source_privileges(&client).await {
344            Ok(privs) => {
345                if privs.has_replication || privs.is_superuser {
346                    result.source_permissions.push(CheckResult::pass(
347                        "replication",
348                        "Has REPLICATION privilege",
349                    ));
350                } else {
351                    result.source_permissions.push(CheckResult::fail(
352                        "replication",
353                        "Missing REPLICATION privilege",
354                    ));
355                    result.issues.push(PreflightIssue {
356                        title: "Missing REPLICATION privilege".to_string(),
357                        explanation: "Required for continuous sync".to_string(),
358                        fixes: vec!["Run: ALTER USER <username> REPLICATION;".to_string()],
359                    });
360                }
361            }
362            Err(e) => {
363                result.source_permissions.push(CheckResult::fail(
364                    "privileges",
365                    format!("Failed to check: {}", e),
366                ));
367            }
368        }
369
370        // Check table SELECT permissions
371        match crate::postgres::check_table_select_permissions(&client).await {
372            Ok(perms) => {
373                if perms.all_accessible() {
374                    result.source_permissions.push(CheckResult::pass(
375                        "select",
376                        format!("Has SELECT on all {} tables", perms.accessible_tables.len()),
377                    ));
378                } else {
379                    let inaccessible = &perms.inaccessible_tables;
380                    let count = inaccessible.len();
381                    let preview: Vec<&str> =
382                        inaccessible.iter().take(5).map(|s| s.as_str()).collect();
383                    let details = if count > 5 {
384                        format!("{}, ... ({} more)", preview.join(", "), count - 5)
385                    } else {
386                        preview.join(", ")
387                    };
388
389                    result.source_permissions.push(
390                        CheckResult::fail("select", format!("Missing SELECT on {} tables", count))
391                            .with_details(details),
392                    );
393                    result.issues.push(PreflightIssue {
394                        title: "Missing table permissions".to_string(),
395                        explanation: format!("User needs SELECT on {} tables", count),
396                        fixes: vec![
397                            "Run: GRANT SELECT ON ALL TABLES IN SCHEMA public TO <username>;"
398                                .to_string(),
399                        ],
400                    });
401                }
402            }
403            Err(e) => {
404                result.source_permissions.push(CheckResult::fail(
405                    "select",
406                    format!("Failed to check table permissions: {}", e),
407                ));
408            }
409        }
410    }
411}
412
413async fn check_target_permissions(result: &mut PreflightResult, target_url: &str) {
414    if let Ok(client) = crate::postgres::connect_with_retry(target_url).await {
415        match crate::postgres::check_target_privileges(&client).await {
416            Ok(privs) => {
417                if privs.has_create_db || privs.is_superuser {
418                    result
419                        .target_permissions
420                        .push(CheckResult::pass("createdb", "Can create databases"));
421                } else {
422                    result
423                        .target_permissions
424                        .push(CheckResult::fail("createdb", "Cannot create databases"));
425                    result.issues.push(PreflightIssue {
426                        title: "Missing CREATEDB privilege".to_string(),
427                        explanation: "Cannot create databases on target".to_string(),
428                        fixes: vec!["Run: ALTER USER <username> CREATEDB;".to_string()],
429                    });
430                }
431
432                if privs.is_superuser || privs.has_replication {
433                    result.target_permissions.push(CheckResult::pass(
434                        "subscription",
435                        "Can create subscriptions",
436                    ));
437                } else {
438                    result.target_permissions.push(CheckResult::fail(
439                        "subscription",
440                        "Cannot create subscriptions",
441                    ));
442                }
443            }
444            Err(e) => {
445                result.target_permissions.push(CheckResult::fail(
446                    "privileges",
447                    format!("Failed to check: {}", e),
448                ));
449            }
450        }
451    }
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457
458    #[test]
459    fn test_check_result_pass() {
460        let check = CheckResult::pass("test", "Test passed");
461        assert!(check.passed);
462        assert_eq!(check.name, "test");
463    }
464
465    #[test]
466    fn test_check_result_fail() {
467        let check = CheckResult::fail("test", "Test failed");
468        assert!(!check.passed);
469    }
470
471    #[test]
472    fn test_check_result_with_details() {
473        let check = CheckResult::pass("test", "Test passed").with_details("Some details");
474        assert_eq!(check.details, Some("Some details".to_string()));
475    }
476
477    #[test]
478    fn test_preflight_result_empty_passes() {
479        let result = PreflightResult::new();
480        assert!(result.all_passed());
481        assert_eq!(result.failed_count(), 0);
482    }
483
484    #[test]
485    fn test_preflight_result_with_issues() {
486        let mut result = PreflightResult::new();
487        result.issues.push(PreflightIssue {
488            title: "Test issue".to_string(),
489            explanation: "Test".to_string(),
490            fixes: vec![],
491        });
492        assert!(!result.all_passed());
493        assert_eq!(result.failed_count(), 1);
494    }
495
496    #[test]
497    fn test_preflight_issue_multiple_fixes() {
498        let issue = PreflightIssue {
499            title: "Test".to_string(),
500            explanation: "Details".to_string(),
501            fixes: vec!["Fix 1".to_string(), "Fix 2".to_string()],
502        };
503        assert_eq!(issue.fixes.len(), 2);
504    }
505}