forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

export.rs300 lines, 11.0 KiBHistoryRawDownload
1//! `iz export --out <dir>`: writes the board to a new directory so it can be read or kept without the
2//! database.
3//!
4//! The directory holds `board.json` (the board, its tasks, assignees, dependencies, comments, activity,
5//! attachment metadata and the members named by those rows), `attachments/<id>` for every attachment whose
6//! bytes are on this disk, and `manifest.json` with its `manifest.mac` (HMAC under the instance key) for all of them. An attachment whose bytes are elsewhere
7//! (location `in`) or that is moving is listed with `"bytes": false`; the export then exits 1 after writing
8//! everything else, so an incomplete export is never silent. The output is refused unless `--out` is missing
9//! or an empty directory, and no path in it is built from anything but fixed names and validated ULIDs. No
10//! symlink is created, and nothing is written outside `--out`.
11
12use std::fs::{DirBuilder, OpenOptions};
13use std::io::{Read, Write};
14use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
15use std::path::Path;
16use std::process::ExitCode;
17
18use iz_core::config::Config;
19use iz_core::manifest::write_manifest;
20use iz_core::staging::blob_path;
21use iz_core::store::export::{AttachmentRow, ReadOnly};
22use iz_core::time::now_stamp;
23use sha2::{Digest, Sha256};
24
25use super::{database_file, describe, existing_data_dir, fail, instance_key, take_lock};
26
27/// The file that holds the board.
28const BOARD_FILE: &str = "board.json";
29/// The directory inside `--out` that holds the attachment bytes.
30const ATTACHMENTS_DIR: &str = "attachments";
31/// Read chunk for copying bytes. Reason: keeps memory flat for large attachments.
32const CHUNK: usize = 64 * 1024;
33
34/// Runs the export and maps its outcome to an exit status.
35pub async fn run(config_path: &Path, out: &Path) -> ExitCode {
36 let config = match Config::load(config_path) {
37 Ok(config) => config,
38 Err(error) => return fail(describe(&error)),
39 };
40 let data_dir = match existing_data_dir(&config) {
41 Ok(dir) => dir,
42 Err(message) => return fail(message),
43 };
44 let _lock = match take_lock(&data_dir) {
45 Ok(lock) => lock,
46 Err(code) => return code,
47 };
48 let key = match instance_key(&data_dir) {
49 Ok(key) => key,
50 Err(message) => return fail(message),
51 };
52 if let Err(message) = prepare_out(out) {
53 return fail(message);
54 }
55 match write_export(&config, &data_dir, out, &key).await {
56 Ok(report) => {
57 println!(
58 "exported {} attachments with bytes and {} without to {}",
59 report.with_bytes,
60 report.without_bytes.len(),
61 out.display()
62 );
63 if report.without_bytes.is_empty() {
64 return ExitCode::SUCCESS;
65 }
66 for (id, reason) in &report.without_bytes {
67 eprintln!("iz: attachment {id} has no bytes in the export: {reason}");
68 }
69 eprintln!(
70 "iz: the export is incomplete; {} attachments have no bytes",
71 report.without_bytes.len()
72 );
73 ExitCode::FAILURE
74 }
75 Err(message) => fail(message),
76 }
77}
78
79/// What an export wrote, for the summary.
80struct Report {
81 /// Attachments whose bytes are in the export.
82 with_bytes: usize,
83 /// Attachments whose bytes are not, with the reason.
84 without_bytes: Vec<(String, String)>,
85}
86
87/// Makes `out` a new directory with mode 0700, or accepts an existing empty one. A link or a file is
88/// refused, and so is a directory with anything in it.
89fn prepare_out(out: &Path) -> Result<(), String> {
90 match std::fs::symlink_metadata(out) {
91 Ok(meta) => {
92 if !meta.file_type().is_dir() {
93 return Err(format!("{} exists and is not a directory", out.display()));
94 }
95 let mut entries = std::fs::read_dir(out)
96 .map_err(|error| format!("cannot read {}: {error}", out.display()))?;
97 if entries.next().is_some() {
98 return Err(format!("{} is not empty", out.display()));
99 }
100 Ok(())
101 }
102 Err(_) => DirBuilder::new()
103 .mode(0o700)
104 .create(out)
105 .map_err(|error| format!("cannot create {}: {error}", out.display())),
106 }
107}
108
109/// Reads the database and writes the export. Every failure before the manifest leaves the directory
110/// partly written; the caller reports it and the operator removes it.
111async fn write_export(
112 config: &Config,
113 data_dir: &Path,
114 out: &Path,
115 key: &[u8; 32],
116) -> Result<Report, String> {
117 let database = database_file(config)?;
118 let db = ReadOnly::open(&database)
119 .await
120 .map_err(|error| describe(&error))?;
121 let board_ids = db.board_ids().await.map_err(|error| describe(&error))?;
122 let [board_id] = board_ids.as_slice() else {
123 return Err(format!(
124 "expected one board in the database, found {}",
125 board_ids.len()
126 ));
127 };
128 let dump = db
129 .export_board(board_id)
130 .await
131 .map_err(|error| describe(&error))?;
132 let rows = db
133 .board_attachment_rows(board_id)
134 .await
135 .map_err(|error| describe(&error))?;
136
137 DirBuilder::new()
138 .mode(0o700)
139 .recursive(true)
140 .create(out.join(ATTACHMENTS_DIR))
141 .map_err(|error| format!("cannot create the attachments directory: {error}"))?;
142 let mut written = vec![BOARD_FILE.to_owned()];
143 let mut attachments = Vec::with_capacity(rows.len());
144 let mut report = Report {
145 with_bytes: 0,
146 without_bytes: Vec::new(),
147 };
148 for row in &rows {
149 // The id is used in two file names, so it must be the canonical ULID text, or it is refused.
150 let source = blob_path(data_dir, &row.id).map_err(|error| describe(&error))?;
151 let mut entry = attachment_json(row);
152 if row.location == "local" {
153 match copy_blob(&source, &out.join(ATTACHMENTS_DIR).join(&row.id), row)? {
154 Ok(()) => {
155 let relative = format!("{ATTACHMENTS_DIR}/{}", row.id);
156 entry["bytes"] = serde_json::Value::Bool(true);
157 entry["file"] = serde_json::Value::String(relative.clone());
158 written.push(relative);
159 report.with_bytes += 1;
160 }
161 Err(reason) => {
162 entry["bytes"] = serde_json::Value::Bool(false);
163 report.without_bytes.push((row.id.clone(), reason));
164 }
165 }
166 } else {
167 entry["bytes"] = serde_json::Value::Bool(false);
168 report.without_bytes.push((
169 row.id.clone(),
170 format!(
171 "location is {}, the bytes are not on this disk",
172 row.location
173 ),
174 ));
175 }
176 attachments.push(entry);
177 }
178
179 let members = dump.members;
180 let board = serde_json::json!({
181 "format": "iz-export",
182 "version": 1,
183 "exported_at": now_stamp(),
184 "board": dump.board,
185 "columns": dump.columns,
186 "tags": dump.tags,
187 "tasks": dump.tasks,
188 "assignees": dump.assignees,
189 "dependencies": dump.dependencies,
190 "comments": dump.comments,
191 "activity": dump.activity,
192 "attachments": attachments,
193 "members": members,
194 });
195 let bytes = serde_json::to_vec_pretty(&board)
196 .map_err(|error| format!("encoding {BOARD_FILE}: {error}"))?;
197 write_new(&out.join(BOARD_FILE), &bytes)?;
198
199 write_manifest(out, key, &now_stamp(), env!("IZ_BUILD_SHA"), &written)
200 .map_err(|error| describe(&error))?;
201 Ok(report)
202}
203
204/// The metadata of an attachment row as the export file states it.
205fn attachment_json(row: &AttachmentRow) -> serde_json::Value {
206 serde_json::json!({
207 "id": row.id,
208 "task_id": row.task_id,
209 "name": row.name,
210 "mime": row.mime,
211 "size": row.size,
212 "sha256": row.sha256,
213 "uploaded_by": row.uploaded_by,
214 "created_at": row.created_at,
215 "location": row.location,
216 })
217}
218
219/// Copies the bytes of a local attachment to `dest` (created new, mode 0600) and checks that they have the
220/// size and digest of the row. The source must be a regular file. On a mismatch the copy is removed and the
221/// reason is returned as the inner error; the outer error is a failure to write.
222fn copy_blob(
223 source: &Path,
224 dest: &Path,
225 row: &AttachmentRow,
226) -> Result<Result<(), String>, String> {
227 let meta = match std::fs::symlink_metadata(source) {
228 Ok(meta) => meta,
229 Err(_) => return Ok(Err("the bytes are missing from the store".into())),
230 };
231 if !meta.file_type().is_file() {
232 return Ok(Err("the stored entry is not a regular file".into()));
233 }
234 let mut input = std::fs::File::open(source)
235 .map_err(|error| format!("cannot read {}: {error}", source.display()))?;
236 let mut output = OpenOptions::new()
237 .write(true)
238 .create_new(true)
239 .mode(0o600)
240 .open(dest)
241 .map_err(|error| format!("cannot create {}: {error}", dest.display()))?;
242 let mut hasher = Sha256::new();
243 let mut size: u64 = 0;
244 let mut buffer = vec![0u8; CHUNK];
245 loop {
246 let read = input
247 .read(&mut buffer)
248 .map_err(|error| format!("cannot read {}: {error}", source.display()))?;
249 if read == 0 {
250 break;
251 }
252 output
253 .write_all(&buffer[..read])
254 .map_err(|error| format!("cannot write {}: {error}", dest.display()))?;
255 hasher.update(&buffer[..read]);
256 size += read as u64;
257 }
258 output
259 .sync_all()
260 .map_err(|error| format!("cannot sync {}: {error}", dest.display()))?;
261 let digest = hex::encode(hasher.finalize());
262 if size != row.size || digest != row.sha256 {
263 drop(output);
264 std::fs::remove_file(dest)
265 .map_err(|error| format!("cannot remove {}: {error}", dest.display()))?;
266 return Ok(Err(
267 "the bytes do not match the recorded size or digest".into()
268 ));
269 }
270 Ok(Ok(()))
271}
272
273/// Writes a new file with mode 0600 and syncs it. Used for `board.json`.
274fn write_new(path: &Path, bytes: &[u8]) -> Result<(), String> {
275 let mut file = OpenOptions::new()
276 .write(true)
277 .create_new(true)
278 .mode(0o600)
279 .open(path)
280 .map_err(|error| format!("cannot create {}: {error}", path.display()))?;
281 file.write_all(bytes)
282 .and_then(|()| file.sync_all())
283 .map_err(|error| format!("cannot write {}: {error}", path.display()))
284}
285
286#[cfg(test)]
287mod tests {
288 use super::*;
289
290 #[test]
291 fn export_refuses_a_non_empty_out_directory() {
292 let dir = tempfile::tempdir().expect("temp dir");
293 std::fs::write(dir.path().join("keep.txt"), b"x").expect("seed file");
294 let error = prepare_out(dir.path()).expect_err("non-empty must be refused");
295 assert!(error.contains("is not empty"), "got: {error}");
296 let empty = dir.path().join("fresh");
297 prepare_out(&empty).expect("a missing directory is created");
298 assert!(empty.is_dir());
299 }
300}