Skip to main content

mysql_replication/engine/
checkpoint.rs

1//! Per-source schema snapshots, atomic checkpoints and exclusive state locks.
2use crate::{Error, Result, TableMeta, config::Config, error::invalid};
3use fs2::FileExt;
4use serde::{Deserialize, Serialize};
5use std::{
6    collections::BTreeSet,
7    fs::{File, OpenOptions},
8    io::Write,
9    path::Path,
10};
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
13#[serde(deny_unknown_fields)]
14pub struct State {
15    pub version: u32,
16    pub source_uuid: String,
17    pub source_id: String,
18    pub source_plugin: String,
19    pub file: String,
20    pub position: u64,
21    pub tables: Vec<TableMeta>,
22}
23impl State {
24    pub fn read(path: &Path) -> Result<Self> {
25        let state: Self = serde_json::from_reader(File::open(path)?)?;
26        state.validate()?;
27        Ok(state)
28    }
29    pub fn validate(&self) -> Result<()> {
30        if self.version != 1
31            || self.file.is_empty()
32            || self.position < 4
33            || self.position > u64::from(u32::MAX)
34            || self.source_uuid.is_empty()
35            || self.source_id.is_empty()
36            || self.source_plugin.is_empty()
37            || self.tables.is_empty()
38        {
39            return Err(invalid("invalid state version/source/file/position/tables"));
40        }
41        let mut names = BTreeSet::new();
42        for table in &self.tables {
43            table.validate()?;
44            if !names.insert((&table.schema, &table.table)) {
45                return Err(invalid("duplicate state table"));
46            }
47        }
48        Ok(())
49    }
50    pub fn verify_whitelist(&self, config: &Config) -> Result<()> {
51        let saved: BTreeSet<_> = self.tables.iter().map(|t| (&t.schema, &t.table)).collect();
52        let requested: BTreeSet<_> = config
53            .tables
54            .iter()
55            .map(|t| (&t.schema, &t.table))
56            .collect();
57        if saved != requested {
58            return Err(Error::Schema(
59                "whitelist differs from saved state; initialize a new state file".into(),
60            ));
61        }
62        Ok(())
63    }
64    /// Atomic replacement; fsync the contents and parent directory before returning.
65    pub fn save(&self, path: &Path) -> Result<()> {
66        let mut temporary = path.as_os_str().to_owned();
67        temporary.push(format!(".{}.tmp", std::process::id()));
68        let temporary = std::path::PathBuf::from(temporary);
69        let result = (|| {
70            let mut options = OpenOptions::new();
71            options.write(true).create_new(true);
72            #[cfg(unix)]
73            {
74                use std::os::unix::fs::OpenOptionsExt;
75                options.mode(0o600);
76            }
77            let mut file = options.open(&temporary)?;
78            serde_json::to_writer_pretty(&mut file, self)?;
79            file.write_all(b"\n")?;
80            file.sync_all()?;
81            std::fs::rename(&temporary, path)?;
82            File::open(
83                path.parent()
84                    .filter(|p| !p.as_os_str().is_empty())
85                    .unwrap_or_else(|| Path::new(".")),
86            )?
87            .sync_all()?;
88            Ok(())
89        })();
90        if result.is_err() {
91            let _ = std::fs::remove_file(&temporary);
92        }
93        result
94    }
95}
96
97pub struct StateLock {
98    _file: File,
99}
100impl StateLock {
101    pub fn acquire(path: &Path) -> Result<Self> {
102        let mut lock_path = path.as_os_str().to_owned();
103        lock_path.push(".lock");
104        let file = OpenOptions::new()
105            .read(true)
106            .write(true)
107            .create(true)
108            .truncate(false)
109            .open(lock_path)?;
110        file.try_lock_exclusive()?;
111        Ok(Self { _file: file })
112    }
113}