forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

hub.rs1047 lines, 42.3 KiBHistoryRawDownload
1//! Per-note live state: one in-memory `LoroDoc` per note, shared by every
2//! WebSocket connection editing that note.
3//!
4//! Wire protocol (binary frames, first byte is the tag):
5//! - `0x01` SYNC_REQ: payload is an encoded `VersionVector`. The receiver
6//! answers with an UPDATE containing what the requester is missing.
7//! - `0x02` UPDATE: payload is Loro update bytes. Imported, persisted and
8//! broadcast to the other connections when it changed the doc.
9//! - `0x03` EPHEMERAL: opaque bytes, broadcast only, never persisted.
10//! - `0x04` RECORDING: UTF-8 `<session>\t<live|lost|ended>`. The state of a recording take,
11//! sent when a connection joins and whenever it changes. Not an edit.
12
13use std::collections::{HashMap, HashSet};
14use std::io;
15use std::path::Path;
16use std::sync::Mutex;
17use std::sync::atomic::{AtomicU64, Ordering};
18use std::time::Duration;
19
20use bytes::Bytes;
21use loro::{ExportMode, Frontiers, LoroDoc, VersionVector};
22use tokio::sync::{Mutex as AsyncMutex, broadcast, oneshot};
23use topcoat::router::content::websocket::{Message, WebSocket};
24
25use crate::export;
26use crate::media::{parts_in, part_file};
27use crate::store::{Store, now_millis};
28
29pub const SYNC_REQ: u8 = 0x01;
30pub const UPDATE: u8 = 0x02;
31pub const EPHEMERAL: u8 = 0x03;
32pub const RECORDING: u8 = 0x04;
33
34/// How long a lost take stays lost before it is reported ended.
35const LOST_FOR: Duration = Duration::from_secs(30);
36
37const SNAPSHOT_EVERY: u64 = 50;
38/// Bodies longer than this derive their text one at a time ([`HEAVY`]): each derivation
39/// holds a few copies of the text, and a 100 MB note's snapshot and text flush overlap.
40const HEAVY_BYTES: usize = 16 << 20;
41static HEAVY: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(1);
42/// Least time between two versions recorded while the note is being edited.
43const VERSION_EVERY_MS: i64 = 10 * 60 * 1000;
44/// Quiet time after the last applied update before the searchable text is written.
45const TEXT_FLUSH_DELAY: Duration = Duration::from_secs(2);
46const CHANNEL_CAPACITY: usize = 256;
47
48/// A broadcast item: the connection id that sent it, and the full frame.
49type Frame = (u64, Bytes);
50
51/// The state of a recording take, as the editor shows it.
52#[derive(Clone, Copy, PartialEq, Eq)]
53pub enum TakeState {
54 /// A socket is attached to a part of the take.
55 Live,
56 /// A socket died without `end` and nothing has come back yet.
57 Lost,
58 /// The take is over. Only sent, never kept.
59 Ended,
60}
61
62impl TakeState {
63 fn as_str(self) -> &'static str {
64 match self {
65 TakeState::Live => "live",
66 TakeState::Lost => "lost",
67 TakeState::Ended => "ended",
68 }
69 }
70}
71
72/// How a part's socket stopped: with `end`, or any other way.
73#[derive(Clone, Copy)]
74pub enum Detach {
75 Ended,
76 Lost,
77}
78
79/// A socket's attachment to a part: what [`Hub::attach`] answers.
80pub struct Attachment {
81 pub part: u32,
82 /// Tells this attachment from a later one on the same part.
83 pub token: u64,
84 /// Fires when another socket takes the part over.
85 pub stop: oneshot::Receiver<()>,
86}
87
88/// A recording take in memory, keyed by its session id.
89struct Take {
90 state: TakeState,
91 /// The part numbers a socket is attached to.
92 attached: HashMap<u32, Slot>,
93 /// Counts the changes, so a lost take's timer can tell it changed since.
94 version: u64,
95}
96
97/// A socket attached to a part.
98struct Slot {
99 token: u64,
100 stop: oneshot::Sender<()>,
101}
102
103pub struct Hub {
104 rooms: Mutex<HashMap<String, std::sync::Arc<Room>>>,
105 next_conn: AtomicU64,
106 /// One lock per note whose doc is being built from imported markdown.
107 building: Mutex<HashMap<String, std::sync::Arc<AsyncMutex<()>>>>,
108 /// Woken when an import leaves a doc to build.
109 pending: tokio::sync::Notify,
110 /// One import at a time builds its doc before answering (see [`Hub::build_now`]).
111 inline: tokio::sync::Semaphore,
112 /// Recording takes by note, then by session id. Also locks the choice of a new part.
113 takes: Mutex<HashMap<String, HashMap<String, Take>>>,
114}
115
116impl Hub {
117 pub fn new() -> Self {
118 Self {
119 rooms: Mutex::new(HashMap::new()),
120 next_conn: AtomicU64::new(1),
121 building: Mutex::new(HashMap::new()),
122 pending: tokio::sync::Notify::new(),
123 inline: tokio::sync::Semaphore::new(1),
124 takes: Mutex::new(HashMap::new()),
125 }
126 }
127
128 /// Wakes [`build_pending`](Self::build_pending) after an import stored markdown
129 /// without a doc.
130 pub fn doc_pending(&self) {
131 self.pending.notify_one();
132 }
133
134 /// Builds the doc of a just imported note before the import answers, so the note
135 /// opens without waiting for it. Only one import at a time does: the others, and
136 /// any build that fails, are left to [`build_pending`](Self::build_pending), which
137 /// keeps the memory of many big imports at once bounded.
138 pub async fn build_now(&self, store: &Store, note_id: &str) {
139 let Ok(_permit) = self.inline.try_acquire() else { return self.doc_pending() };
140 if let Err(err) = self.ensure_doc(store, note_id, false).await {
141 eprintln!("building the doc of note {note_id} failed: {err:#}");
142 self.doc_pending();
143 }
144 }
145
146 /// Builds the docs of imported notes in the background, one at a time.
147 pub async fn build_pending(&self, store: &Store) {
148 loop {
149 match store.pending_docs().await {
150 Ok(ids) => {
151 for id in ids {
152 if let Err(err) = self.ensure_doc(store, &id, true).await {
153 eprintln!("building the doc of note {id} failed: {err:#}");
154 }
155 }
156 }
157 Err(err) => eprintln!("reading pending docs failed: {err:#}"),
158 }
159 self.pending.notified().await;
160 }
161 }
162
163 /// Snapshots the notes whose updates outgrew their snapshot, which happens when the
164 /// server stops before a due snapshot is written. Until then every load of such a
165 /// note replays its updates, and an export renders it from scratch.
166 pub async fn compact_stale(&self, store: &Store) {
167 let ids = match store.stale_snapshots().await {
168 Ok(ids) => ids,
169 Err(err) => return eprintln!("finding stale snapshots failed: {err:#}"),
170 };
171 for id in ids {
172 // An open room snapshots on its own.
173 if self.rooms.lock().unwrap().contains_key(&id) {
174 continue;
175 }
176 let result = async {
177 let upto_seq = store.max_seq(&id).await?;
178 let (doc, _, _, _) = load_doc(store, &id).await?;
179 let (data, (title, markdown, links), export) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
180 Ok((doc.export(ExportMode::Snapshot)?, derived_text(&doc), export::to_markdown_deferred(&doc)))
181 })
182 .await??;
183 if store.put_snapshot(&id, data, upto_seq, &markdown, &title).await? {
184 store.set_links(&id, &links).await?;
185 if let Some(export) = export {
186 store.put_export_texts(&[(id.clone(), upto_seq, export)]).await?;
187 }
188 }
189 anyhow::Ok(())
190 }
191 .await;
192 if let Err(err) = result {
193 eprintln!("snapshot failed for note {id}: {err:#}");
194 }
195 }
196 }
197
198 /// Builds the note's doc from its imported markdown if that has not happened yet.
199 /// A big import stores only the markdown, since a doc of a million blocks takes
200 /// Loro some 15 s to build and snapshot.
201 ///
202 /// The background builder (`skip_busy`) leaves a note alone that is being built:
203 /// waiting on it would count as someone opening the note, and keep its doc in memory.
204 async fn ensure_doc(&self, store: &Store, note_id: &str, skip_busy: bool) -> anyhow::Result<()> {
205 let lock = {
206 let mut building = self.building.lock().unwrap();
207 if skip_busy && building.contains_key(note_id) {
208 return Ok(());
209 }
210 building.entry(note_id.to_owned()).or_default().clone()
211 };
212 let mut guard = Some(lock.lock().await);
213 let result = async {
214 // A builder before us may have handed its doc to a room, still storing it.
215 if self.rooms.lock().unwrap().contains_key(note_id) {
216 return Ok(());
217 }
218 let Some(markdown) = store.pending_markdown(note_id).await? else { return Ok(()) };
219 let (doc, snapshot, title, body, links) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
220 let doc = crate::import::markdown_to_doc(&markdown)?;
221 // The text read overlaps the export: together about 1 s sooner.
222 let (snapshot, (title, body, links)) = std::thread::scope(|s| {
223 let text = s.spawn(|| derived_text(&doc));
224 (doc.export(ExportMode::Snapshot), text.join().unwrap())
225 });
226 Ok((doc, snapshot?, title, body, links))
227 })
228 .await??;
229 let body = std::sync::Arc::new(body);
230 // Someone waits to open the note: give them the doc now, not after the store
231 // takes its 100+ MB of text (a second for a huge note). Edits stored meanwhile
232 // land after the snapshot, which covers no updates (`upto_seq` 0). Nobody
233 // waiting, the doc is dropped, so a bulk import keeps no docs in memory.
234 if std::sync::Arc::strong_count(&lock) > 2 {
235 let markdown = links.is_empty().then(|| (doc.oplog_vv(), body.clone()));
236 let last_version = load_last_version(store, note_id).await?;
237 let room = std::sync::Arc::new(Room::new(note_id, doc, last_version, snapshot.len(), markdown, 0));
238 self.rooms.lock().unwrap().entry(note_id.to_owned()).or_insert(room);
239 guard.take();
240 } else {
241 drop(doc);
242 }
243 store.finish_pending(note_id, &snapshot, &title, &body, &links).await
244 }
245 .await;
246 drop(guard);
247 let mut building = self.building.lock().unwrap();
248 if std::sync::Arc::strong_count(&lock) == 2 {
249 building.remove(note_id);
250 }
251 result
252 }
253
254 /// Returns the live room for `note_id`, loading it from the store on first use.
255 /// Rooms are kept in memory after their last connection leaves, so a room is
256 /// never orphaned while a connection still holds it.
257 pub async fn room(&self, store: &Store, note_id: &str) -> anyhow::Result<std::sync::Arc<Room>> {
258 let existing = self
259 .rooms
260 .lock()
261 .unwrap()
262 .get(note_id)
263 .cloned();
264 if let Some(room) = existing {
265 *room.used.lock().unwrap() = std::time::Instant::now();
266 return Ok(room);
267 }
268
269 // Load without holding the map lock: this awaits the store.
270 self.ensure_doc(store, note_id, false).await?;
271 if let Some(room) = self.rooms.lock().unwrap().get(note_id).cloned() {
272 return Ok(room);
273 }
274 let (doc, stored, markdown, updates) = load_doc(store, note_id).await?;
275 let markdown = match markdown {
276 Some(md) if !store.has_links(note_id).await? => Some((doc.oplog_vv(), std::sync::Arc::new(md))),
277 _ => None,
278 };
279 let last_version = load_last_version(store, note_id).await?;
280 let room = std::sync::Arc::new(Room::new(note_id, doc, last_version, stored, markdown, updates));
281
282 // Another task may have loaded the same note meanwhile; keep the first one.
283 let mut rooms = self.rooms.lock().unwrap();
284 Ok(rooms
285 .entry(note_id.to_owned())
286 .or_insert(room)
287 .clone())
288 }
289
290 /// Unloads rooms nobody has used for a while, so the docs of notes opened once do
291 /// not stay in memory for good. Only a room nothing else holds and with every update
292 /// stored goes: the next use loads the same doc from the store.
293 pub async fn evict_idle(&self) {
294 const IDLE: Duration = Duration::from_secs(5 * 60);
295 loop {
296 tokio::time::sleep(Duration::from_secs(30)).await;
297 self.rooms.lock().unwrap().retain(|_, room| {
298 let idle = room.used.lock().unwrap().elapsed() >= IDLE;
299 let held = std::sync::Arc::strong_count(room) > 1;
300 let writing = room.queued.load(Ordering::Acquire) > 0;
301 // A locked state is in use.
302 let quiet = room.state.try_lock().is_ok_and(|s| s.conns == 0 && !s.text_pending && s.last_update.elapsed() >= IDLE);
303 !(idle && !held && !writing && quiet)
304 });
305 }
306 }
307
308 /// Drops the in-memory room for a deleted note. Connections still holding the
309 /// room keep working until they leave; nothing new is loaded for this id.
310 pub fn forget(&self, note_id: &str) {
311 self.rooms.lock().unwrap().remove(note_id);
312 }
313
314 fn next_conn_id(&self) -> u64 {
315 self.next_conn.fetch_add(1, Ordering::Relaxed)
316 }
317
318 /// Attaches a socket to a part of take `session` of `note`, and makes the take live. With
319 /// `part` None the socket gets a new part, created now, numbered after the take's last part.
320 /// With `part` given it gets that part, which must exist, and a socket already on it stops.
321 /// Answers `None` when that part does not exist. `dir` is the take's folder.
322 pub fn attach(&self, note: &str, session: &str, part: Option<u32>, dir: &Path) -> io::Result<Option<Attachment>> {
323 let mut takes = self.takes.lock().unwrap();
324 let part = match part {
325 Some(part) if !part_file(dir, part).is_file() => return Ok(None),
326 Some(part) => part,
327 None => {
328 let part = parts_in(dir)?.last().map_or(0, |(n, _)| n + 1);
329 std::fs::OpenOptions::new().write(true).create_new(true).open(part_file(dir, part))?;
330 part
331 }
332 };
333 let token = self.next_conn_id();
334 let (stop, stopped) = oneshot::channel();
335 let take = takes
336 .entry(note.to_owned())
337 .or_default()
338 .entry(session.to_owned())
339 .or_insert_with(|| Take { state: TakeState::Ended, attached: HashMap::new(), version: 0 });
340 take.version += 1;
341 if let Some(old) = take.attached.insert(part, Slot { token, stop }) {
342 let _ = old.stop.send(());
343 }
344 let changed = take.state != TakeState::Live;
345 take.state = TakeState::Live;
346 drop(takes);
347 if changed {
348 self.publish(note, session, TakeState::Live);
349 }
350 Ok(Some(Attachment { part, token, stop: stopped }))
351 }
352
353 /// Detaches the socket `token` from `part` of a take. Once no part is attached the take is
354 /// ended by `end`, and lost otherwise: a lost take becomes ended after [`LOST_FOR`] unless it
355 /// changes first. A socket that was taken over no longer matches its token, so this does
356 /// nothing for it.
357 pub fn detach(self: &std::sync::Arc<Self>, note: &str, session: &str, part: u32, token: u64, how: Detach) {
358 let mut takes = self.takes.lock().unwrap();
359 let Some(sessions) = takes.get_mut(note) else { return };
360 let Some(take) = sessions.get_mut(session) else { return };
361 if take.attached.get(&part).is_none_or(|slot| slot.token != token) {
362 return;
363 }
364 take.attached.remove(&part);
365 take.version += 1;
366 if !take.attached.is_empty() {
367 return;
368 }
369 let version = take.version;
370 match how {
371 Detach::Ended => {
372 sessions.remove(session);
373 if sessions.is_empty() {
374 takes.remove(note);
375 }
376 drop(takes);
377 self.publish(note, session, TakeState::Ended);
378 }
379 Detach::Lost => {
380 take.state = TakeState::Lost;
381 drop(takes);
382 self.publish(note, session, TakeState::Lost);
383 let hub = self.clone();
384 let (note, session) = (note.to_owned(), session.to_owned());
385 tokio::spawn(async move {
386 tokio::time::sleep(LOST_FOR).await;
387 hub.expire(&note, &session, version);
388 });
389 }
390 }
391 }
392
393 /// Ends a lost take that has not changed since `version`.
394 fn expire(&self, note: &str, session: &str, version: u64) {
395 let mut takes = self.takes.lock().unwrap();
396 let Some(sessions) = takes.get_mut(note) else { return };
397 let due = sessions
398 .get(session)
399 .is_some_and(|take| take.state == TakeState::Lost && take.version == version);
400 if !due {
401 return;
402 }
403 sessions.remove(session);
404 if sessions.is_empty() {
405 takes.remove(note);
406 }
407 drop(takes);
408 self.publish(note, session, TakeState::Ended);
409 }
410
411 /// The part numbers of `session` that a socket is attached to.
412 pub fn attached(&self, session: &str) -> HashSet<u32> {
413 let takes = self.takes.lock().unwrap();
414 let note = session.split('.').next().unwrap_or_default();
415 takes
416 .get(note)
417 .and_then(|sessions| sessions.get(session))
418 .map(|take| take.attached.keys().copied().collect())
419 .unwrap_or_default()
420 }
421
422 /// A RECORDING frame for each take of `note` that is live or lost, sent to a connection that
423 /// just joined.
424 pub fn take_frames(&self, note: &str) -> Vec<Bytes> {
425 let takes = self.takes.lock().unwrap();
426 takes
427 .get(note)
428 .map(|sessions| sessions.iter().map(|(session, take)| recording_frame(session, take.state)).collect())
429 .unwrap_or_default()
430 }
431
432 /// Sends a take's state to the note's room, if the room is loaded. Its connections forward it.
433 fn publish(&self, note: &str, session: &str, state: TakeState) {
434 let room = self.rooms.lock().unwrap().get(note).cloned();
435 if let Some(room) = room {
436 room.broadcast(0, recording_frame(session, state));
437 }
438 }
439}
440
441/// A RECORDING frame: the take's session id and state.
442fn recording_frame(session: &str, state: TakeState) -> Bytes {
443 Bytes::from(frame(RECORDING, format!("{session}\t{}", state.as_str()).as_bytes()))
444}
445
446impl Default for Hub {
447 fn default() -> Self {
448 Self::new()
449 }
450}
451
452/// Update holding the body of a new note: one empty paragraph. Written once at note
453/// creation so clients never race to initialise it.
454pub fn initial_note_update() -> anyhow::Result<Vec<u8>> {
455 let doc = LoroDoc::new();
456 note_model::flat::init(&doc)?;
457 doc.commit();
458 Ok(doc.export(ExportMode::all_updates())?)
459}
460
461/// The newest recorded version of a note, with its time in millis.
462async fn load_last_version(store: &Store, note_id: &str) -> anyhow::Result<Option<(i64, Frontiers)>> {
463 match store.list_versions(note_id).await?.into_iter().next() {
464 Some((at, bytes)) => Ok(Some((at, Frontiers::decode(&bytes)?))),
465 None => Ok(None),
466 }
467}
468
469/// The note's doc, how many bytes it is stored in, its stored markdown when that is up
470/// to date, and how many updates it has after its snapshot.
471/// Runs whole-doc work (imports, exports, reads of a huge note take seconds) without
472/// stalling the other tasks on this runtime thread, such as page requests.
473fn blocking<T>(f: impl FnOnce() -> T) -> T {
474 tokio::task::block_in_place(f)
475}
476
477pub async fn load_doc(store: &Store, note_id: &str) -> anyhow::Result<(LoroDoc, usize, Option<String>, u64)> {
478 let bytes = store.load_doc(note_id).await?;
479 let doc = LoroDoc::new();
480 let mut stored = 0;
481 if let Some(snapshot) = bytes.snapshot {
482 stored += snapshot.len();
483 blocking(|| doc.import(&snapshot))?;
484 }
485 let updates = bytes.updates.len() as u64;
486 for update in bytes.updates {
487 stored += update.len();
488 blocking(|| doc.import(&update))?;
489 }
490 Ok((doc, stored, bytes.markdown, updates))
491}
492
493struct RoomState {
494 doc: LoroDoc,
495 /// Live WebSocket connections on this room.
496 conns: usize,
497 updates_since_snapshot: u64,
498 /// Bytes of the updates since the last snapshot, and the size of that snapshot: a
499 /// snapshot costs time in proportion to the doc, so a huge doc takes one rarely.
500 update_bytes: usize,
501 snapshot_len: usize,
502 /// How long the last searchable-text read took, and when the last update came: the
503 /// read waits for a pause in typing that long, so a huge doc is not re-read over
504 /// and over while someone types.
505 text_cost: Duration,
506 last_update: std::time::Instant,
507 /// A searchable-text flush is scheduled and has not read the doc yet.
508 text_pending: bool,
509 /// A huge doc's snapshot waits for [`HEAVY`] and has not been taken yet.
510 snapshot_pending: bool,
511 /// Time in millis and frontiers of the newest recorded version.
512 last_version: Option<(i64, Frontiers)>,
513 /// The doc's markdown at a version, kept only while the doc has no note links:
514 /// then it is also the export, which a huge doc takes seconds to write.
515 markdown: Option<(VersionVector, std::sync::Arc<String>)>,
516}
517
518impl RoomState {
519 /// Keeps `markdown`, read at `vv`, if the doc is still at that version.
520 fn cache_markdown(&mut self, vv: VersionVector, markdown: std::sync::Arc<String>, links: &[export::LinkTarget]) {
521 self.markdown = (links.is_empty() && vv == self.doc.oplog_vv()).then(|| (vv, markdown));
522 }
523
524 fn cached_markdown(&self) -> Option<std::sync::Arc<String>> {
525 let (vv, md) = self.markdown.as_ref()?;
526 (*vv == self.doc.oplog_vv()).then(|| md.clone())
527 }
528}
529
530/// A snapshot taken under the room lock, still to be stored with its derived text.
531struct Snapshot {
532 data: Vec<u8>,
533 /// The doc's body at the snapshot, for its derived text.
534 body: export::Body,
535 vv: VersionVector,
536 upto_seq: i64,
537 heavy: bool,
538}
539
540pub struct Room {
541 note_id: String,
542 tx: broadcast::Sender<Frame>,
543 state: AsyncMutex<RoomState>,
544 /// Client updates on their way to the store, in order (see `apply_update`).
545 writes: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<Bytes>>,
546 /// How many of those are not stored yet.
547 queued: std::sync::Arc<std::sync::atomic::AtomicUsize>,
548 /// When the room was last handed out (see [`Hub::evict_idle`]).
549 used: Mutex<std::time::Instant>,
550}
551
552impl Room {
553 fn new(
554 note_id: &str,
555 doc: LoroDoc,
556 last_version: Option<(i64, Frontiers)>,
557 stored: usize,
558 markdown: Option<(VersionVector, std::sync::Arc<String>)>,
559 updates: u64,
560 ) -> Self {
561 let (tx, _) = broadcast::channel(CHANNEL_CAPACITY);
562 Self {
563 note_id: note_id.to_owned(),
564 tx,
565 state: AsyncMutex::new(RoomState {
566 doc,
567 conns: 0,
568 updates_since_snapshot: updates,
569 update_bytes: 0,
570 snapshot_len: stored,
571 text_cost: Duration::ZERO,
572 last_update: std::time::Instant::now(),
573 text_pending: false,
574 snapshot_pending: false,
575 last_version,
576 markdown,
577 }),
578 writes: std::sync::OnceLock::new(),
579 queued: Default::default(),
580 used: Mutex::new(std::time::Instant::now()),
581 }
582 }
583
584 /// Registers a connection. The receiver is created under the same lock as the
585 /// connection count, so no broadcast can be missed between join and first recv.
586 async fn join(&self) -> broadcast::Receiver<Frame> {
587 let mut state = self.state.lock().await;
588 state.conns += 1;
589 self.tx.subscribe()
590 }
591
592 /// Records a version and persists a snapshot when the last connection leaves.
593 async fn leave(self: &std::sync::Arc<Self>, store: &std::sync::Arc<Store>) {
594 let mut state = self.state.lock().await;
595 state.conns = state.conns.saturating_sub(1);
596 if state.conns == 0 {
597 if let Err(err) = record_version(&mut state, store, &self.note_id).await {
598 eprintln!("version record failed for note {}: {err:#}", self.note_id);
599 }
600 // A reload leaves and joins again: only new updates are worth a snapshot.
601 if state.updates_since_snapshot > 0 {
602 schedule_snapshot(self, &mut state, store).await;
603 }
604 }
605 }
606
607 /// Frame announcing our version vector, so the peer can send what we lack.
608 pub async fn sync_req_frame(&self) -> Vec<u8> {
609 let state = self.state.lock().await;
610 frame(SYNC_REQ, &state.doc.oplog_vv().encode())
611 }
612
613 /// Answers a SYNC_REQ payload with an UPDATE frame of what the peer lacks.
614 async fn sync_reply(&self, payload: &[u8]) -> anyhow::Result<Vec<u8>> {
615 let state = self.state.lock().await;
616 let vv = VersionVector::decode(payload)?;
617 // A fresh peer gets a snapshot: it loads lazily instead of replaying every op.
618 let mode = if vv.is_empty() { ExportMode::Snapshot } else { ExportMode::updates(&vv) };
619 let updates = blocking(|| state.doc.export(mode))?;
620 Ok(frame(UPDATE, &updates))
621 }
622
623 async fn all_updates_frame(&self) -> anyhow::Result<Vec<u8>> {
624 let state = self.state.lock().await;
625 Ok(frame(UPDATE, &blocking(|| state.doc.export(ExportMode::all_updates()))?))
626 }
627
628 /// Imports an UPDATE payload. Returns `true` when it changed the doc, in which
629 /// case it should be broadcast. The store write is queued, not awaited: one write
630 /// of a huge note's text holds the store for seconds, and collaborators would see
631 /// every keystroke that much later. A snapshot only covers updates the doc has
632 /// already imported, and a client resends on reconnect what the server lacks, so
633 /// order and a write lost in a crash are both harmless.
634 async fn apply_update(self: &std::sync::Arc<Self>, store: &std::sync::Arc<Store>, payload: Bytes) -> anyhow::Result<bool> {
635 let mut state = self.state.lock().await;
636 let before = state.doc.oplog_vv();
637 blocking(|| state.doc.import(&payload))?;
638 if state.doc.oplog_vv() == before {
639 return Ok(false);
640 }
641 let writes = self.writes.get_or_init(|| {
642 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Bytes>();
643 let (store, note_id, queued) = (store.clone(), self.note_id.clone(), self.queued.clone());
644 tokio::spawn(async move {
645 while let Some(update) = rx.recv().await {
646 if let Err(err) = store.append_update(&note_id, &update).await {
647 eprintln!("update write failed for note {note_id}: {err:#}");
648 }
649 queued.fetch_sub(1, Ordering::Release);
650 }
651 });
652 tx
653 });
654 self.queued.fetch_add(1, Ordering::Acquire);
655 let len = payload.len();
656 let _ = writes.send(payload);
657 count_update(self, &mut state, store, len).await?;
658 Ok(true)
659 }
660
661 /// The document as it was at `frontiers`, as HTML. The live doc is not changed.
662 pub async fn html_at(&self, frontiers: &Frontiers) -> anyhow::Result<String> {
663 let state = self.state.lock().await;
664 let forked = state.doc.fork_at(frontiers)?;
665 Ok(export::to_html(&forked))
666 }
667
668 /// Makes the doc match an earlier version. The change is a new edit on top of the
669 /// history, so it is persisted and broadcast like a client update. The state before
670 /// and after the restore are both recorded as versions, so the restore can be undone.
671 pub async fn restore(self: &std::sync::Arc<Self>, store: &std::sync::Arc<Store>, frontiers: &Frontiers) -> anyhow::Result<()> {
672 let mut state = self.state.lock().await;
673 let vv_before = state.doc.oplog_vv();
674 record_version(&mut state, store, &self.note_id).await?;
675 state.doc.revert_to(frontiers)?;
676 state.doc.commit();
677 if state.doc.oplog_vv() == vv_before {
678 return Ok(());
679 }
680 let update = blocking(|| state.doc.export(ExportMode::updates(&vv_before)))?;
681 persist_update(self, &mut state, store, &update).await?;
682 // Connection 0 never exists, so every connection receives the restore.
683 self.broadcast(0, frame(UPDATE, &update).into());
684 record_version(&mut state, store, &self.note_id).await
685 }
686
687 fn broadcast(&self, conn_id: u64, frame: Bytes) {
688 // Err only means there are no receivers, which is fine.
689 let _ = self.tx.send((conn_id, frame));
690 }
691
692 /// Live markdown of the in-memory doc, with note links written as `[[Title]]`.
693 pub async fn markdown_with(&self, store: &Store) -> anyhow::Result<String> {
694 let body = {
695 let state = self.state.lock().await;
696 if let Some(md) = state.cached_markdown() {
697 return Ok(md.to_string());
698 }
699 blocking(|| export::Body::read(&state.doc))
700 };
701 let ids: Vec<String> = body
702 .note_links()
703 .into_iter()
704 .filter_map(|t| match t {
705 export::LinkTarget::Id(id) => Some(id),
706 export::LinkTarget::Title(_) => None,
707 })
708 .collect();
709 let titles = store.titles_of(ids).await?;
710 Ok(tokio::task::spawn_blocking(move || body.markdown_with(&|id| titles.get(id).cloned())).await?)
711 }
712
713 pub async fn html(&self) -> anyhow::Result<String> {
714 self.read(|body| body.html()).await
715 }
716
717 /// Runs a whole-document read on a blocking thread. Only reading the body holds the
718 /// room (one pass over the text, ~50 ms for 100 MB): rendering it does not.
719 async fn read<T: Send + 'static>(&self, f: impl FnOnce(&export::Body) -> T + Send + 'static) -> anyhow::Result<T> {
720 let state = self.state.lock().await;
721 let body = blocking(|| export::Body::read(&state.doc));
722 drop(state);
723 Ok(tokio::task::spawn_blocking(move || f(&body)).await?)
724 }
725
726 /// The editor's markup for the doc, shown until the editor takes over.
727 pub async fn editor_html(&self) -> String {
728 let state = self.state.lock().await;
729 note_model::render::preview_html(&state.doc, 128, 100_000)
730 }
731}
732
733/// Stores a changed update, counts it towards the next snapshot, and schedules the
734/// searchable-text flush. The caller has already imported the update into `state`.
735async fn persist_update(
736 room: &std::sync::Arc<Room>,
737 state: &mut RoomState,
738 store: &std::sync::Arc<Store>,
739 payload: &[u8],
740) -> anyhow::Result<()> {
741 store.append_update(&room.note_id, payload).await?;
742 count_update(room, state, store, payload.len()).await
743}
744
745/// Counts a stored or queued update towards the next snapshot, and schedules the
746/// searchable-text flush.
747async fn count_update(room: &std::sync::Arc<Room>, state: &mut RoomState, store: &std::sync::Arc<Store>, len: usize) -> anyhow::Result<()> {
748 state.updates_since_snapshot += 1;
749 state.update_bytes += len;
750 state.last_update = std::time::Instant::now();
751 if state.updates_since_snapshot >= SNAPSHOT_EVERY && state.update_bytes * 16 >= state.snapshot_len {
752 schedule_snapshot(room, state, store).await;
753 }
754 if !state.text_pending {
755 state.text_pending = true;
756 tokio::spawn(flush_text(room.clone(), store.clone()));
757 }
758 Ok(())
759}
760
761/// Records the doc's current frontiers as a version, unless they are the same as the
762/// newest recorded version.
763async fn record_version(state: &mut RoomState, store: &Store, note_id: &str) -> anyhow::Result<()> {
764 let frontiers = state.doc.oplog_frontiers();
765 if state.last_version.as_ref().is_some_and(|(_, last)| *last == frontiers) {
766 return Ok(());
767 }
768 let at = now_millis();
769 store.add_version(note_id, at, &frontiers.encode()).await?;
770 state.last_version = Some((at, frontiers));
771 Ok(())
772}
773
774/// Writes the note's title and searchable text after typing pauses. The flag is
775/// cleared before the doc is read, so an update that arrives during the write
776/// schedules a new flush. A version is recorded when the last one is 10 minutes old.
777async fn flush_text(room: std::sync::Arc<Room>, store: std::sync::Arc<Store>) {
778 let mut permit = None;
779 let (title, body, links) = {
780 let mut state = loop {
781 let state = room.state.lock().await;
782 let quiet = TEXT_FLUSH_DELAY.max(state.text_cost * 2);
783 let idle = state.last_update.elapsed();
784 if idle >= quiet {
785 break state;
786 }
787 drop(state);
788 tokio::time::sleep(quiet - idle).await;
789 };
790 // A huge body waits its turn, then reads the doc as it is by then.
791 if note_model::flat::body(&state.doc).len_utf8() > HEAVY_BYTES {
792 drop(state);
793 permit = Some(HEAVY.acquire().await.expect("never closed"));
794 state = room.state.lock().await;
795 }
796 let started = std::time::Instant::now();
797 state.text_pending = false;
798 let due = state
799 .last_version
800 .as_ref()
801 .is_none_or(|(at, _)| now_millis() - at >= VERSION_EVERY_MS);
802 if due {
803 if let Err(err) = record_version(&mut state, &store, &room.note_id).await {
804 eprintln!("version record failed for note {}: {err:#}", room.note_id);
805 }
806 }
807 // A snapshot just rendered this version: only the title is left to read.
808 if let Some(markdown) = state.cached_markdown() {
809 let title = export::title_of(&state.doc);
810 state.text_cost = started.elapsed();
811 drop(state);
812 (title, markdown, Vec::new())
813 } else {
814 let body = blocking(|| export::Body::read(&state.doc));
815 let vv = state.doc.oplog_vv();
816 drop(state);
817 let read = tokio::task::spawn_blocking(move || {
818 let (title, markdown, links) = derived_body(&body);
819 (title, std::sync::Arc::new(markdown), links)
820 })
821 .await;
822 let mut state = room.state.lock().await;
823 state.text_cost = started.elapsed();
824 if let Ok((_, body, links)) = &read {
825 state.cache_markdown(vv, body.clone(), links);
826 }
827 drop(state);
828 match read {
829 Ok(out) => out,
830 Err(err) => {
831 eprintln!("text read failed for note {}: {err:#}", room.note_id);
832 return;
833 }
834 }
835 }
836 };
837 if let Err(err) = store.set_title(&room.note_id, &title).await {
838 eprintln!("title write failed for note {}: {err:#}", room.note_id);
839 }
840 if let Err(err) = store.put_text(&room.note_id, &title, &body).await {
841 eprintln!("text write failed for note {}: {err:#}", room.note_id);
842 }
843 if let Err(err) = store.set_links(&room.note_id, &links).await {
844 eprintln!("link index write failed for note {}: {err:#}", room.note_id);
845 }
846 drop(permit);
847}
848
849/// The title, searchable markdown and note links of a doc: three whole-doc reads.
850fn derived_text(doc: &LoroDoc) -> (String, String, Vec<export::LinkTarget>) {
851 derived_body(&export::Body::read(doc))
852}
853
854fn derived_body(body: &export::Body) -> (String, String, Vec<export::LinkTarget>) {
855 (body.title(), body.markdown(), body.note_links())
856}
857
858/// Takes a snapshot now, or for a huge doc once [`HEAVY`] is free: its snapshot and
859/// body would otherwise wait in memory beside the text flush that holds it.
860async fn schedule_snapshot(room: &std::sync::Arc<Room>, state: &mut RoomState, store: &std::sync::Arc<Store>) {
861 if note_model::flat::body(&state.doc).len_utf8() > HEAVY_BYTES {
862 if !state.snapshot_pending {
863 state.snapshot_pending = true;
864 tokio::spawn(heavy_snapshot(room.clone(), store.clone()));
865 }
866 return;
867 }
868 match take_snapshot(state, store, &room.note_id).await {
869 Ok(snapshot) => {
870 tokio::spawn(write_snapshot(room.clone(), store.clone(), snapshot, None));
871 }
872 Err(err) => eprintln!("snapshot failed for note {}: {err:#}", room.note_id),
873 }
874}
875
876async fn heavy_snapshot(room: std::sync::Arc<Room>, store: std::sync::Arc<Store>) {
877 let permit = HEAVY.acquire().await.expect("never closed");
878 let snapshot = {
879 let mut state = room.state.lock().await;
880 state.snapshot_pending = false;
881 if state.updates_since_snapshot == 0 {
882 return;
883 }
884 match take_snapshot(&mut state, &store, &room.note_id).await {
885 Ok(snapshot) => snapshot,
886 Err(err) => return eprintln!("snapshot failed for note {}: {err:#}", room.note_id),
887 }
888 };
889 write_snapshot(room, store, snapshot, Some(permit)).await;
890}
891
892/// Takes a snapshot of the doc and reads its body; [`write_snapshot`] renders the
893/// derived text off the room lock. The update count is read under the lock too, so the snapshot
894/// claims only updates it holds.
895async fn take_snapshot(state: &mut RoomState, store: &Store, note_id: &str) -> anyhow::Result<Snapshot> {
896 let upto_seq = store.max_seq(note_id).await?;
897 let data = blocking(|| state.doc.export(ExportMode::Snapshot))?;
898 state.updates_since_snapshot = 0;
899 state.update_bytes = 0;
900 state.snapshot_len = data.len();
901 let heavy = note_model::flat::body(&state.doc).len_utf8() > HEAVY_BYTES;
902 let body = blocking(|| export::Body::read(&state.doc));
903 Ok(Snapshot { data, body, vv: state.doc.oplog_vv(), upto_seq, heavy })
904}
905
906/// Stores a snapshot from [`take_snapshot`] with its markdown, title and links.
907async fn write_snapshot(
908 room: std::sync::Arc<Room>,
909 store: std::sync::Arc<Store>,
910 snapshot: Snapshot,
911 permit: Option<tokio::sync::SemaphorePermit<'static>>,
912) {
913 let result = async {
914 let Snapshot { data, body, vv, upto_seq, heavy } = snapshot;
915 let permit = match permit {
916 None if heavy => Some(HEAVY.acquire().await?),
917 permit => permit,
918 };
919 let ((title, markdown, links), export) =
920 tokio::task::spawn_blocking(move || {
921 let derived = derived_body(&body);
922 // Without note links the export is the markdown itself.
923 let export = if derived.2.is_empty() { None } else { body.markdown_deferred() };
924 (derived, export)
925 })
926 .await?;
927 if store.put_snapshot(&room.note_id, data, upto_seq, &markdown, &title).await? {
928 store.set_links(&room.note_id, &links).await?;
929 if let Some(export) = export {
930 store.put_export_texts(&[(room.note_id.clone(), upto_seq, export)]).await?;
931 }
932 }
933 room.state.lock().await.cache_markdown(vv, std::sync::Arc::new(markdown), &links);
934 drop(permit);
935 anyhow::Ok(())
936 }
937 .await;
938 if let Err(err) = result {
939 eprintln!("snapshot failed for note {}: {err:#}", room.note_id);
940 }
941}
942
943fn frame(tag: u8, payload: &[u8]) -> Vec<u8> {
944 let mut out = Vec::with_capacity(payload.len() + 1);
945 out.push(tag);
946 out.extend_from_slice(payload);
947 out
948}
949
950/// Drives one WebSocket connection until either side closes it.
951pub async fn serve_socket(hub: std::sync::Arc<Hub>, store: std::sync::Arc<Store>, room: std::sync::Arc<Room>, mut socket: WebSocket) {
952 let conn_id = hub.next_conn_id();
953 let mut rx = room.join().await;
954
955 if socket
956 .send(Message::binary(room.sync_req_frame().await))
957 .await
958 .is_err()
959 {
960 room.leave(&store).await;
961 return;
962 }
963 // The takes of the note, so the editor shows them from the start.
964 for frame in hub.take_frames(&room.note_id) {
965 if socket.send(Message::binary(frame)).await.is_err() {
966 room.leave(&store).await;
967 return;
968 }
969 }
970
971 loop {
972 tokio::select! {
973 incoming = socket.recv() => {
974 let message = match incoming {
975 Some(Ok(message)) => message,
976 _ => break,
977 };
978 match message {
979 Message::Binary(bytes) => {
980 if !handle_frame(&room, &store, conn_id, bytes, &mut socket).await {
981 break;
982 }
983 }
984 Message::Close(_) => break,
985 // Text frames are not part of the protocol; ping/pong are handled by topcoat.
986 _ => {}
987 }
988 }
989 event = rx.recv() => match event {
990 Ok((from, frame)) => {
991 if from != conn_id && socket.send(Message::binary(frame)).await.is_err() {
992 break;
993 }
994 }
995 Err(broadcast::error::RecvError::Lagged(_)) => {
996 // Missed frames: push every update; importing known ops is a no-op.
997 let Ok(frame) = room.all_updates_frame().await else { break };
998 if socket.send(Message::binary(frame)).await.is_err() {
999 break;
1000 }
1001 }
1002 Err(broadcast::error::RecvError::Closed) => break,
1003 }
1004 }
1005 }
1006
1007 room.leave(&store).await;
1008}
1009
1010/// Handles one inbound binary frame. Returns `false` when the socket is unusable.
1011async fn handle_frame(
1012 room: &std::sync::Arc<Room>,
1013 store: &std::sync::Arc<Store>,
1014 conn_id: u64,
1015 bytes: Bytes,
1016 socket: &mut WebSocket,
1017) -> bool {
1018 let Some(&tag) = bytes.first() else {
1019 return true;
1020 };
1021 // The frame's payload, sharing its buffer: a huge update is neither copied for the
1022 // store write nor for the other connections, which get the frame as it came.
1023 let payload = bytes.slice(1..);
1024 match tag {
1025 SYNC_REQ => match room.sync_reply(&payload).await {
1026 Ok(reply) => socket.send(Message::binary(reply)).await.is_ok(),
1027 Err(err) => {
1028 eprintln!("bad sync request on note {}: {err:#}", room.note_id);
1029 true
1030 }
1031 },
1032 UPDATE => {
1033 match room.apply_update(store, payload).await {
1034 Ok(true) => room.broadcast(conn_id, bytes),
1035 Ok(false) => {}
1036 Err(err) => eprintln!("bad update on note {}: {err:#}", room.note_id),
1037 }
1038 true
1039 }
1040 EPHEMERAL => {
1041 room.broadcast(conn_id, bytes);
1042 true
1043 }
1044 _ => true,
1045 }
1046}
1047