| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use std::borrow::Cow; |
| 6 | use std::collections::{HashMap, HashSet}; |
| 7 | use std::io::{BufWriter, Write}; |
| 8 | use std::pin::Pin; |
| 9 | use std::sync::Arc; |
| 10 | use std::task::{Context, Poll}; |
| 11 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 12 | |
| 13 | use bytes::Bytes; |
| 14 | use http_body::Frame; |
| 15 | use tokio::sync::mpsc; |
| 16 | use topcoat::{ |
| 17 | Result, |
| 18 | context::{Cx, app_context}, |
| 19 | router::{Body, header, route}, |
| 20 | }; |
| 21 | use loro::LoroDoc; |
| 22 | |
| 23 | use crate::export; |
| 24 | use crate::hub::Hub; |
| 25 | use crate::media::Media; |
| 26 | use crate::store::{DocBytes, Notebook, Store}; |
| 27 | use crate::zipout::{Deflated, ZipOut}; |
| 28 | |
| 29 | const MAX_NAME_CHARS: usize = 100; |
| 30 | |
| 31 | const EXPORT_BATCH: usize = 2000; |
| 32 | |
| 33 | |
| 34 | const LOAD_BATCH_BYTES: usize = 64 << 20; |
| 35 | |
| 36 | const EXPORT_BATCH_BYTES: usize = 8 << 20; |
| 37 | |
| 38 | const SEND_CHUNK: usize = 256 * 1024; |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | #[route(GET "/export.zip")] |
| 45 | pub 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 | |
| 67 | type Chunk = std::io::Result<Bytes>; |
| 68 | type Zip = ZipOut<BufWriter<ChannelWriter>>; |
| 69 | |
| 70 | type Job = (u32, String, String, DocBytes); |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | async 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 | |
| 80 | let titles = store.titles_of(store.link_targets().await?).await?; |
| 81 | |
| 82 | |
| 83 | let mut files: Vec<(Box<str>, Box<str>)> = Vec::with_capacity(notes.len() + 1); |
| 84 | { |
| 85 | |
| 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 ¬es { |
| 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(¬e.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 | |
| 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 | |
| 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 | |
| 144 | drop(index); |
| 145 | let rest: Vec<u32> = (0..files.len() as u32).filter(|&i| !written[i as usize]).collect(); |
| 146 | drop(written); |
| 147 | |
| 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 | |
| 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 | |
| 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 | |
| 191 | |
| 192 | async 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 | |
| 200 | async 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 | |
| 211 | |
| 212 | |
| 213 | fn 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 | |
| 251 | |
| 252 | |
| 253 | fn 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 | |
| 262 | struct Rendered { |
| 263 | files: Vec<(u32, String, Deflated)>, |
| 264 | cache: Vec<(String, i64, String)>, |
| 265 | } |
| 266 | |
| 267 | |
| 268 | struct ChannelWriter(mpsc::Sender<Chunk>); |
| 269 | |
| 270 | impl 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 | |
| 284 | struct ChannelBody(mpsc::Receiver<Chunk>); |
| 285 | |
| 286 | impl 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 | |
| 296 | |
| 297 | |
| 298 | fn 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 | |
| 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 | |
| 330 | |
| 331 | pub(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 | |
| 354 | |
| 355 | fn 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 | |
| 367 | fn 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 | |
| 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 | } |