fuel_core_chain_config/config/
snapshot_metadata.rs

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
use anyhow::Context;
use std::{
    io::Read,
    path::{
        Path,
        PathBuf,
    },
};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
pub enum TableEncoding {
    Json {
        filepath: PathBuf,
    },
    #[cfg(feature = "parquet")]
    Parquet {
        tables: std::collections::HashMap<String, PathBuf>,
        latest_block_config_path: PathBuf,
    },
}
impl TableEncoding {
    #[allow(clippy::assigning_clones)] // False positive will be fixed in 1.81 Rust (https://github.com/rust-lang/rust-clippy/pull/12756)
    fn strip_prefix(&mut self, dir: &Path) -> anyhow::Result<()> {
        match self {
            TableEncoding::Json { filepath } => {
                *filepath = filepath.strip_prefix(dir)?.to_owned();
            }
            #[cfg(feature = "parquet")]
            TableEncoding::Parquet {
                tables,
                latest_block_config_path,
                ..
            } => {
                for path in tables.values_mut() {
                    *path = path.strip_prefix(dir)?.to_owned();
                }
                *latest_block_config_path =
                    latest_block_config_path.strip_prefix(dir)?.to_owned();
            }
        }
        Ok(())
    }

    fn prepend_path(&mut self, dir: &Path) {
        match self {
            TableEncoding::Json { filepath } => {
                *filepath = dir.join(&filepath);
            }
            #[cfg(feature = "parquet")]
            TableEncoding::Parquet {
                tables,
                latest_block_config_path,
                ..
            } => {
                for path in tables.values_mut() {
                    *path = dir.join(&path);
                }
                *latest_block_config_path = dir.join(&latest_block_config_path);
            }
        }
    }
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
pub struct SnapshotMetadata {
    pub chain_config: PathBuf,
    pub table_encoding: TableEncoding,
}

impl SnapshotMetadata {
    const METADATA_FILENAME: &'static str = "metadata.json";
    pub fn read(dir: impl AsRef<Path>) -> anyhow::Result<Self> {
        let path = dir.as_ref().join(Self::METADATA_FILENAME);
        let mut json = String::new();
        std::fs::File::open(&path)
            .with_context(|| format!("Could not open snapshot file: {path:?}"))?
            .read_to_string(&mut json)?;
        let mut snapshot: Self = serde_json::from_str(json.as_str())?;
        snapshot.prepend_path(dir.as_ref());

        Ok(snapshot)
    }

    #[allow(clippy::assigning_clones)] // False positive will be fixed in 1.81 Rust (https://github.com/rust-lang/rust-clippy/pull/12756)
    fn strip_prefix(&mut self, dir: &Path) -> anyhow::Result<&mut Self> {
        self.chain_config = self.chain_config.strip_prefix(dir)?.to_owned();
        self.table_encoding.strip_prefix(dir)?;
        Ok(self)
    }

    fn prepend_path(&mut self, dir: &Path) {
        self.chain_config = dir.join(&self.chain_config);
        self.table_encoding.prepend_path(dir);
    }

    pub fn write(mut self, dir: &Path) -> anyhow::Result<()> {
        self.strip_prefix(dir)?;
        let path = dir.join(Self::METADATA_FILENAME);
        let file = std::fs::File::create(path)?;
        serde_json::to_writer_pretty(file, &self)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod json {
        use super::*;

        #[test]
        fn directory_added_to_paths_upon_load() {
            // given
            let temp_dir = tempfile::tempdir().unwrap();
            let dir = temp_dir.path();
            let data = SnapshotMetadata {
                chain_config: "some_chain_config.json".into(),
                table_encoding: TableEncoding::Json {
                    filepath: "some_state_file.json".into(),
                },
            };
            serde_json::to_writer(
                std::fs::File::create(dir.join("metadata.json")).unwrap(),
                &data,
            )
            .unwrap();

            // when
            let snapshot = SnapshotMetadata::read(temp_dir.path()).unwrap();

            // then
            assert_eq!(
                snapshot,
                SnapshotMetadata {
                    chain_config: dir.join("some_chain_config.json"),
                    table_encoding: TableEncoding::Json {
                        filepath: temp_dir.path().join("some_state_file.json"),
                    }
                }
            );
        }

        #[test]
        fn directory_removed_from_paths_upon_save() {
            // given
            let temp_dir = tempfile::tempdir().unwrap();
            let dir = temp_dir.path();
            let snapshot = SnapshotMetadata {
                chain_config: dir.join("some_chain_config.json"),
                table_encoding: TableEncoding::Json {
                    filepath: dir.join("some_state_file.json"),
                },
            };

            // when
            snapshot.write(temp_dir.path()).unwrap();

            // then
            let data: SnapshotMetadata = serde_json::from_reader(
                std::fs::File::open(temp_dir.path().join("metadata.json")).unwrap(),
            )
            .unwrap();
            assert_eq!(
                data,
                SnapshotMetadata {
                    chain_config: "some_chain_config.json".into(),
                    table_encoding: TableEncoding::Json {
                        filepath: "some_state_file.json".into(),
                    }
                }
            );
        }
    }

    #[cfg(feature = "parquet")]
    mod parquet {
        use super::*;
        #[test]
        fn directory_added_to_paths_upon_load() {
            // given
            let temp_dir = tempfile::tempdir().unwrap();
            let dir = temp_dir.path();
            let data = SnapshotMetadata {
                chain_config: "some_chain_config.json".into(),
                table_encoding: TableEncoding::Parquet {
                    tables: std::collections::HashMap::from_iter(vec![(
                        "coins".into(),
                        "coins.parquet".into(),
                    )]),
                    latest_block_config_path: "latest_block_config.parquet".into(),
                },
            };
            serde_json::to_writer(
                std::fs::File::create(dir.join("metadata.json")).unwrap(),
                &data,
            )
            .unwrap();

            // when
            let snapshot = SnapshotMetadata::read(temp_dir.path()).unwrap();

            // then
            assert_eq!(
                snapshot,
                SnapshotMetadata {
                    chain_config: dir.join("some_chain_config.json"),
                    table_encoding: TableEncoding::Parquet {
                        tables: std::collections::HashMap::from_iter(vec![(
                            "coins".into(),
                            temp_dir.path().join("coins.parquet")
                        )]),
                        latest_block_config_path: temp_dir
                            .path()
                            .join("latest_block_config.parquet"),
                    }
                }
            );
        }

        #[test]
        fn directory_removed_from_paths_upon_save() {
            // given
            let temp_dir = tempfile::tempdir().unwrap();
            let dir = temp_dir.path();
            let snapshot = SnapshotMetadata {
                chain_config: dir.join("some_chain_config.json"),
                table_encoding: TableEncoding::Parquet {
                    tables: std::collections::HashMap::from_iter([(
                        "coins".into(),
                        dir.join("coins.parquet"),
                    )]),
                    latest_block_config_path: dir.join("latest_block_config.parquet"),
                },
            };

            // when
            snapshot.write(temp_dir.path()).unwrap();

            // then
            let data: SnapshotMetadata = serde_json::from_reader(
                std::fs::File::open(temp_dir.path().join("metadata.json")).unwrap(),
            )
            .unwrap();
            assert_eq!(
                data,
                SnapshotMetadata {
                    chain_config: "some_chain_config.json".into(),
                    table_encoding: TableEncoding::Parquet {
                        tables: std::collections::HashMap::from_iter([(
                            "coins".into(),
                            "coins.parquet".into(),
                        )]),
                        latest_block_config_path: "latest_block_config.parquet".into(),
                    }
                }
            );
        }
    }
}