forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli3 hours ago363 commits

mod.rs208 lines, 4.9 KiBHistoryRawDownload
1mod create;
2mod fsck;
3pub mod healthcheck;
4mod restore;
5mod retention;
6pub mod scheduler;
7mod verify;
8
9use std::fs::{DirBuilder, File};
10use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
11use std::path::{Path, PathBuf};
12
13use forge_core::token::sha256_reader;
14use forge_core::{Error, Result, Store};
15use forge_git::GitEnv;
16use serde::{Deserialize, Serialize};
17use sha2::{Digest, Sha256};
18
19pub use create::create_backup;
20pub use fsck::{FsckSummary, run_fsck};
21pub use restore::restore_backup;
22pub use scheduler::Jobs;
23pub use verify::verify_backup;
24
25pub const FORMAT_VERSION: u32 = 1;
26pub const MANIFEST_FILE: &str = "manifest.json";
27pub const DB_FILE: &str = "db/forge.db";
28pub const KEY_FILE: &str = "keys/forge.key";
29const BACKUP_DIR_PREFIX: &str = "forge-backup-";
30const PARTIAL_PREFIX: &str = ".partial-";
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "kebab-case")]
34pub enum Scope {
35 All,
36 ReposOnly,
37 DbOnly,
38}
39
40#[derive(Clone)]
41pub struct BackupSource {
42 pub store: Store,
43 pub git: GitEnv,
44 pub base_url: String,
45}
46
47#[derive(Debug, Clone)]
48pub struct BackupOptions {
49 pub out: PathBuf,
50 pub include_key: bool,
51 pub scope: Scope,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct BackupSummary {
56 pub path: PathBuf,
57 pub scope: Scope,
58 pub files: usize,
59 pub bytes: u64,
60 pub repos: usize,
61 pub bundles: usize,
62 pub empty_repos: usize,
63 pub schema_version: Option<u32>,
64 pub key_included: bool,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct VerifyReport {
69 pub path: PathBuf,
70 pub scope: Scope,
71 pub files: usize,
72 pub bytes: u64,
73 pub repos: usize,
74 pub bundles_verified: usize,
75 pub empty_repos: usize,
76 pub schema_version: Option<u32>,
77 pub problems: Vec<String>,
78}
79
80impl VerifyReport {
81 pub fn is_ok(&self) -> bool {
82 self.problems.is_empty()
83 }
84}
85
86#[derive(Debug, Serialize, Deserialize)]
87pub struct Manifest {
88 pub format: u32,
89 pub forge_version: String,
90 pub created_at: String,
91 pub base_url: String,
92 pub scope: Scope,
93 pub db_snapshot: Option<DbSnapshot>,
94 pub key_included: bool,
95 pub files: Vec<FileEntry>,
96 pub repos: Vec<RepoEntry>,
97}
98
99#[derive(Debug, Serialize, Deserialize)]
100pub struct DbSnapshot {
101 pub method: String,
102 pub schema_version: u32,
103}
104
105#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
106pub struct FileEntry {
107 pub path: String,
108 pub bytes: u64,
109 pub sha256: String,
110}
111
112#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
113pub struct RepoEntry {
114 pub id: String,
115 pub owner: String,
116 pub name: String,
117 pub refs_sha256: String,
118 pub bundle: Option<String>,
119}
120
121fn io_err(e: std::io::Error) -> Error {
122 Error::Io(e)
123}
124
125fn create_private_dir(path: &Path) -> Result<()> {
126 DirBuilder::new().mode(0o700).create(path).map_err(io_err)
127}
128
129fn ensure_private_dir_all(path: &Path) -> Result<()> {
130 DirBuilder::new()
131 .recursive(true)
132 .mode(0o700)
133 .create(path)
134 .map_err(io_err)
135}
136
137fn write_private_file(path: &Path, bytes: &[u8]) -> Result<()> {
138 use std::io::Write;
139 let mut f = std::fs::OpenOptions::new()
140 .write(true)
141 .create_new(true)
142 .mode(0o600)
143 .open(path)
144 .map_err(io_err)?;
145 f.write_all(bytes).map_err(io_err)?;
146 f.sync_all().map_err(io_err)
147}
148
149fn set_private(path: &Path) -> Result<()> {
150 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(io_err)
151}
152
153fn fsync_dir(path: &Path) -> Result<()> {
154 File::open(path).map_err(io_err)?.sync_all().map_err(io_err)
155}
156
157fn hash_file(path: &Path) -> Result<(u64, String)> {
158 sha256_reader(File::open(path).map_err(io_err)?).map_err(io_err)
159}
160
161fn name_stamp(t: time::OffsetDateTime) -> String {
162 stamp(t, "", "")
163}
164
165fn manifest_stamp(t: time::OffsetDateTime) -> String {
166 stamp(t, "-", ":")
167}
168
169fn stamp(t: time::OffsetDateTime, date_sep: &str, time_sep: &str) -> String {
170 format!(
171 "{:04}{d}{:02}{d}{:02}T{:02}{s}{:02}{s}{:02}Z",
172 t.year(),
173 u8::from(t.month()),
174 t.day(),
175 t.hour(),
176 t.minute(),
177 t.second(),
178 d = date_sep,
179 s = time_sep,
180 )
181}
182
183fn unique_suffix() -> String {
184 let nanos = time::OffsetDateTime::now_utc().unix_timestamp_nanos();
185 format!("{}-{nanos}", std::process::id())
186}
187
188fn empty_sha256() -> String {
189 hex::encode(Sha256::digest(b""))
190}
191
192fn is_known_path(rel: &str) -> bool {
193 if rel == DB_FILE || rel == KEY_FILE {
194 return true;
195 }
196 rel.strip_prefix("repos/")
197 .and_then(|name| name.strip_suffix(".bundle"))
198 .map(|id| id.strip_suffix(".wiki").unwrap_or(id))
199 .is_some_and(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric()))
200}
201
202fn sorted(mut files: Vec<FileEntry>) -> Vec<FileEntry> {
203 files.sort_by(|a, b| a.path.cmp(&b.path));
204 files
205}
206
207#[cfg(test)]
208mod tests;