2026-03-04 23:55:08 +01:00
|
|
|
use crate::application::services::file_retrieval_service::FileRetrievalService;
|
|
|
|
|
use crate::application::services::folder_service::FolderService;
|
2025-04-02 01:22:05 +02:00
|
|
|
use crate::{
|
|
|
|
|
application::dtos::file_dto::FileDto,
|
2026-02-08 13:40:23 +01:00
|
|
|
application::ports::file_ports::FileRetrievalUseCase,
|
2026-05-20 15:39:53 +02:00
|
|
|
application::ports::folder_ports::FolderUseCase,
|
2026-02-08 13:40:23 +01:00
|
|
|
application::ports::zip_ports::ZipPort,
|
2026-02-14 01:29:34 +01:00
|
|
|
common::errors::{DomainError, ErrorKind, Result},
|
2025-04-02 01:22:05 +02:00
|
|
|
};
|
2026-02-23 23:11:55 +01:00
|
|
|
use async_zip::base::write::ZipFileWriter;
|
|
|
|
|
use async_zip::{Compression, ZipEntryBuilder};
|
2026-02-22 22:29:07 +01:00
|
|
|
use futures::StreamExt;
|
2026-02-25 10:28:34 +01:00
|
|
|
use futures::io::AsyncWriteExt as FuturesWriteExt;
|
2026-02-24 12:18:38 +01:00
|
|
|
use std::collections::HashMap;
|
2025-04-02 01:22:05 +02:00
|
|
|
use std::sync::Arc;
|
2026-02-22 22:29:07 +01:00
|
|
|
use tempfile::NamedTempFile;
|
2026-02-14 01:29:34 +01:00
|
|
|
use thiserror::Error;
|
2026-02-23 23:11:55 +01:00
|
|
|
use tokio::io::BufWriter;
|
|
|
|
|
use tokio_util::compat::Compat;
|
2026-02-14 01:29:34 +01:00
|
|
|
use tracing::*;
|
2025-04-02 01:22:05 +02:00
|
|
|
|
2026-02-12 09:41:25 +01:00
|
|
|
/// Error related to ZIP file creation
|
2025-04-02 01:22:05 +02:00
|
|
|
#[derive(Debug, Error)]
|
|
|
|
|
pub enum ZipError {
|
2026-02-12 09:41:25 +01:00
|
|
|
#[error("IO error: {0}")]
|
2025-04-02 01:22:05 +02:00
|
|
|
IoError(#[from] std::io::Error),
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-02-12 09:41:25 +01:00
|
|
|
#[error("ZIP error: {0}")]
|
2026-02-23 23:11:55 +01:00
|
|
|
AsyncZipError(#[from] async_zip::error::ZipError),
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-02-12 09:41:25 +01:00
|
|
|
#[error("Error reading file: {0}")]
|
2025-04-02 01:22:05 +02:00
|
|
|
FileReadError(String),
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-02-12 09:41:25 +01:00
|
|
|
#[error("Error getting folder contents: {0}")]
|
2025-04-02 01:22:05 +02:00
|
|
|
FolderContentsError(String),
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-02-12 09:41:25 +01:00
|
|
|
#[error("Folder not found: {0}")]
|
2025-04-02 01:22:05 +02:00
|
|
|
FolderNotFound(String),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl From<ZipError> for DomainError {
|
|
|
|
|
fn from(err: ZipError) -> Self {
|
|
|
|
|
DomainError::new(ErrorKind::InternalError, "zip_service", err.to_string())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-23 23:11:55 +01:00
|
|
|
/// Type alias for the fully-async ZIP writer backed by a buffered tokio file.
|
|
|
|
|
type AsyncZipWriter = ZipFileWriter<Compat<BufWriter<tokio::fs::File>>>;
|
2025-04-02 01:22:05 +02:00
|
|
|
|
2026-06-11 13:19:29 +00:00
|
|
|
/// One planned archive entry, in final ZIP order.
|
|
|
|
|
enum ZipPlanEntry {
|
|
|
|
|
/// Directory entry (Stored, zero-length body).
|
|
|
|
|
Dir(String),
|
|
|
|
|
/// File entry: ZIP-relative path + file id to stream from the blob store.
|
|
|
|
|
File { zip_path: String, file_id: String },
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Message protocol from the prefetch task to the ZIP writer. For each
|
|
|
|
|
/// planned file, in order: zero or more `Chunk`s, then exactly one `End`;
|
|
|
|
|
/// `Err` aborts the whole archive.
|
|
|
|
|
enum Prefetched {
|
|
|
|
|
Chunk(bytes::Bytes),
|
|
|
|
|
End,
|
|
|
|
|
Err(String),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Bound on the prefetch channel (messages of ≤ ~64 KB blob-stream chunks):
|
|
|
|
|
/// ~4 MiB of read-ahead. Enough to hide the per-file open latency of the
|
|
|
|
|
/// blob store (PG lookup + backend round-trip — significant on S3/Azure)
|
|
|
|
|
/// behind the deflate of the previous entry, while keeping RAM flat.
|
|
|
|
|
const PREFETCH_BUFFER_CHUNKS: usize = 64;
|
|
|
|
|
|
2026-02-22 22:29:07 +01:00
|
|
|
/// Service for creating ZIP files.
|
|
|
|
|
///
|
2026-02-23 23:11:55 +01:00
|
|
|
/// Uses `async_zip` for fully-async archive creation. Every write (headers,
|
|
|
|
|
/// compressed chunk data, central directory) goes through
|
|
|
|
|
/// `tokio::io::BufWriter` → `tokio::fs::File`, so **no Tokio worker is ever
|
|
|
|
|
/// blocked** by disk I/O or compression.
|
2026-06-11 13:19:29 +00:00
|
|
|
///
|
|
|
|
|
/// Archive creation is a 2-stage pipeline: a prefetch task reads file
|
|
|
|
|
/// content from the blob store ahead of the writer, so the next file's
|
|
|
|
|
/// read latency overlaps the current file's compression instead of adding
|
|
|
|
|
/// to it. The ZIP entries themselves are still written strictly in order
|
|
|
|
|
/// (the format requires it).
|
2025-04-02 01:22:05 +02:00
|
|
|
pub struct ZipService {
|
2026-03-03 15:36:42 +00:00
|
|
|
file_service: Arc<FileRetrievalService>,
|
|
|
|
|
folder_service: Arc<FolderService>,
|
2025-04-02 01:22:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl ZipService {
|
2026-02-22 22:29:07 +01:00
|
|
|
/// Creates a new instance of the ZIP service
|
2026-02-14 01:29:34 +01:00
|
|
|
pub fn new(
|
2026-03-03 15:36:42 +00:00
|
|
|
file_service: Arc<FileRetrievalService>,
|
|
|
|
|
folder_service: Arc<FolderService>,
|
2026-02-14 01:29:34 +01:00
|
|
|
) -> Self {
|
2025-04-02 01:22:05 +02:00
|
|
|
Self {
|
|
|
|
|
file_service,
|
|
|
|
|
folder_service,
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-02-22 22:29:07 +01:00
|
|
|
/// Creates a ZIP file backed by a temporary file, containing the contents
|
2026-02-23 23:11:55 +01:00
|
|
|
/// of a folder and all its subfolders. Returns the `NamedTempFile` so the
|
2026-02-22 22:29:07 +01:00
|
|
|
/// caller can stream it and let the OS clean up on drop.
|
2026-02-24 12:18:38 +01:00
|
|
|
///
|
|
|
|
|
/// Uses **2 SQL queries** (ltree `<@`) to fetch the entire subtree instead
|
|
|
|
|
/// of the previous N+1 BFS traversal.
|
2026-02-22 22:29:07 +01:00
|
|
|
pub async fn create_folder_zip(
|
|
|
|
|
&self,
|
|
|
|
|
folder_id: &str,
|
|
|
|
|
folder_name: &str,
|
|
|
|
|
) -> Result<NamedTempFile> {
|
2026-02-14 01:29:34 +01:00
|
|
|
info!(
|
|
|
|
|
"Creating ZIP for folder: {} (ID: {})",
|
|
|
|
|
folder_name, folder_id
|
|
|
|
|
);
|
|
|
|
|
|
2026-02-24 12:18:38 +01:00
|
|
|
// Verify the folder exists and get its path for prefix stripping
|
|
|
|
|
let root_folder = match self.folder_service.get_folder(folder_id).await {
|
|
|
|
|
Ok(f) => f,
|
2025-04-02 01:22:05 +02:00
|
|
|
Err(e) => {
|
2026-02-12 09:41:25 +01:00
|
|
|
error!("Error getting folder {}: {}", folder_id, e);
|
2025-04-02 01:22:05 +02:00
|
|
|
return Err(ZipError::FolderNotFound(folder_id.to_string()).into());
|
|
|
|
|
}
|
|
|
|
|
};
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-02-26 00:07:10 +01:00
|
|
|
// ── 1. Bulk-fetch folder tree (small — one entry per folder) ────
|
2026-02-24 12:18:38 +01:00
|
|
|
let all_folders = self
|
|
|
|
|
.folder_service
|
|
|
|
|
.list_subtree_folders(folder_id)
|
2026-02-23 23:11:55 +01:00
|
|
|
.await
|
2026-02-25 10:28:34 +01:00
|
|
|
.map_err(|e| ZipError::FolderContentsError(format!("subtree folders: {}", e)))?;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-02-26 00:07:10 +01:00
|
|
|
// ── 2. Stream files from DB cursor — O(1) per row ───────────────
|
|
|
|
|
let mut file_stream = self
|
2026-02-24 12:18:38 +01:00
|
|
|
.file_service
|
2026-02-26 00:07:10 +01:00
|
|
|
.stream_files_in_subtree(folder_id)
|
2026-02-24 12:18:38 +01:00
|
|
|
.await
|
2026-02-25 10:28:34 +01:00
|
|
|
.map_err(|e| ZipError::FolderContentsError(format!("subtree files: {}", e)))?;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-02-26 00:07:10 +01:00
|
|
|
// Group files by folder_id incrementally from the stream
|
2026-02-24 12:18:38 +01:00
|
|
|
let mut files_by_folder: HashMap<String, Vec<FileDto>> =
|
|
|
|
|
HashMap::with_capacity(all_folders.len());
|
2026-02-26 00:07:10 +01:00
|
|
|
while let Some(file) = file_stream.next().await {
|
|
|
|
|
let file =
|
|
|
|
|
file.map_err(|e| ZipError::FolderContentsError(format!("subtree file: {}", e)))?;
|
2026-02-24 12:18:38 +01:00
|
|
|
let fid = file.folder_id.clone().unwrap_or_default();
|
|
|
|
|
files_by_folder.entry(fid).or_default().push(file);
|
2025-04-02 01:22:05 +02:00
|
|
|
}
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-02-26 00:07:10 +01:00
|
|
|
info!(
|
|
|
|
|
"ZIP subtree: {} folders, {} files",
|
|
|
|
|
all_folders.len(),
|
|
|
|
|
files_by_folder.values().map(|v| v.len()).sum::<usize>()
|
|
|
|
|
);
|
|
|
|
|
|
2026-02-24 12:18:38 +01:00
|
|
|
// ── 3. Build a mapping: folder_id → ZIP-relative path ────────────
|
|
|
|
|
//
|
|
|
|
|
// The root folder's DB path is e.g. "/users/alice/Documents".
|
|
|
|
|
// We want ZIP entries relative to `folder_name`, so we strip the
|
|
|
|
|
// root prefix and prepend `folder_name`.
|
|
|
|
|
let root_path = root_folder.path.trim_end_matches('/');
|
|
|
|
|
let folder_zip_path = |db_path: &str| -> String {
|
|
|
|
|
let db_path = db_path.trim_end_matches('/');
|
|
|
|
|
if db_path == root_path {
|
|
|
|
|
folder_name.to_string()
|
|
|
|
|
} else {
|
|
|
|
|
let suffix = db_path
|
|
|
|
|
.strip_prefix(root_path)
|
|
|
|
|
.unwrap_or(db_path)
|
|
|
|
|
.trim_start_matches('/');
|
|
|
|
|
format!("{}/{}", folder_name, suffix)
|
|
|
|
|
}
|
|
|
|
|
};
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-06-11 13:19:29 +00:00
|
|
|
// ── 4. Plan the archive (folders are already sorted by path) ─────
|
|
|
|
|
let mut plan: Vec<ZipPlanEntry> = Vec::new();
|
|
|
|
|
for folder in &all_folders {
|
|
|
|
|
let zip_dir = format!("{}/", folder_zip_path(&folder.path));
|
|
|
|
|
plan.push(ZipPlanEntry::Dir(zip_dir.clone()));
|
|
|
|
|
if let Some(files) = files_by_folder.get(&folder.id) {
|
|
|
|
|
for file in files {
|
|
|
|
|
plan.push(ZipPlanEntry::File {
|
|
|
|
|
zip_path: format!("{}{}", zip_dir, file.name),
|
|
|
|
|
file_id: file.id.to_string(),
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ── 5. Open the temp file + ZIP writer ───────────────────────────
|
2026-02-24 12:18:38 +01:00
|
|
|
let temp = NamedTempFile::new().map_err(ZipError::IoError)?;
|
|
|
|
|
let tokio_file = tokio::fs::File::create(temp.path())
|
|
|
|
|
.await
|
|
|
|
|
.map_err(ZipError::IoError)?;
|
|
|
|
|
let buf_writer = BufWriter::with_capacity(256 * 1024, tokio_file);
|
|
|
|
|
let mut zip = ZipFileWriter::with_tokio(buf_writer);
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-06-11 13:19:29 +00:00
|
|
|
// ── 6. Write entries: 2-stage pipeline ───────────────────────────
|
|
|
|
|
// The prefetch task reads blob streams for the planned files, in
|
|
|
|
|
// order, ahead of the writer — the next file's blob-store latency
|
|
|
|
|
// overlaps the current file's deflate. If the writer bails out,
|
|
|
|
|
// dropping the receiver makes the prefetcher's next send fail and
|
|
|
|
|
// it stops on its own.
|
|
|
|
|
let file_ids: Vec<String> = plan
|
|
|
|
|
.iter()
|
|
|
|
|
.filter_map(|entry| match entry {
|
|
|
|
|
ZipPlanEntry::File { file_id, .. } => Some(file_id.clone()),
|
|
|
|
|
ZipPlanEntry::Dir(_) => None,
|
|
|
|
|
})
|
|
|
|
|
.collect();
|
|
|
|
|
let (tx, mut rx) = tokio::sync::mpsc::channel::<Prefetched>(PREFETCH_BUFFER_CHUNKS);
|
|
|
|
|
let _prefetcher = tokio::spawn(Self::prefetch_files(
|
|
|
|
|
self.file_service.clone(),
|
|
|
|
|
file_ids,
|
|
|
|
|
tx,
|
|
|
|
|
));
|
|
|
|
|
|
|
|
|
|
for entry in &plan {
|
|
|
|
|
match entry {
|
|
|
|
|
ZipPlanEntry::Dir(zip_dir) => {
|
|
|
|
|
let dir_entry =
|
|
|
|
|
ZipEntryBuilder::new(zip_dir.clone().into(), Compression::Stored);
|
|
|
|
|
match zip.write_entry_whole(dir_entry, &[]).await {
|
|
|
|
|
Ok(()) => debug!("Folder added to ZIP: {}", zip_dir),
|
|
|
|
|
Err(e) => {
|
|
|
|
|
warn!("Could not add folder entry (may already exist): {}", e);
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-04-02 01:22:05 +02:00
|
|
|
}
|
2026-06-11 13:19:29 +00:00
|
|
|
ZipPlanEntry::File { zip_path, .. } => {
|
|
|
|
|
Self::write_prefetched_file(&mut zip, zip_path, &mut rx).await?;
|
2025-04-02 01:22:05 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-06-11 13:19:29 +00:00
|
|
|
// ── 7. Finalize ──────────────────────────────────────────────────
|
2026-02-24 12:18:38 +01:00
|
|
|
let mut compat_writer = zip.close().await.map_err(ZipError::AsyncZipError)?;
|
|
|
|
|
compat_writer.close().await.map_err(ZipError::IoError)?;
|
|
|
|
|
|
|
|
|
|
Ok(temp)
|
2025-04-02 01:22:05 +02:00
|
|
|
}
|
2026-02-14 01:29:34 +01:00
|
|
|
|
2026-06-11 13:19:29 +00:00
|
|
|
/// Prefetch stage: streams each planned file's content from the blob
|
|
|
|
|
/// store, in plan order, into the bounded channel. Stops on the first
|
|
|
|
|
/// read error (after forwarding it) or when the writer hangs up.
|
|
|
|
|
async fn prefetch_files(
|
|
|
|
|
file_service: Arc<FileRetrievalService>,
|
|
|
|
|
file_ids: Vec<String>,
|
|
|
|
|
tx: tokio::sync::mpsc::Sender<Prefetched>,
|
|
|
|
|
) {
|
|
|
|
|
for file_id in file_ids {
|
|
|
|
|
let stream = match file_service.get_file_stream(&file_id).await {
|
|
|
|
|
Ok(s) => s,
|
|
|
|
|
Err(e) => {
|
|
|
|
|
error!("Error opening file stream {}: {}", file_id, e);
|
|
|
|
|
let _ = tx
|
|
|
|
|
.send(Prefetched::Err(format!(
|
|
|
|
|
"Error streaming file {}: {}",
|
|
|
|
|
file_id, e
|
|
|
|
|
)))
|
|
|
|
|
.await;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let mut stream = std::pin::Pin::from(stream);
|
|
|
|
|
while let Some(chunk_result) = stream.next().await {
|
|
|
|
|
let message = match chunk_result {
|
|
|
|
|
Ok(bytes) => Prefetched::Chunk(bytes),
|
|
|
|
|
Err(e) => Prefetched::Err(format!("Error streaming file {}: {}", file_id, e)),
|
|
|
|
|
};
|
|
|
|
|
let abort = matches!(message, Prefetched::Err(_));
|
|
|
|
|
if tx.send(message).await.is_err() || abort {
|
|
|
|
|
return; // writer gone, or fatal read error forwarded
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if tx.send(Prefetched::End).await.is_err() {
|
|
|
|
|
return; // writer gone
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Writer stage: drains one file's prefetched chunks into a Deflate
|
|
|
|
|
/// ZIP entry. Peak memory stays bounded by the channel, independent
|
|
|
|
|
/// of individual file sizes.
|
|
|
|
|
async fn write_prefetched_file(
|
2026-02-23 23:11:55 +01:00
|
|
|
zip: &mut AsyncZipWriter,
|
2026-06-11 13:19:29 +00:00
|
|
|
zip_path: &str,
|
|
|
|
|
rx: &mut tokio::sync::mpsc::Receiver<Prefetched>,
|
2025-04-02 01:22:05 +02:00
|
|
|
) -> Result<()> {
|
2026-06-11 13:19:29 +00:00
|
|
|
info!("Adding file to ZIP: {}", zip_path);
|
2026-02-22 22:29:07 +01:00
|
|
|
|
2026-06-11 13:19:29 +00:00
|
|
|
let entry = ZipEntryBuilder::new(zip_path.to_string().into(), Compression::Deflate);
|
2026-02-23 23:11:55 +01:00
|
|
|
let mut entry_writer = zip
|
|
|
|
|
.write_entry_stream(entry)
|
|
|
|
|
.await
|
|
|
|
|
.map_err(ZipError::AsyncZipError)?;
|
2026-02-22 22:29:07 +01:00
|
|
|
|
2026-06-11 13:19:29 +00:00
|
|
|
loop {
|
|
|
|
|
match rx.recv().await {
|
|
|
|
|
Some(Prefetched::Chunk(bytes)) => {
|
|
|
|
|
entry_writer
|
|
|
|
|
.write_all(&bytes)
|
|
|
|
|
.await
|
|
|
|
|
.map_err(ZipError::IoError)?;
|
|
|
|
|
}
|
|
|
|
|
Some(Prefetched::End) => break,
|
|
|
|
|
Some(Prefetched::Err(message)) => {
|
|
|
|
|
// Close the partially-written entry before bailing out.
|
|
|
|
|
let _ = entry_writer.close().await;
|
|
|
|
|
return Err(ZipError::FileReadError(message).into());
|
|
|
|
|
}
|
|
|
|
|
None => {
|
|
|
|
|
let _ = entry_writer.close().await;
|
|
|
|
|
return Err(ZipError::FileReadError(format!(
|
|
|
|
|
"Prefetch stage ended unexpectedly while writing {}",
|
|
|
|
|
zip_path
|
|
|
|
|
))
|
|
|
|
|
.into());
|
|
|
|
|
}
|
2025-04-02 01:22:05 +02:00
|
|
|
}
|
|
|
|
|
}
|
2026-02-22 22:29:07 +01:00
|
|
|
|
2026-02-23 23:11:55 +01:00
|
|
|
// Finalize the entry (writes data descriptor with CRC + sizes)
|
|
|
|
|
entry_writer
|
|
|
|
|
.close()
|
|
|
|
|
.await
|
|
|
|
|
.map_err(ZipError::AsyncZipError)?;
|
|
|
|
|
|
2026-06-11 13:19:29 +00:00
|
|
|
debug!("File added to ZIP: {}", zip_path);
|
2026-02-22 22:29:07 +01:00
|
|
|
Ok(())
|
2025-04-02 01:22:05 +02:00
|
|
|
}
|
2026-02-08 13:40:23 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ─── Port implementation ─────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
impl ZipPort for ZipService {
|
|
|
|
|
async fn create_folder_zip(
|
|
|
|
|
&self,
|
|
|
|
|
folder_id: &str,
|
|
|
|
|
folder_name: &str,
|
2026-02-22 22:29:07 +01:00
|
|
|
) -> std::result::Result<NamedTempFile, DomainError> {
|
2026-02-08 13:40:23 +01:00
|
|
|
self.create_folder_zip(folder_id, folder_name).await
|
|
|
|
|
}
|
2026-02-14 01:29:34 +01:00
|
|
|
}
|