//! GET /export.zip: every note outside the trash, as markdown files in one zip, and the //! media files in a `media` folder that the notes' `/media/` links are pointed at. //! Notes in a notebook go into a folder named after it; unfiled notes sit at the root. use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use std::io::{BufWriter, Write}; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use std::time::{SystemTime, UNIX_EPOCH}; use bytes::Bytes; use http_body::Frame; use tokio::sync::mpsc; use topcoat::{ Result, context::{Cx, app_context}, router::{Body, header, route}, }; use loro::LoroDoc; use crate::export; use crate::hub::Hub; use crate::media::Media; use crate::store::{DocBytes, Notebook, Store}; use crate::zipout::{Deflated, ZipOut}; const MAX_NAME_CHARS: usize = 100; /// Most notes read and rendered together while exporting. const EXPORT_BATCH: usize = 2000; /// Bytes of stored notes read together, about: batches shrink for big notes, or a /// batch of huge notes would not fit in memory. const LOAD_BATCH_BYTES: usize = 64 << 20; /// Bytes of cached export markdown read and rendered together. const EXPORT_BATCH_BYTES: usize = 8 << 20; /// Bytes of the zip sent to the client at a time. const SEND_CHUNK: usize = 256 * 1024; /// GET /export.zip: a zip of the live markdown of every non-trashed note, and of every /// media file under `media/`. The zip is streamed while it is made, so the download /// starts at once and the server holds one batch of notes at a time, however many there /// are. #[route(GET "/export.zip")] pub async fn export_zip(cx: &Cx) -> Result<([(&'static str, String); 2], Body)> { let store = app_context::>(cx).clone(); let media = app_context::>(cx).clone(); let hub = app_context::>(cx).clone(); let (tx, rx) = mpsc::channel(8); tokio::spawn(async move { if let Err(err) = write_zip(&store, &media, &hub, tx.clone()).await { eprintln!("export failed: {err:#}"); let _ = tx.send(Err(std::io::Error::other(err))).await; } }); let (year, month, day) = utc_date(); let disposition = format!("attachment; filename=\"notes-{year:04}-{month:02}-{day:02}.zip\""); Ok(( [ (header::CONTENT_TYPE.as_str(), "application/zip".to_owned()), (header::CONTENT_DISPOSITION.as_str(), disposition), ], Body::new(ChannelBody(rx)), )) } type Chunk = std::io::Result; type Zip = ZipOut>; /// A note to export: its index in the file list, its path, its id and its stored bytes. type Job = (u32, String, String, DocBytes); /// Writes the export zip into `tx`. Each batch is rendered and compressed on every /// core while the next one is read, then appended. The media files follow the notes, /// one at a time. async fn write_zip(store: &Store, media: &Media, hub: &Hub, tx: mpsc::Sender) -> anyhow::Result<()> { let notes = store.list_notes().await?; let notebooks = store.list_notebooks().await?; let notebooks_by_id: HashMap<&str, &Notebook> = notebooks.iter().map(|nb| (nb.id.as_str(), nb)).collect(); // Links resolve by id: only their targets' titles are needed, not every note's. let titles = store.titles_of(store.link_targets().await?).await?; // The (id, path) of every note, in list order: the notes themselves are dropped. let mut files: Vec<(Box, Box)> = Vec::with_capacity(notes.len() + 1); { // Dropped before the export starts: at millions of notes they hold every path again. let mut folder_names: HashMap = HashMap::new(); let mut folder_taken = HashSet::new(); let mut file_taken = HashSet::new(); for note in ¬es { let folder = match note.notebook_id.as_deref().and_then(|id| notebooks_by_id.get(id)) { Some(nb) => folder_names .entry(nb.id.clone()) .or_insert_with(|| unique(&mut folder_taken, "", &sanitize(&nb.name))) .clone(), None => String::new(), }; let stem = unique(&mut file_taken, &folder, &sanitize(¬e.title)); let path = if folder.is_empty() { format!("{stem}.md") } else { format!("{folder}/{stem}.md") }; files.push((note.id.as_str().into(), path.into())); } } drop((notes, notebooks_by_id)); let titles = Arc::new(titles); let linking = Arc::new(store.linking_notes().await?); let mut zip: Zip = ZipOut::new(BufWriter::with_capacity(SEND_CHUNK, ChannelWriter(tx)), utc_date()); let mut rendering: Option>> = None; // Renders `jobs` while the previous batch is appended. let mut next = async |zip: Zip, jobs: Vec| -> anyhow::Result { let done = match rendering.take() { Some(handle) => Some(handle.await??), None => None, }; let (titles, linking) = (titles.clone(), linking.clone()); rendering = Some(tokio::task::spawn_blocking(move || render_files(jobs, &titles, &linking))); match done { Some(done) => finish_batch(store, zip, done).await, None => Ok(zip), } }; // Notes whose export markdown is cached and current come first, in one read. let index: HashMap<&str, usize> = files.iter().enumerate().map(|(i, (id, _))| (&**id, i)).collect(); let mut written = vec![false; files.len()]; let stale: HashSet = store.stale_snapshots().await?.into_iter().collect(); let mut cached = store.scan_export_texts(EXPORT_BATCH_BYTES)?; while let Some(batch) = cached.recv().await { let jobs: Vec = batch? .into_iter() .filter(|(id, _)| !stale.contains(id)) .filter_map(|(id, md)| { let i = *index.get(id.as_str())?; if std::mem::replace(&mut written[i], true) { return None; } let path = files[i].1.to_string(); let doc = DocBytes { snapshot: None, updates: Vec::new(), markdown: None, export: Some(md), upto_seq: 0 }; Some((i as u32, path, id, doc)) }) .collect(); zip = next(zip, jobs).await?; } // The rest from their stored docs, in batches. drop(index); let rest: Vec = (0..files.len() as u32).filter(|&i| !written[i as usize]).collect(); drop(written); // Sized by the notes read so far, starting at one: these are often the few huge ones. let (mut at, mut size) = (0, 1); while at < rest.len() { let batch = &rest[at..(at + size).min(rest.len())]; at += batch.len(); let ids: Vec = batch.iter().map(|&i| files[i as usize].0.to_string()).collect(); let docs = store.load_docs(&ids, &linking).await?; let bytes: usize = docs.iter().map(DocBytes::stored_len).sum(); size = (LOAD_BATCH_BYTES / (bytes / batch.len()).max(1)).clamp(1, EXPORT_BATCH); let jobs = batch.iter().zip(ids).zip(docs).map(|((&i, id), doc)| (i, files[i as usize].1.to_string(), id, doc)).collect(); zip = next(zip, jobs).await?; } drop(next); if let Some(handle) = rendering.take() { zip = finish_batch(store, zip, handle.await??).await?; } drop(rest); // Media, one file in memory at a time: each is read, stored and appended before the next. for name in media.list().await? { let bytes = tokio::fs::read(media.path(&name)).await?; let file = tokio::task::spawn_blocking(move || Deflated::fast(&bytes)).await??; let path = format!("media/{name}"); let index = files.len() as u32; files.push((name.as_str().into(), path.as_str().into())); zip = append(zip, vec![(index, path, file)]).await?; } // Takes, each joined from its closed parts, at the URL their embeds use. for id in media.takes().await? { let Some((joined, _)) = media.joined_take(&id, &hub.attached(&id)).await? else { continue }; let bytes = tokio::fs::read(&joined).await?; let file = tokio::task::spawn_blocking(move || Deflated::fast(&bytes)).await??; let path = format!("media/rec/{id}"); let index = files.len() as u32; files.push((id.as_str().into(), path.as_str().into())); zip = append(zip, vec![(index, path, file)]).await?; } tokio::task::spawn_blocking(move || -> anyhow::Result<()> { zip.finish(|i| &files[i as usize].1)?.into_inner().map_err(|e| e.into_error())?; Ok(()) }) .await? } /// Appends a rendered batch to the zip and caches the export markdown it rendered, so /// the next export of those notes needs no doc. async fn finish_batch(store: &Store, zip: Zip, done: Rendered) -> anyhow::Result { if !done.cache.is_empty() { store.put_export_texts(&done.cache).await?; } append(zip, done.files).await } /// Appends compressed files to the zip on a blocking thread: sending waits for the client. async fn append(mut zip: Zip, files: Vec<(u32, String, Deflated)>) -> anyhow::Result { tokio::task::spawn_blocking(move || { for (name, path, file) in files { zip.add(name, &path, file)?; } Ok(zip) }) .await? } /// Renders and compresses every `(path, id, bytes)` job on scoped threads, keeping the /// job order. Threads take the next job when done, so one huge note keeps one thread /// busy rather than holding back a share of the others. fn render_files(jobs: Vec, titles: &HashMap, linking: &HashSet) -> anyhow::Result { let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(jobs.len().max(1)); let next = std::sync::atomic::AtomicUsize::new(0); let (queue, next) = (&jobs, &next); let mut done: Vec<(usize, Deflated, Option)> = std::thread::scope(|scope| { let handles: Vec<_> = (0..threads) .map(|_| { scope.spawn(move || -> anyhow::Result)>> { let mut out = Vec::new(); loop { let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let Some((_, _, id, bytes)) = queue.get(i) else { return Ok(out) }; let (md, cache) = render(bytes, titles, linking, id)?; let md = media_links(&md, &queue[i].1); out.push((i, Deflated::new(md.as_bytes())?, cache)); } }) }) .collect(); let mut done = Vec::with_capacity(queue.len()); for handle in handles { done.extend(handle.join().map_err(|_| anyhow::anyhow!("export thread panicked"))??); } anyhow::Ok(done) })?; done.sort_unstable_by_key(|(i, _, _)| *i); let mut cache = Vec::new(); let mut files = Vec::with_capacity(done.len()); for ((name, path, id, bytes), (_, file, md)) in jobs.into_iter().zip(done) { files.push((name, path, file)); if let Some(md) = md { cache.push((id, bytes.upto_seq, md)); } } Ok(Rendered { files, cache }) } /// Points a note's `/media/` links at the zip's `media` folder, relative to the note's /// file: `media/` for a note at the root, `../media/` for one in a notebook folder. /// Plain text, so it also works on cached export markdown; the cache keeps `/media/`. fn media_links<'a>(md: &'a str, path: &str) -> Cow<'a, str> { if !md.contains("](/media/") { return Cow::Borrowed(md); } let to = if path.contains('/') { "../media/" } else { "media/" }; Cow::Owned(md.replace("](/media/", &format!("]({to}"))) } /// A batch of the export: its files in order, and export markdown to cache. struct Rendered { files: Vec<(u32, String, Deflated)>, cache: Vec<(String, i64, String)>, } /// Sends what is written to it to the response body, waiting while the client is behind. struct ChannelWriter(mpsc::Sender); impl Write for ChannelWriter { fn write(&mut self, buf: &[u8]) -> std::io::Result { self.0 .blocking_send(Ok(Bytes::copy_from_slice(buf))) .map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "the download was cancelled"))?; Ok(buf.len()) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } /// A response body fed by a [`ChannelWriter`]. struct ChannelBody(mpsc::Receiver); impl http_body::Body for ChannelBody { type Data = Bytes; type Error = std::io::Error; fn poll_frame(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>>> { self.0.poll_recv(cx).map(|chunk| chunk.map(|chunk| chunk.map(Frame::data))) } } /// One note's markdown, and its export markdown to cache when it was rendered here. /// A cached one only needs the current titles; a note without note links exports as /// its stored markdown; any other is imported and rendered. fn render<'a>( bytes: &'a DocBytes, titles: &HashMap, linking: &HashSet, id: &str, ) -> anyhow::Result<(Cow<'a, str>, Option)> { let resolve = |id: &str| titles.get(id).cloned(); if let Some(md) = &bytes.export { return Ok((export::resolve_deferred(md, &resolve).into(), None)); } let pending = bytes.snapshot.is_none() && bytes.updates.is_empty(); if let Some(md) = bytes.markdown.as_ref().filter(|_| pending || !linking.contains(id)) { return Ok((Cow::Borrowed(md), None)); } let doc = LoroDoc::new(); if let Some(snapshot) = &bytes.snapshot { doc.import(snapshot)?; } for update in &bytes.updates { doc.import(update)?; } match export::to_markdown_deferred(&doc) { // Cached only for a snapshot with nothing after it, the key of the cache. Some(md) => { let out = export::resolve_deferred(&md, &resolve); Ok((out.into(), (bytes.snapshot.is_some() && bytes.updates.is_empty()).then_some(md))) } None => Ok((export::to_markdown_with(&doc, &resolve).into(), None)), } } /// Makes a file or folder name safe on common systems: reserved characters and control /// characters become "-", edge spaces and dots are trimmed, and the length is capped. pub(crate) fn sanitize(name: &str) -> String { let replaced: String = name .chars() .map(|c| match c { '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '-', c if c.is_control() => '-', c => c, }) .collect(); let capped: String = replaced .trim_matches(|c: char| c == ' ' || c == '.') .chars() .take(MAX_NAME_CHARS) .collect(); let trimmed = capped.trim_matches(|c: char| c == ' ' || c == '.'); if trimmed.is_empty() { "Untitled".to_owned() } else { trimmed.to_owned() } } /// Returns `base` if no entry of `dir` uses it yet, else `base (2)`, `base (3)`, and so on. /// The chosen name is recorded in `taken` under the key `dir/name`. fn unique(taken: &mut HashSet, dir: &str, base: &str) -> String { let mut name = base.to_owned(); let mut n = 2; while taken.contains(&format!("{dir}/{name}")) { name = format!("{base} ({n})"); n += 1; } taken.insert(format!("{dir}/{name}")); name } /// The current UTC date as (year, month, day), from the Unix clock. fn utc_date() -> (i64, i64, i64) { let days = SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs() as i64 / 86_400) .unwrap_or(0); // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm). let z = days + 719_468; let era = z.div_euclid(146_097); let doe = z - era * 146_097; let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let day = doy - (153 * mp + 2) / 5 + 1; let month = if mp < 10 { mp + 3 } else { mp - 9 }; let year = yoe + era * 400 + if month <= 2 { 1 } else { 0 }; (year, month, day) }