forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiB0d793e7Tahinli6 hours ago359 commits

create.rs266 lines, 7.9 KiBHistoryRawDownload
1use std::path::{Path, PathBuf};
2
3use forge_core::store::snapshot::{SNAPSHOT_METHOD, verify_snapshot};
4use forge_core::{Error, Result};
5
6use super::{
7 BACKUP_DIR_PREFIX, BackupOptions, BackupSource, BackupSummary, DB_FILE, DbSnapshot,
8 FORMAT_VERSION, FileEntry, KEY_FILE, MANIFEST_FILE, Manifest, PARTIAL_PREFIX, RepoEntry, Scope,
9 create_private_dir, empty_sha256, ensure_private_dir_all, fsync_dir, hash_file, io_err,
10 manifest_stamp, name_stamp, set_private, sorted, unique_suffix, write_private_file,
11};
12use forge_git::GitEnv;
13
14pub async fn create_backup(source: &BackupSource, opts: &BackupOptions) -> Result<BackupSummary> {
15 let now = time::OffsetDateTime::now_utc();
16 let stamp = name_stamp(now);
17 ensure_private_dir_all(&opts.out)?;
18 let out = opts.out.as_path();
19 let final_dir = out.join(format!("{BACKUP_DIR_PREFIX}{stamp}"));
20 if std::fs::symlink_metadata(&final_dir).is_ok() {
21 return Err(Error::Conflict(format!(
22 "backup set already exists: {}",
23 final_dir.display()
24 )));
25 }
26
27 let suffix = unique_suffix();
28 let staging = out.join(format!(
29 "{PARTIAL_PREFIX}{BACKUP_DIR_PREFIX}{stamp}-{suffix}"
30 ));
31 let scratch_root = out.join(format!("{PARTIAL_PREFIX}verify-{suffix}"));
32 create_private_dir(&staging)?;
33
34 let built = build(source, opts, &staging, &scratch_root, now).await;
35 remove_if_exists(&scratch_root);
36 let mut summary = match built {
37 Ok(summary) => summary,
38 Err(e) => {
39 remove_if_exists(&staging);
40 return Err(e);
41 }
42 };
43 if let Err(e) = std::fs::rename(&staging, &final_dir) {
44 remove_if_exists(&staging);
45 return Err(io_err(e));
46 }
47 fsync_dir(out)?;
48 summary.path = final_dir;
49 Ok(summary)
50}
51
52fn remove_if_exists(path: &Path) {
53 if std::fs::symlink_metadata(path).is_err() {
54 return;
55 }
56 let result = if path.is_dir() {
57 std::fs::remove_dir_all(path)
58 } else {
59 std::fs::remove_file(path)
60 };
61 if let Err(e) = result {
62 tracing::warn!(path = %path.display(), error = %e, "could not remove backup leftovers");
63 }
64}
65
66async fn build(
67 source: &BackupSource,
68 opts: &BackupOptions,
69 staging: &Path,
70 scratch_root: &Path,
71 now: time::OffsetDateTime,
72) -> Result<BackupSummary> {
73 let db_dir = staging.join("db");
74 create_private_dir(&db_dir)?;
75 let snap = db_dir.join("forge.db");
76 source.store.snapshot_to(&snap).await?;
77 set_private(&snap)?;
78 let info = verify_snapshot(&snap).await?;
79 for entry in std::fs::read_dir(&db_dir)? {
80 let name = entry?.file_name();
81 if name != "forge.db" {
82 return Err(Error::Invalid(format!(
83 "snapshot left an unexpected file next to it: {}",
84 name.to_string_lossy()
85 )));
86 }
87 }
88
89 let db_snapshot = if opts.scope == Scope::ReposOnly {
90 std::fs::remove_file(&snap)?;
91 std::fs::remove_dir(&db_dir)?;
92 None
93 } else {
94 Some(DbSnapshot {
95 method: SNAPSHOT_METHOD.to_string(),
96 schema_version: info.schema_version,
97 })
98 };
99
100 let mut repos = Vec::new();
101 if opts.scope != Scope::DbOnly {
102 create_private_dir(&staging.join("repos"))?;
103 create_private_dir(scratch_root)?;
104 for (idx, (id, owner, name)) in info.repos.iter().enumerate() {
105 repos.push(bundle_repo(source, staging, scratch_root, idx, id, owner, name).await?);
106 }
107 }
108
109 let mut rels = Vec::new();
110 if db_snapshot.is_some() {
111 rels.push(DB_FILE.to_string());
112 }
113 for repo in &repos {
114 if let Some(bundle) = &repo.bundle {
115 rels.push(bundle.clone());
116 }
117 }
118 let key_included = opts.include_key;
119 if key_included {
120 copy_key(&source.git.data_dir, staging)?;
121 rels.push(KEY_FILE.to_string());
122 }
123 rels.sort();
124
125 let mut files = Vec::with_capacity(rels.len());
126 for rel in rels {
127 let path = staging.join(&rel);
128 let (bytes, sha256) = tokio::task::spawn_blocking(move || -> Result<(u64, String)> {
129 let f = std::fs::File::open(&path)?;
130 f.sync_all()?;
131 drop(f);
132 hash_file(&path)
133 })
134 .await
135 .map_err(|e| Error::Io(std::io::Error::other(e)))??;
136 files.push(FileEntry {
137 path: rel,
138 bytes,
139 sha256,
140 });
141 }
142
143 let schema_version = db_snapshot.as_ref().map(|d| d.schema_version);
144 let bundles = repos.iter().filter(|r| r.bundle.is_some()).count();
145 let empty_repos = repos.len() - bundles;
146 let total_bytes = files.iter().map(|f| f.bytes).sum();
147 let file_count = files.len();
148 let repo_count = repos.len();
149
150 let manifest = Manifest {
151 format: FORMAT_VERSION,
152 forge_version: format!(
153 "{} ({})",
154 env!("CARGO_PKG_VERSION"),
155 env!("FORGE_BUILD_SHA")
156 ),
157 created_at: manifest_stamp(now),
158 base_url: source.base_url.clone(),
159 scope: opts.scope,
160 db_snapshot,
161 key_included,
162 files: sorted(files),
163 repos,
164 };
165 let json = serde_json::to_vec_pretty(&manifest)
166 .map_err(|e| Error::Invalid(format!("manifest: {e}")))?;
167 write_private_file(&staging.join(MANIFEST_FILE), &json)?;
168 for dir in ["db", "repos", "keys"] {
169 let path = staging.join(dir);
170 if path.is_dir() {
171 fsync_dir(&path)?;
172 }
173 }
174 fsync_dir(staging)?;
175
176 Ok(BackupSummary {
177 path: PathBuf::new(),
178 scope: opts.scope,
179 files: file_count,
180 bytes: total_bytes,
181 repos: repo_count,
182 bundles,
183 empty_repos,
184 schema_version,
185 key_included,
186 })
187}
188
189async fn bundle_repo(
190 source: &BackupSource,
191 staging: &Path,
192 scratch_root: &Path,
193 idx: usize,
194 id: &str,
195 owner: &str,
196 name: &str,
197) -> Result<RepoEntry> {
198 let git = &source.git;
199 let repo = forge_git::repo::repo_path(&git.data_dir, id)?;
200 let (refs_sha256, bundle) = bundle_git_repo(
201 git,
202 &repo,
203 staging,
204 scratch_root,
205 &format!("{idx}.git"),
206 &format!("repos/{id}.bundle"),
207 id,
208 )
209 .await?;
210 Ok(RepoEntry {
211 id: id.to_string(),
212 owner: owner.to_string(),
213 name: name.to_string(),
214 refs_sha256,
215 bundle,
216 })
217}
218
219async fn bundle_git_repo(
220 git: &GitEnv,
221 repo_dir: &Path,
222 staging: &Path,
223 scratch_root: &Path,
224 scratch_name: &str,
225 rel: &str,
226 label: &str,
227) -> Result<(String, Option<String>)> {
228 let refs_sha256 = forge_git::backup::refs_checksum(git, repo_dir).await?;
229 let out = staging.join(rel);
230 let bundle = if forge_git::backup::bundle_create(git, repo_dir, &out).await? {
231 let scratch = scratch_root.join(scratch_name);
232 forge_git::repo::init_bare(git, &scratch, "main").await?;
233 let imported = forge_git::backup::bundle_verify(git, &scratch, &out).await?;
234 remove_if_exists(&scratch);
235 if imported != refs_sha256 {
236 return Err(Error::Conflict(format!(
237 "repo {label} changed while it was being bundled; run the backup again"
238 )));
239 }
240 Some(rel.to_string())
241 } else {
242 if refs_sha256 != empty_sha256() {
243 return Err(Error::Conflict(format!(
244 "repo {label} changed while it was being bundled; run the backup again"
245 )));
246 }
247 None
248 };
249 Ok((refs_sha256, bundle))
250}
251
252fn copy_key(data_dir: &Path, staging: &Path) -> Result<()> {
253 let src = data_dir.join("forge.key");
254 if !src.is_file() {
255 return Err(Error::Config(format!(
256 "--include-key was given but there is no key at {}",
257 src.display()
258 )));
259 }
260 create_private_dir(&staging.join("keys"))?;
261 let dst = staging.join(KEY_FILE);
262 std::fs::copy(&src, &dst)?;
263 set_private(&dst)?;
264 std::fs::File::open(&dst)?.sync_all()?;
265 Ok(())
266}