forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

export_all.rs383 lines, 16.0 KiBHistoryRawDownload
1//! GET /export.zip: every note outside the trash, as markdown files in one zip, and the
2//! media files in a `media` folder that the notes' `/media/` links are pointed at.
3//! Notes in a notebook go into a folder named after it; unfiled notes sit at the root.
4
5use std::borrow::Cow;
6use std::collections::{HashMap, HashSet};
7use std::io::{BufWriter, Write};
8use std::pin::Pin;
9use std::sync::Arc;
10use std::task::{Context, Poll};
11use std::time::{SystemTime, UNIX_EPOCH};
12
13use bytes::Bytes;
14use http_body::Frame;
15use tokio::sync::mpsc;
16use topcoat::{
17 Result,
18 context::{Cx, app_context},
19 router::{Body, header, route},
20};
21use loro::LoroDoc;
22
23use crate::export;
24use crate::hub::Hub;
25use crate::media::Media;
26use crate::store::{DocBytes, Notebook, Store};
27use crate::zipout::{Deflated, ZipOut};
28
29const MAX_NAME_CHARS: usize = 100;
30/// Most notes read and rendered together while exporting.
31const EXPORT_BATCH: usize = 2000;
32/// Bytes of stored notes read together, about: batches shrink for big notes, or a
33/// batch of huge notes would not fit in memory.
34const LOAD_BATCH_BYTES: usize = 64 << 20;
35/// Bytes of cached export markdown read and rendered together.
36const EXPORT_BATCH_BYTES: usize = 8 << 20;
37/// Bytes of the zip sent to the client at a time.
38const SEND_CHUNK: usize = 256 * 1024;
39
40/// GET /export.zip: a zip of the live markdown of every non-trashed note, and of every
41/// media file under `media/`. The zip is streamed while it is made, so the download
42/// starts at once and the server holds one batch of notes at a time, however many there
43/// are.
44#[route(GET "/export.zip")]
45pub async fn export_zip(cx: &Cx) -> Result<([(&'static str, String); 2], Body)> {
46 let store = app_context::<Arc<Store>>(cx).clone();
47 let media = app_context::<Arc<Media>>(cx).clone();
48 let hub = app_context::<Arc<Hub>>(cx).clone();
49 let (tx, rx) = mpsc::channel(8);
50 tokio::spawn(async move {
51 if let Err(err) = write_zip(&store, &media, &hub, tx.clone()).await {
52 eprintln!("export failed: {err:#}");
53 let _ = tx.send(Err(std::io::Error::other(err))).await;
54 }
55 });
56 let (year, month, day) = utc_date();
57 let disposition = format!("attachment; filename=\"notes-{year:04}-{month:02}-{day:02}.zip\"");
58 Ok((
59 [
60 (header::CONTENT_TYPE.as_str(), "application/zip".to_owned()),
61 (header::CONTENT_DISPOSITION.as_str(), disposition),
62 ],
63 Body::new(ChannelBody(rx)),
64 ))
65}
66
67type Chunk = std::io::Result<Bytes>;
68type Zip = ZipOut<BufWriter<ChannelWriter>>;
69/// A note to export: its index in the file list, its path, its id and its stored bytes.
70type Job = (u32, String, String, DocBytes);
71
72/// Writes the export zip into `tx`. Each batch is rendered and compressed on every
73/// core while the next one is read, then appended. The media files follow the notes,
74/// one at a time.
75async fn write_zip(store: &Store, media: &Media, hub: &Hub, tx: mpsc::Sender<Chunk>) -> anyhow::Result<()> {
76 let notes = store.list_notes().await?;
77 let notebooks = store.list_notebooks().await?;
78 let notebooks_by_id: HashMap<&str, &Notebook> = notebooks.iter().map(|nb| (nb.id.as_str(), nb)).collect();
79 // Links resolve by id: only their targets' titles are needed, not every note's.
80 let titles = store.titles_of(store.link_targets().await?).await?;
81
82 // The (id, path) of every note, in list order: the notes themselves are dropped.
83 let mut files: Vec<(Box<str>, Box<str>)> = Vec::with_capacity(notes.len() + 1);
84 {
85 // Dropped before the export starts: at millions of notes they hold every path again.
86 let mut folder_names: HashMap<String, String> = HashMap::new();
87 let mut folder_taken = HashSet::new();
88 let mut file_taken = HashSet::new();
89 for note in &notes {
90 let folder = match note.notebook_id.as_deref().and_then(|id| notebooks_by_id.get(id)) {
91 Some(nb) => folder_names
92 .entry(nb.id.clone())
93 .or_insert_with(|| unique(&mut folder_taken, "", &sanitize(&nb.name)))
94 .clone(),
95 None => String::new(),
96 };
97 let stem = unique(&mut file_taken, &folder, &sanitize(&note.title));
98 let path = if folder.is_empty() { format!("{stem}.md") } else { format!("{folder}/{stem}.md") };
99 files.push((note.id.as_str().into(), path.into()));
100 }
101 }
102 drop((notes, notebooks_by_id));
103
104 let titles = Arc::new(titles);
105 let linking = Arc::new(store.linking_notes().await?);
106 let mut zip: Zip = ZipOut::new(BufWriter::with_capacity(SEND_CHUNK, ChannelWriter(tx)), utc_date());
107 let mut rendering: Option<tokio::task::JoinHandle<anyhow::Result<Rendered>>> = None;
108 // Renders `jobs` while the previous batch is appended.
109 let mut next = async |zip: Zip, jobs: Vec<Job>| -> anyhow::Result<Zip> {
110 let done = match rendering.take() {
111 Some(handle) => Some(handle.await??),
112 None => None,
113 };
114 let (titles, linking) = (titles.clone(), linking.clone());
115 rendering = Some(tokio::task::spawn_blocking(move || render_files(jobs, &titles, &linking)));
116 match done {
117 Some(done) => finish_batch(store, zip, done).await,
118 None => Ok(zip),
119 }
120 };
121
122 // Notes whose export markdown is cached and current come first, in one read.
123 let index: HashMap<&str, usize> = files.iter().enumerate().map(|(i, (id, _))| (&**id, i)).collect();
124 let mut written = vec![false; files.len()];
125 let stale: HashSet<String> = store.stale_snapshots().await?.into_iter().collect();
126 let mut cached = store.scan_export_texts(EXPORT_BATCH_BYTES)?;
127 while let Some(batch) = cached.recv().await {
128 let jobs: Vec<Job> = batch?
129 .into_iter()
130 .filter(|(id, _)| !stale.contains(id))
131 .filter_map(|(id, md)| {
132 let i = *index.get(id.as_str())?;
133 if std::mem::replace(&mut written[i], true) {
134 return None;
135 }
136 let path = files[i].1.to_string();
137 let doc = DocBytes { snapshot: None, updates: Vec::new(), markdown: None, export: Some(md), upto_seq: 0 };
138 Some((i as u32, path, id, doc))
139 })
140 .collect();
141 zip = next(zip, jobs).await?;
142 }
143 // The rest from their stored docs, in batches.
144 drop(index);
145 let rest: Vec<u32> = (0..files.len() as u32).filter(|&i| !written[i as usize]).collect();
146 drop(written);
147 // Sized by the notes read so far, starting at one: these are often the few huge ones.
148 let (mut at, mut size) = (0, 1);
149 while at < rest.len() {
150 let batch = &rest[at..(at + size).min(rest.len())];
151 at += batch.len();
152 let ids: Vec<String> = batch.iter().map(|&i| files[i as usize].0.to_string()).collect();
153 let docs = store.load_docs(&ids, &linking).await?;
154 let bytes: usize = docs.iter().map(DocBytes::stored_len).sum();
155 size = (LOAD_BATCH_BYTES / (bytes / batch.len()).max(1)).clamp(1, EXPORT_BATCH);
156 let jobs = batch.iter().zip(ids).zip(docs).map(|((&i, id), doc)| (i, files[i as usize].1.to_string(), id, doc)).collect();
157 zip = next(zip, jobs).await?;
158 }
159 drop(next);
160 if let Some(handle) = rendering.take() {
161 zip = finish_batch(store, zip, handle.await??).await?;
162 }
163 drop(rest);
164 // Media, one file in memory at a time: each is read, stored and appended before the next.
165 for name in media.list().await? {
166 let bytes = tokio::fs::read(media.path(&name)).await?;
167 let file = tokio::task::spawn_blocking(move || Deflated::fast(&bytes)).await??;
168 let path = format!("media/{name}");
169 let index = files.len() as u32;
170 files.push((name.as_str().into(), path.as_str().into()));
171 zip = append(zip, vec![(index, path, file)]).await?;
172 }
173 // Takes, each joined from its closed parts, at the URL their embeds use.
174 for id in media.takes().await? {
175 let Some((joined, _)) = media.joined_take(&id, &hub.attached(&id)).await? else { continue };
176 let bytes = tokio::fs::read(&joined).await?;
177 let file = tokio::task::spawn_blocking(move || Deflated::fast(&bytes)).await??;
178 let path = format!("media/rec/{id}");
179 let index = files.len() as u32;
180 files.push((id.as_str().into(), path.as_str().into()));
181 zip = append(zip, vec![(index, path, file)]).await?;
182 }
183 tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
184 zip.finish(|i| &files[i as usize].1)?.into_inner().map_err(|e| e.into_error())?;
185 Ok(())
186 })
187 .await?
188}
189
190/// Appends a rendered batch to the zip and caches the export markdown it rendered, so
191/// the next export of those notes needs no doc.
192async fn finish_batch(store: &Store, zip: Zip, done: Rendered) -> anyhow::Result<Zip> {
193 if !done.cache.is_empty() {
194 store.put_export_texts(&done.cache).await?;
195 }
196 append(zip, done.files).await
197}
198
199/// Appends compressed files to the zip on a blocking thread: sending waits for the client.
200async fn append(mut zip: Zip, files: Vec<(u32, String, Deflated)>) -> anyhow::Result<Zip> {
201 tokio::task::spawn_blocking(move || {
202 for (name, path, file) in files {
203 zip.add(name, &path, file)?;
204 }
205 Ok(zip)
206 })
207 .await?
208}
209
210/// Renders and compresses every `(path, id, bytes)` job on scoped threads, keeping the
211/// job order. Threads take the next job when done, so one huge note keeps one thread
212/// busy rather than holding back a share of the others.
213fn render_files(jobs: Vec<Job>, titles: &HashMap<String, String>, linking: &HashSet<String>) -> anyhow::Result<Rendered> {
214 let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(jobs.len().max(1));
215 let next = std::sync::atomic::AtomicUsize::new(0);
216 let (queue, next) = (&jobs, &next);
217 let mut done: Vec<(usize, Deflated, Option<String>)> = std::thread::scope(|scope| {
218 let handles: Vec<_> = (0..threads)
219 .map(|_| {
220 scope.spawn(move || -> anyhow::Result<Vec<(usize, Deflated, Option<String>)>> {
221 let mut out = Vec::new();
222 loop {
223 let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
224 let Some((_, _, id, bytes)) = queue.get(i) else { return Ok(out) };
225 let (md, cache) = render(bytes, titles, linking, id)?;
226 let md = media_links(&md, &queue[i].1);
227 out.push((i, Deflated::new(md.as_bytes())?, cache));
228 }
229 })
230 })
231 .collect();
232 let mut done = Vec::with_capacity(queue.len());
233 for handle in handles {
234 done.extend(handle.join().map_err(|_| anyhow::anyhow!("export thread panicked"))??);
235 }
236 anyhow::Ok(done)
237 })?;
238 done.sort_unstable_by_key(|(i, _, _)| *i);
239 let mut cache = Vec::new();
240 let mut files = Vec::with_capacity(done.len());
241 for ((name, path, id, bytes), (_, file, md)) in jobs.into_iter().zip(done) {
242 files.push((name, path, file));
243 if let Some(md) = md {
244 cache.push((id, bytes.upto_seq, md));
245 }
246 }
247 Ok(Rendered { files, cache })
248}
249
250/// Points a note's `/media/` links at the zip's `media` folder, relative to the note's
251/// file: `media/` for a note at the root, `../media/` for one in a notebook folder.
252/// Plain text, so it also works on cached export markdown; the cache keeps `/media/`.
253fn media_links<'a>(md: &'a str, path: &str) -> Cow<'a, str> {
254 if !md.contains("](/media/") {
255 return Cow::Borrowed(md);
256 }
257 let to = if path.contains('/') { "../media/" } else { "media/" };
258 Cow::Owned(md.replace("](/media/", &format!("]({to}")))
259}
260
261/// A batch of the export: its files in order, and export markdown to cache.
262struct Rendered {
263 files: Vec<(u32, String, Deflated)>,
264 cache: Vec<(String, i64, String)>,
265}
266
267/// Sends what is written to it to the response body, waiting while the client is behind.
268struct ChannelWriter(mpsc::Sender<Chunk>);
269
270impl Write for ChannelWriter {
271 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
272 self.0
273 .blocking_send(Ok(Bytes::copy_from_slice(buf)))
274 .map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "the download was cancelled"))?;
275 Ok(buf.len())
276 }
277
278 fn flush(&mut self) -> std::io::Result<()> {
279 Ok(())
280 }
281}
282
283/// A response body fed by a [`ChannelWriter`].
284struct ChannelBody(mpsc::Receiver<Chunk>);
285
286impl http_body::Body for ChannelBody {
287 type Data = Bytes;
288 type Error = std::io::Error;
289
290 fn poll_frame(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<std::io::Result<Frame<Bytes>>>> {
291 self.0.poll_recv(cx).map(|chunk| chunk.map(|chunk| chunk.map(Frame::data)))
292 }
293}
294
295/// One note's markdown, and its export markdown to cache when it was rendered here.
296/// A cached one only needs the current titles; a note without note links exports as
297/// its stored markdown; any other is imported and rendered.
298fn render<'a>(
299 bytes: &'a DocBytes,
300 titles: &HashMap<String, String>,
301 linking: &HashSet<String>,
302 id: &str,
303) -> anyhow::Result<(Cow<'a, str>, Option<String>)> {
304 let resolve = |id: &str| titles.get(id).cloned();
305 if let Some(md) = &bytes.export {
306 return Ok((export::resolve_deferred(md, &resolve).into(), None));
307 }
308 let pending = bytes.snapshot.is_none() && bytes.updates.is_empty();
309 if let Some(md) = bytes.markdown.as_ref().filter(|_| pending || !linking.contains(id)) {
310 return Ok((Cow::Borrowed(md), None));
311 }
312 let doc = LoroDoc::new();
313 if let Some(snapshot) = &bytes.snapshot {
314 doc.import(snapshot)?;
315 }
316 for update in &bytes.updates {
317 doc.import(update)?;
318 }
319 match export::to_markdown_deferred(&doc) {
320 // Cached only for a snapshot with nothing after it, the key of the cache.
321 Some(md) => {
322 let out = export::resolve_deferred(&md, &resolve);
323 Ok((out.into(), (bytes.snapshot.is_some() && bytes.updates.is_empty()).then_some(md)))
324 }
325 None => Ok((export::to_markdown_with(&doc, &resolve).into(), None)),
326 }
327}
328
329/// Makes a file or folder name safe on common systems: reserved characters and control
330/// characters become "-", edge spaces and dots are trimmed, and the length is capped.
331pub(crate) fn sanitize(name: &str) -> String {
332 let replaced: String = name
333 .chars()
334 .map(|c| match c {
335 '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '-',
336 c if c.is_control() => '-',
337 c => c,
338 })
339 .collect();
340 let capped: String = replaced
341 .trim_matches(|c: char| c == ' ' || c == '.')
342 .chars()
343 .take(MAX_NAME_CHARS)
344 .collect();
345 let trimmed = capped.trim_matches(|c: char| c == ' ' || c == '.');
346 if trimmed.is_empty() {
347 "Untitled".to_owned()
348 } else {
349 trimmed.to_owned()
350 }
351}
352
353/// Returns `base` if no entry of `dir` uses it yet, else `base (2)`, `base (3)`, and so on.
354/// The chosen name is recorded in `taken` under the key `dir/name`.
355fn unique(taken: &mut HashSet<String>, dir: &str, base: &str) -> String {
356 let mut name = base.to_owned();
357 let mut n = 2;
358 while taken.contains(&format!("{dir}/{name}")) {
359 name = format!("{base} ({n})");
360 n += 1;
361 }
362 taken.insert(format!("{dir}/{name}"));
363 name
364}
365
366/// The current UTC date as (year, month, day), from the Unix clock.
367fn utc_date() -> (i64, i64, i64) {
368 let days = SystemTime::now()
369 .duration_since(UNIX_EPOCH)
370 .map(|d| d.as_secs() as i64 / 86_400)
371 .unwrap_or(0);
372 // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
373 let z = days + 719_468;
374 let era = z.div_euclid(146_097);
375 let doe = z - era * 146_097;
376 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
377 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
378 let mp = (5 * doy + 2) / 153;
379 let day = doy - (153 * mp + 2) / 5 + 1;
380 let month = if mp < 10 { mp + 3 } else { mp - 9 };
381 let year = yoe + era * 400 + if month <= 2 { 1 } else { 0 };
382 (year, month, day)
383}