| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::collections::HashMap; |
| 15 | use std::io::{BufWriter, Write}; |
| 16 | use std::path::{Path, PathBuf}; |
| 17 | use std::sync::{LazyLock, Mutex, PoisonError}; |
| 18 | use std::time::Duration; |
| 19 | |
| 20 | use forge_core::issues::IssueFilter; |
| 21 | use forge_core::store::exports::{DataExport, ExportState}; |
| 22 | use forge_core::time::now_stamp; |
| 23 | use forge_core::{IssueSort, Repo, User}; |
| 24 | use forge_git::backup::bundle_create; |
| 25 | use serde_json::{Value, json}; |
| 26 | use tokio::sync::watch; |
| 27 | |
| 28 | use crate::state::AppState; |
| 29 | |
| 30 | |
| 31 | pub const EXPORT_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60); |
| 32 | |
| 33 | pub const EXPORT_TTL_DAYS: u64 = 7; |
| 34 | const PAGE: u32 = 100; |
| 35 | |
| 36 | static HUB: LazyLock<Mutex<HashMap<String, watch::Sender<u64>>>> = |
| 37 | LazyLock::new(|| Mutex::new(HashMap::new())); |
| 38 | |
| 39 | |
| 40 | pub fn subscribe(user_id: &str) -> watch::Receiver<u64> { |
| 41 | let mut hub = HUB.lock().unwrap_or_else(PoisonError::into_inner); |
| 42 | |
| 43 | hub.retain(|_, tx| tx.receiver_count() > 0); |
| 44 | hub.entry(user_id.to_owned()) |
| 45 | .or_insert_with(|| watch::channel(0).0) |
| 46 | .subscribe() |
| 47 | } |
| 48 | |
| 49 | fn bump(user_id: &str) { |
| 50 | let mut hub = HUB.lock().unwrap_or_else(PoisonError::into_inner); |
| 51 | if let Some(tx) = hub.get(user_id) { |
| 52 | tx.send_modify(|n| *n = n.wrapping_add(1)); |
| 53 | if tx.receiver_count() == 0 { |
| 54 | hub.remove(user_id); |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub fn export_dir(state: &AppState) -> PathBuf { |
| 60 | state.config.data_dir.join("exports") |
| 61 | } |
| 62 | |
| 63 | pub fn archive_path(state: &AppState, id: &str) -> PathBuf { |
| 64 | export_dir(state).join(format!("{id}.tar.gz")) |
| 65 | } |
| 66 | |
| 67 | |
| 68 | |
| 69 | pub async fn start(state: &AppState, user: &User) -> forge_core::Result<DataExport> { |
| 70 | sweep_expired(state).await; |
| 71 | if let Some(running) = state |
| 72 | .store |
| 73 | .list_exports(&user.id) |
| 74 | .await? |
| 75 | .into_iter() |
| 76 | .find(|e| e.state == ExportState::Building) |
| 77 | { |
| 78 | return Ok(running); |
| 79 | } |
| 80 | let export = state.store.create_export(&user.id, EXPORT_TTL).await?; |
| 81 | let task_state = state.clone(); |
| 82 | let task_user = user.clone(); |
| 83 | let id = export.id.clone(); |
| 84 | tokio::spawn(async move { |
| 85 | run(&task_state, &task_user, &id).await; |
| 86 | }); |
| 87 | Ok(export) |
| 88 | } |
| 89 | |
| 90 | async fn run(state: &AppState, user: &User, id: &str) { |
| 91 | let outcome = build(state, user, id).await; |
| 92 | match outcome { |
| 93 | Ok(size) => { |
| 94 | if let Err(e) = state |
| 95 | .store |
| 96 | .mark_export_ready(id, i64::try_from(size).unwrap_or(i64::MAX), EXPORT_TTL) |
| 97 | .await |
| 98 | { |
| 99 | tracing::error!(error = %e, "export: could not mark the export ready"); |
| 100 | } |
| 101 | notify_ready(state, user, id).await; |
| 102 | } |
| 103 | Err(message) => { |
| 104 | tracing::error!(error = %message, export_id = id, "export failed"); |
| 105 | let _ = tokio::fs::remove_file(archive_path(state, id)).await; |
| 106 | if let Err(e) = state.store.mark_export_failed(id, &message).await { |
| 107 | tracing::error!(error = %e, "export: could not record a failure"); |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | bump(&user.id); |
| 112 | } |
| 113 | |
| 114 | async fn notify_ready(state: &AppState, user: &User, id: &str) { |
| 115 | let Some(email) = user.email.as_deref().filter(|e| !e.is_empty()) else { |
| 116 | return; |
| 117 | }; |
| 118 | let base = state.config.base_url.trim_end_matches('/'); |
| 119 | let body = format!( |
| 120 | "Your data export is ready.\n\nDownload it at {base}/settings/export (you must be signed in). \ |
| 121 | It is removed after {EXPORT_TTL_DAYS} days.\n" |
| 122 | ); |
| 123 | if let Err(e) = crate::mail::enqueue( |
| 124 | state, |
| 125 | &format!("export:{id}"), |
| 126 | forge_core::mail::MailKind::Other, |
| 127 | Some(&user.id), |
| 128 | email, |
| 129 | "Your data export is ready", |
| 130 | &body, |
| 131 | ) |
| 132 | .await |
| 133 | { |
| 134 | tracing::warn!(error = %e, "export: could not queue the ready mail"); |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | |
| 139 | async fn build(state: &AppState, user: &User, id: &str) -> Result<u64, String> { |
| 140 | let dir = export_dir(state); |
| 141 | tokio::fs::create_dir_all(&dir) |
| 142 | .await |
| 143 | .map_err(|e| e.to_string())?; |
| 144 | let work = dir.join(format!("{id}.work")); |
| 145 | let _ = tokio::fs::remove_dir_all(&work).await; |
| 146 | tokio::fs::create_dir_all(work.join("repos")) |
| 147 | .await |
| 148 | .map_err(|e| e.to_string())?; |
| 149 | let result = stage_and_pack(state, user, id, &work).await; |
| 150 | let _ = tokio::fs::remove_dir_all(&work).await; |
| 151 | result |
| 152 | } |
| 153 | |
| 154 | async fn stage_and_pack( |
| 155 | state: &AppState, |
| 156 | user: &User, |
| 157 | id: &str, |
| 158 | work: &Path, |
| 159 | ) -> Result<u64, String> { |
| 160 | write_json(&work.join("profile.json"), &profile_json(user)).await?; |
| 161 | let repos = state |
| 162 | .store |
| 163 | .list_repos_by_owner(&user.id) |
| 164 | .await |
| 165 | .map_err(|e| e.to_string())?; |
| 166 | for repo in &repos { |
| 167 | let repo_dir = work.join("repos").join(&repo.name); |
| 168 | tokio::fs::create_dir_all(&repo_dir) |
| 169 | .await |
| 170 | .map_err(|e| e.to_string())?; |
| 171 | stage_repo(state, repo, &repo_dir).await?; |
| 172 | } |
| 173 | let target = archive_path(state, id); |
| 174 | let partial = target.with_extension("part"); |
| 175 | let (work_buf, partial_buf, name) = ( |
| 176 | work.to_path_buf(), |
| 177 | partial.clone(), |
| 178 | format!("forge-export-{}", user.username), |
| 179 | ); |
| 180 | tokio::task::spawn_blocking(move || pack(&work_buf, &partial_buf, &name)) |
| 181 | .await |
| 182 | .map_err(|e| e.to_string())??; |
| 183 | tokio::fs::rename(&partial, &target) |
| 184 | .await |
| 185 | .map_err(|e| e.to_string())?; |
| 186 | let meta = tokio::fs::metadata(&target) |
| 187 | .await |
| 188 | .map_err(|e| e.to_string())?; |
| 189 | Ok(meta.len()) |
| 190 | } |
| 191 | |
| 192 | fn pack(work: &Path, out: &Path, top: &str) -> Result<(), String> { |
| 193 | use std::os::unix::fs::OpenOptionsExt; |
| 194 | let file = std::fs::OpenOptions::new() |
| 195 | .write(true) |
| 196 | .create(true) |
| 197 | .truncate(true) |
| 198 | .mode(0o600) |
| 199 | .open(out) |
| 200 | .map_err(|e| e.to_string())?; |
| 201 | let gz = flate2::write::GzEncoder::new(file, flate2::Compression::default()); |
| 202 | let mut tar = tar::Builder::new(gz); |
| 203 | tar.append_dir_all(top, work).map_err(|e| e.to_string())?; |
| 204 | let gz = tar.into_inner().map_err(|e| e.to_string())?; |
| 205 | gz.finish().map_err(|e| e.to_string())?; |
| 206 | Ok(()) |
| 207 | } |
| 208 | |
| 209 | async fn write_json(path: &Path, value: &Value) -> Result<(), String> { |
| 210 | let text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?; |
| 211 | tokio::fs::write(path, text) |
| 212 | .await |
| 213 | .map_err(|e| e.to_string()) |
| 214 | } |
| 215 | |
| 216 | |
| 217 | |
| 218 | fn write_array_item( |
| 219 | out: &mut impl Write, |
| 220 | written: &mut usize, |
| 221 | value: &Value, |
| 222 | ) -> Result<(), String> { |
| 223 | let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?; |
| 224 | let lead: &[u8] = if *written == 0 { b"[\n " } else { b",\n " }; |
| 225 | out.write_all(lead) |
| 226 | .and_then(|()| out.write_all(text.replace('\n', "\n ").as_bytes())) |
| 227 | .map_err(|e| e.to_string())?; |
| 228 | *written += 1; |
| 229 | Ok(()) |
| 230 | } |
| 231 | |
| 232 | |
| 233 | pub fn profile_json(user: &User) -> Value { |
| 234 | json!({ |
| 235 | "username": user.username, |
| 236 | "display_name": user.display_name, |
| 237 | "email": user.email, |
| 238 | "about": user.about, |
| 239 | "created_at": user.created_at, |
| 240 | "timezone": user.timezone, |
| 241 | "language": user.language, |
| 242 | "theme": user.theme, |
| 243 | "exported_at": now_stamp(), |
| 244 | }) |
| 245 | } |
| 246 | |
| 247 | async fn stage_repo(state: &AppState, repo: &Repo, dir: &Path) -> Result<(), String> { |
| 248 | let git_dir = |
| 249 | forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?; |
| 250 | let bundled = bundle_create(&state.git, &git_dir, &dir.join("repo.bundle")) |
| 251 | .await |
| 252 | .map_err(|e| format!("bundling {}: {e}", repo.name))? |
| 253 | .is_some(); |
| 254 | |
| 255 | let labels = state |
| 256 | .store |
| 257 | .list_labels(&repo.id) |
| 258 | .await |
| 259 | .map_err(|e| e.to_string())?; |
| 260 | let milestones = state |
| 261 | .store |
| 262 | .list_milestones(&repo.id, None) |
| 263 | .await |
| 264 | .map_err(|e| e.to_string())?; |
| 265 | let meta = json!({ |
| 266 | "name": repo.name, |
| 267 | "description": repo.description, |
| 268 | "visibility": repo.visibility.as_str(), |
| 269 | "default_branch": repo.default_branch, |
| 270 | "created_at": repo.created_at, |
| 271 | "archived": repo.archived, |
| 272 | "has_bundle": bundled, |
| 273 | "labels": labels.iter().map(|l| json!({"name": l.name, "color": l.color, "description": l.description})).collect::<Vec<_>>(), |
| 274 | "milestones": milestones.iter().map(|m| json!({ |
| 275 | "title": m.title, "description": m.description, "due_on": m.due_on, |
| 276 | "state": m.state.as_str(), "created_at": m.created_at, "closed_at": m.closed_at, |
| 277 | })).collect::<Vec<_>>(), |
| 278 | }); |
| 279 | write_json(&dir.join("repo.json"), &meta).await?; |
| 280 | |
| 281 | |
| 282 | let mut out = |
| 283 | BufWriter::new(std::fs::File::create(dir.join("issues.json")).map_err(|e| e.to_string())?); |
| 284 | let mut written = 0usize; |
| 285 | let mut page = 1; |
| 286 | loop { |
| 287 | let filter = IssueFilter { |
| 288 | state: None, |
| 289 | sort: IssueSort::Oldest, |
| 290 | page, |
| 291 | per_page: PAGE, |
| 292 | ..IssueFilter::default() |
| 293 | }; |
| 294 | let (items, total) = state |
| 295 | .store |
| 296 | .list_issues(&repo.id, &filter) |
| 297 | .await |
| 298 | .map_err(|e| e.to_string())?; |
| 299 | let got = items.len(); |
| 300 | for item in items { |
| 301 | let comments = state |
| 302 | .store |
| 303 | .list_comments(&item.issue.id) |
| 304 | .await |
| 305 | .map_err(|e| e.to_string())?; |
| 306 | let names = state |
| 307 | .store |
| 308 | .usernames_by_ids( |
| 309 | &comments |
| 310 | .iter() |
| 311 | .map(|c| c.author_id.clone()) |
| 312 | .collect::<Vec<_>>(), |
| 313 | ) |
| 314 | .await |
| 315 | .map_err(|e| e.to_string())?; |
| 316 | let names: HashMap<String, String> = |
| 317 | names.into_iter().map(|(k, (name, _))| (k, name)).collect(); |
| 318 | write_array_item( |
| 319 | &mut out, |
| 320 | &mut written, |
| 321 | &issue_json(&item, &comments, &names), |
| 322 | )?; |
| 323 | } |
| 324 | if got == 0 || (u64::from(page) * u64::from(PAGE)) >= total { |
| 325 | break; |
| 326 | } |
| 327 | page += 1; |
| 328 | } |
| 329 | |
| 330 | out.write_all(if written == 0 { b"[]" } else { b"\n]" }) |
| 331 | .and_then(|()| out.flush()) |
| 332 | .map_err(|e| e.to_string())?; |
| 333 | |
| 334 | let releases = state |
| 335 | .store |
| 336 | .list_releases(&repo.id) |
| 337 | .await |
| 338 | .map_err(|e| e.to_string())?; |
| 339 | let mut out = Vec::new(); |
| 340 | for r in releases { |
| 341 | let assets = state |
| 342 | .store |
| 343 | .list_release_assets(&r.id) |
| 344 | .await |
| 345 | .map_err(|e| e.to_string())?; |
| 346 | out.push(json!({ |
| 347 | "tag": r.tag, "title": r.title, "body": r.body, "draft": r.draft, |
| 348 | "prerelease": r.prerelease, "author": r.author_name, "target_oid": r.target_oid, |
| 349 | "created_at": r.created_at, "published_at": r.published_at, |
| 350 | "assets": assets.iter().map(|a| json!({ |
| 351 | "name": a.name, "size": a.size, "sha256": a.sha256, |
| 352 | "content_type": a.content_type, "downloads": a.download_count, |
| 353 | })).collect::<Vec<_>>(), |
| 354 | })); |
| 355 | } |
| 356 | write_json(&dir.join("releases.json"), &Value::Array(out)).await |
| 357 | } |
| 358 | |
| 359 | fn issue_json( |
| 360 | item: &forge_core::IssueListItem, |
| 361 | comments: &[forge_core::Comment], |
| 362 | names: &HashMap<String, String>, |
| 363 | ) -> Value { |
| 364 | let i = &item.issue; |
| 365 | json!({ |
| 366 | "number": i.number, |
| 367 | "title": i.title, |
| 368 | "body": i.body, |
| 369 | "state": i.state.as_str(), |
| 370 | "author": item.author, |
| 371 | "labels": item.labels.iter().map(|l| l.name.clone()).collect::<Vec<_>>(), |
| 372 | "assignees": item.assignees, |
| 373 | "created_at": i.created_at, |
| 374 | "closed_at": i.closed_at, |
| 375 | "comments": comments.iter().map(|c| json!({ |
| 376 | "author": names.get(&c.author_id).cloned().unwrap_or_default(), |
| 377 | "body": c.body, |
| 378 | "created_at": c.created_at, |
| 379 | })).collect::<Vec<_>>(), |
| 380 | }) |
| 381 | } |
| 382 | |
| 383 | |
| 384 | pub async fn sweep_expired(state: &AppState) { |
| 385 | let expired = match state.store.expired_exports(&now_stamp()).await { |
| 386 | Ok(rows) => rows, |
| 387 | Err(e) => { |
| 388 | tracing::warn!(error = %e, "export: could not list expired exports"); |
| 389 | return; |
| 390 | } |
| 391 | }; |
| 392 | for export in expired { |
| 393 | let path = archive_path(state, &export.id); |
| 394 | match tokio::fs::remove_file(&path).await { |
| 395 | Ok(()) => {} |
| 396 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} |
| 397 | Err(e) => { |
| 398 | tracing::warn!(error = %e, "export: could not remove an expired archive"); |
| 399 | continue; |
| 400 | } |
| 401 | } |
| 402 | if let Err(e) = state.store.delete_export(&export.id).await { |
| 403 | tracing::warn!(error = %e, "export: could not delete an expired export row"); |
| 404 | } |
| 405 | bump(&export.user_id); |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | |
| 410 | pub async fn delete_one(state: &AppState, export: &DataExport) -> forge_core::Result<()> { |
| 411 | match tokio::fs::remove_file(archive_path(state, &export.id)).await { |
| 412 | Ok(()) => {} |
| 413 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} |
| 414 | Err(e) => { |
| 415 | tracing::warn!(error = %e, "export: could not remove an archive"); |
| 416 | return Err(e.into()); |
| 417 | } |
| 418 | } |
| 419 | state.store.delete_export(&export.id).await?; |
| 420 | bump(&export.user_id); |
| 421 | Ok(()) |
| 422 | } |
| 423 | |
| 424 | |
| 425 | pub async fn on_boot(state: &AppState) { |
| 426 | if let Err(e) = state.store.fail_interrupted_exports().await { |
| 427 | tracing::error!(error = %e, "export: could not clean up interrupted exports"); |
| 428 | } |
| 429 | sweep_expired(state).await; |
| 430 | } |
| 431 | |
| 432 | #[cfg(test)] |
| 433 | mod tests; |