//! Per-note live state: one in-memory `LoroDoc` per note, shared by every //! WebSocket connection editing that note. //! //! Wire protocol (binary frames, first byte is the tag): //! - `0x01` SYNC_REQ: payload is an encoded `VersionVector`. The receiver //! answers with an UPDATE containing what the requester is missing. //! - `0x02` UPDATE: payload is Loro update bytes. Imported, persisted and //! broadcast to the other connections when it changed the doc. //! - `0x03` EPHEMERAL: opaque bytes, broadcast only, never persisted. //! - `0x04` RECORDING: UTF-8 `\t`. The state of a recording take, //! sent when a connection joins and whenever it changes. Not an edit. use std::collections::{HashMap, HashSet}; use std::io; use std::path::Path; use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use bytes::Bytes; use loro::{ExportMode, Frontiers, LoroDoc, VersionVector}; use tokio::sync::{Mutex as AsyncMutex, broadcast, oneshot}; use topcoat::router::content::websocket::{Message, WebSocket}; use crate::export; use crate::media::{parts_in, part_file}; use crate::store::{Store, now_millis}; pub const SYNC_REQ: u8 = 0x01; pub const UPDATE: u8 = 0x02; pub const EPHEMERAL: u8 = 0x03; pub const RECORDING: u8 = 0x04; /// How long a lost take stays lost before it is reported ended. const LOST_FOR: Duration = Duration::from_secs(30); const SNAPSHOT_EVERY: u64 = 50; /// Bodies longer than this derive their text one at a time ([`HEAVY`]): each derivation /// holds a few copies of the text, and a 100 MB note's snapshot and text flush overlap. const HEAVY_BYTES: usize = 16 << 20; static HEAVY: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(1); /// Least time between two versions recorded while the note is being edited. const VERSION_EVERY_MS: i64 = 10 * 60 * 1000; /// Quiet time after the last applied update before the searchable text is written. const TEXT_FLUSH_DELAY: Duration = Duration::from_secs(2); const CHANNEL_CAPACITY: usize = 256; /// A broadcast item: the connection id that sent it, and the full frame. type Frame = (u64, Bytes); /// The state of a recording take, as the editor shows it. #[derive(Clone, Copy, PartialEq, Eq)] pub enum TakeState { /// A socket is attached to a part of the take. Live, /// A socket died without `end` and nothing has come back yet. Lost, /// The take is over. Only sent, never kept. Ended, } impl TakeState { fn as_str(self) -> &'static str { match self { TakeState::Live => "live", TakeState::Lost => "lost", TakeState::Ended => "ended", } } } /// How a part's socket stopped: with `end`, or any other way. #[derive(Clone, Copy)] pub enum Detach { Ended, Lost, } /// A socket's attachment to a part: what [`Hub::attach`] answers. pub struct Attachment { pub part: u32, /// Tells this attachment from a later one on the same part. pub token: u64, /// Fires when another socket takes the part over. pub stop: oneshot::Receiver<()>, } /// A recording take in memory, keyed by its session id. struct Take { state: TakeState, /// The part numbers a socket is attached to. attached: HashMap, /// Counts the changes, so a lost take's timer can tell it changed since. version: u64, } /// A socket attached to a part. struct Slot { token: u64, stop: oneshot::Sender<()>, } pub struct Hub { rooms: Mutex>>, next_conn: AtomicU64, /// One lock per note whose doc is being built from imported markdown. building: Mutex>>>, /// Woken when an import leaves a doc to build. pending: tokio::sync::Notify, /// One import at a time builds its doc before answering (see [`Hub::build_now`]). inline: tokio::sync::Semaphore, /// Recording takes by note, then by session id. Also locks the choice of a new part. takes: Mutex>>, } impl Hub { pub fn new() -> Self { Self { rooms: Mutex::new(HashMap::new()), next_conn: AtomicU64::new(1), building: Mutex::new(HashMap::new()), pending: tokio::sync::Notify::new(), inline: tokio::sync::Semaphore::new(1), takes: Mutex::new(HashMap::new()), } } /// Wakes [`build_pending`](Self::build_pending) after an import stored markdown /// without a doc. pub fn doc_pending(&self) { self.pending.notify_one(); } /// Builds the doc of a just imported note before the import answers, so the note /// opens without waiting for it. Only one import at a time does: the others, and /// any build that fails, are left to [`build_pending`](Self::build_pending), which /// keeps the memory of many big imports at once bounded. pub async fn build_now(&self, store: &Store, note_id: &str) { let Ok(_permit) = self.inline.try_acquire() else { return self.doc_pending() }; if let Err(err) = self.ensure_doc(store, note_id, false).await { eprintln!("building the doc of note {note_id} failed: {err:#}"); self.doc_pending(); } } /// Builds the docs of imported notes in the background, one at a time. pub async fn build_pending(&self, store: &Store) { loop { match store.pending_docs().await { Ok(ids) => { for id in ids { if let Err(err) = self.ensure_doc(store, &id, true).await { eprintln!("building the doc of note {id} failed: {err:#}"); } } } Err(err) => eprintln!("reading pending docs failed: {err:#}"), } self.pending.notified().await; } } /// Snapshots the notes whose updates outgrew their snapshot, which happens when the /// server stops before a due snapshot is written. Until then every load of such a /// note replays its updates, and an export renders it from scratch. pub async fn compact_stale(&self, store: &Store) { let ids = match store.stale_snapshots().await { Ok(ids) => ids, Err(err) => return eprintln!("finding stale snapshots failed: {err:#}"), }; for id in ids { // An open room snapshots on its own. if self.rooms.lock().unwrap().contains_key(&id) { continue; } let result = async { let upto_seq = store.max_seq(&id).await?; let (doc, _, _, _) = load_doc(store, &id).await?; let (data, (title, markdown, links), export) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> { Ok((doc.export(ExportMode::Snapshot)?, derived_text(&doc), export::to_markdown_deferred(&doc))) }) .await??; if store.put_snapshot(&id, data, upto_seq, &markdown, &title).await? { store.set_links(&id, &links).await?; if let Some(export) = export { store.put_export_texts(&[(id.clone(), upto_seq, export)]).await?; } } anyhow::Ok(()) } .await; if let Err(err) = result { eprintln!("snapshot failed for note {id}: {err:#}"); } } } /// Builds the note's doc from its imported markdown if that has not happened yet. /// A big import stores only the markdown, since a doc of a million blocks takes /// Loro some 15 s to build and snapshot. /// /// The background builder (`skip_busy`) leaves a note alone that is being built: /// waiting on it would count as someone opening the note, and keep its doc in memory. async fn ensure_doc(&self, store: &Store, note_id: &str, skip_busy: bool) -> anyhow::Result<()> { let lock = { let mut building = self.building.lock().unwrap(); if skip_busy && building.contains_key(note_id) { return Ok(()); } building.entry(note_id.to_owned()).or_default().clone() }; let mut guard = Some(lock.lock().await); let result = async { // A builder before us may have handed its doc to a room, still storing it. if self.rooms.lock().unwrap().contains_key(note_id) { return Ok(()); } let Some(markdown) = store.pending_markdown(note_id).await? else { return Ok(()) }; let (doc, snapshot, title, body, links) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> { let doc = crate::import::markdown_to_doc(&markdown)?; // The text read overlaps the export: together about 1 s sooner. let (snapshot, (title, body, links)) = std::thread::scope(|s| { let text = s.spawn(|| derived_text(&doc)); (doc.export(ExportMode::Snapshot), text.join().unwrap()) }); Ok((doc, snapshot?, title, body, links)) }) .await??; let body = std::sync::Arc::new(body); // Someone waits to open the note: give them the doc now, not after the store // takes its 100+ MB of text (a second for a huge note). Edits stored meanwhile // land after the snapshot, which covers no updates (`upto_seq` 0). Nobody // waiting, the doc is dropped, so a bulk import keeps no docs in memory. if std::sync::Arc::strong_count(&lock) > 2 { let markdown = links.is_empty().then(|| (doc.oplog_vv(), body.clone())); let last_version = load_last_version(store, note_id).await?; let room = std::sync::Arc::new(Room::new(note_id, doc, last_version, snapshot.len(), markdown, 0)); self.rooms.lock().unwrap().entry(note_id.to_owned()).or_insert(room); guard.take(); } else { drop(doc); } store.finish_pending(note_id, &snapshot, &title, &body, &links).await } .await; drop(guard); let mut building = self.building.lock().unwrap(); if std::sync::Arc::strong_count(&lock) == 2 { building.remove(note_id); } result } /// Returns the live room for `note_id`, loading it from the store on first use. /// Rooms are kept in memory after their last connection leaves, so a room is /// never orphaned while a connection still holds it. pub async fn room(&self, store: &Store, note_id: &str) -> anyhow::Result> { let existing = self .rooms .lock() .unwrap() .get(note_id) .cloned(); if let Some(room) = existing { *room.used.lock().unwrap() = std::time::Instant::now(); return Ok(room); } // Load without holding the map lock: this awaits the store. self.ensure_doc(store, note_id, false).await?; if let Some(room) = self.rooms.lock().unwrap().get(note_id).cloned() { return Ok(room); } let (doc, stored, markdown, updates) = load_doc(store, note_id).await?; let markdown = match markdown { Some(md) if !store.has_links(note_id).await? => Some((doc.oplog_vv(), std::sync::Arc::new(md))), _ => None, }; let last_version = load_last_version(store, note_id).await?; let room = std::sync::Arc::new(Room::new(note_id, doc, last_version, stored, markdown, updates)); // Another task may have loaded the same note meanwhile; keep the first one. let mut rooms = self.rooms.lock().unwrap(); Ok(rooms .entry(note_id.to_owned()) .or_insert(room) .clone()) } /// Unloads rooms nobody has used for a while, so the docs of notes opened once do /// not stay in memory for good. Only a room nothing else holds and with every update /// stored goes: the next use loads the same doc from the store. pub async fn evict_idle(&self) { const IDLE: Duration = Duration::from_secs(5 * 60); loop { tokio::time::sleep(Duration::from_secs(30)).await; self.rooms.lock().unwrap().retain(|_, room| { let idle = room.used.lock().unwrap().elapsed() >= IDLE; let held = std::sync::Arc::strong_count(room) > 1; let writing = room.queued.load(Ordering::Acquire) > 0; // A locked state is in use. let quiet = room.state.try_lock().is_ok_and(|s| s.conns == 0 && !s.text_pending && s.last_update.elapsed() >= IDLE); !(idle && !held && !writing && quiet) }); } } /// Drops the in-memory room for a deleted note. Connections still holding the /// room keep working until they leave; nothing new is loaded for this id. pub fn forget(&self, note_id: &str) { self.rooms.lock().unwrap().remove(note_id); } fn next_conn_id(&self) -> u64 { self.next_conn.fetch_add(1, Ordering::Relaxed) } /// Attaches a socket to a part of take `session` of `note`, and makes the take live. With /// `part` None the socket gets a new part, created now, numbered after the take's last part. /// With `part` given it gets that part, which must exist, and a socket already on it stops. /// Answers `None` when that part does not exist. `dir` is the take's folder. pub fn attach(&self, note: &str, session: &str, part: Option, dir: &Path) -> io::Result> { let mut takes = self.takes.lock().unwrap(); let part = match part { Some(part) if !part_file(dir, part).is_file() => return Ok(None), Some(part) => part, None => { let part = parts_in(dir)?.last().map_or(0, |(n, _)| n + 1); std::fs::OpenOptions::new().write(true).create_new(true).open(part_file(dir, part))?; part } }; let token = self.next_conn_id(); let (stop, stopped) = oneshot::channel(); let take = takes .entry(note.to_owned()) .or_default() .entry(session.to_owned()) .or_insert_with(|| Take { state: TakeState::Ended, attached: HashMap::new(), version: 0 }); take.version += 1; if let Some(old) = take.attached.insert(part, Slot { token, stop }) { let _ = old.stop.send(()); } let changed = take.state != TakeState::Live; take.state = TakeState::Live; drop(takes); if changed { self.publish(note, session, TakeState::Live); } Ok(Some(Attachment { part, token, stop: stopped })) } /// Detaches the socket `token` from `part` of a take. Once no part is attached the take is /// ended by `end`, and lost otherwise: a lost take becomes ended after [`LOST_FOR`] unless it /// changes first. A socket that was taken over no longer matches its token, so this does /// nothing for it. pub fn detach(self: &std::sync::Arc, note: &str, session: &str, part: u32, token: u64, how: Detach) { let mut takes = self.takes.lock().unwrap(); let Some(sessions) = takes.get_mut(note) else { return }; let Some(take) = sessions.get_mut(session) else { return }; if take.attached.get(&part).is_none_or(|slot| slot.token != token) { return; } take.attached.remove(&part); take.version += 1; if !take.attached.is_empty() { return; } let version = take.version; match how { Detach::Ended => { sessions.remove(session); if sessions.is_empty() { takes.remove(note); } drop(takes); self.publish(note, session, TakeState::Ended); } Detach::Lost => { take.state = TakeState::Lost; drop(takes); self.publish(note, session, TakeState::Lost); let hub = self.clone(); let (note, session) = (note.to_owned(), session.to_owned()); tokio::spawn(async move { tokio::time::sleep(LOST_FOR).await; hub.expire(¬e, &session, version); }); } } } /// Ends a lost take that has not changed since `version`. fn expire(&self, note: &str, session: &str, version: u64) { let mut takes = self.takes.lock().unwrap(); let Some(sessions) = takes.get_mut(note) else { return }; let due = sessions .get(session) .is_some_and(|take| take.state == TakeState::Lost && take.version == version); if !due { return; } sessions.remove(session); if sessions.is_empty() { takes.remove(note); } drop(takes); self.publish(note, session, TakeState::Ended); } /// The part numbers of `session` that a socket is attached to. pub fn attached(&self, session: &str) -> HashSet { let takes = self.takes.lock().unwrap(); let note = session.split('.').next().unwrap_or_default(); takes .get(note) .and_then(|sessions| sessions.get(session)) .map(|take| take.attached.keys().copied().collect()) .unwrap_or_default() } /// A RECORDING frame for each take of `note` that is live or lost, sent to a connection that /// just joined. pub fn take_frames(&self, note: &str) -> Vec { let takes = self.takes.lock().unwrap(); takes .get(note) .map(|sessions| sessions.iter().map(|(session, take)| recording_frame(session, take.state)).collect()) .unwrap_or_default() } /// Sends a take's state to the note's room, if the room is loaded. Its connections forward it. fn publish(&self, note: &str, session: &str, state: TakeState) { let room = self.rooms.lock().unwrap().get(note).cloned(); if let Some(room) = room { room.broadcast(0, recording_frame(session, state)); } } } /// A RECORDING frame: the take's session id and state. fn recording_frame(session: &str, state: TakeState) -> Bytes { Bytes::from(frame(RECORDING, format!("{session}\t{}", state.as_str()).as_bytes())) } impl Default for Hub { fn default() -> Self { Self::new() } } /// Update holding the body of a new note: one empty paragraph. Written once at note /// creation so clients never race to initialise it. pub fn initial_note_update() -> anyhow::Result> { let doc = LoroDoc::new(); note_model::flat::init(&doc)?; doc.commit(); Ok(doc.export(ExportMode::all_updates())?) } /// The newest recorded version of a note, with its time in millis. async fn load_last_version(store: &Store, note_id: &str) -> anyhow::Result> { match store.list_versions(note_id).await?.into_iter().next() { Some((at, bytes)) => Ok(Some((at, Frontiers::decode(&bytes)?))), None => Ok(None), } } /// The note's doc, how many bytes it is stored in, its stored markdown when that is up /// to date, and how many updates it has after its snapshot. /// Runs whole-doc work (imports, exports, reads of a huge note take seconds) without /// stalling the other tasks on this runtime thread, such as page requests. fn blocking(f: impl FnOnce() -> T) -> T { tokio::task::block_in_place(f) } pub async fn load_doc(store: &Store, note_id: &str) -> anyhow::Result<(LoroDoc, usize, Option, u64)> { let bytes = store.load_doc(note_id).await?; let doc = LoroDoc::new(); let mut stored = 0; if let Some(snapshot) = bytes.snapshot { stored += snapshot.len(); blocking(|| doc.import(&snapshot))?; } let updates = bytes.updates.len() as u64; for update in bytes.updates { stored += update.len(); blocking(|| doc.import(&update))?; } Ok((doc, stored, bytes.markdown, updates)) } struct RoomState { doc: LoroDoc, /// Live WebSocket connections on this room. conns: usize, updates_since_snapshot: u64, /// Bytes of the updates since the last snapshot, and the size of that snapshot: a /// snapshot costs time in proportion to the doc, so a huge doc takes one rarely. update_bytes: usize, snapshot_len: usize, /// How long the last searchable-text read took, and when the last update came: the /// read waits for a pause in typing that long, so a huge doc is not re-read over /// and over while someone types. text_cost: Duration, last_update: std::time::Instant, /// A searchable-text flush is scheduled and has not read the doc yet. text_pending: bool, /// A huge doc's snapshot waits for [`HEAVY`] and has not been taken yet. snapshot_pending: bool, /// Time in millis and frontiers of the newest recorded version. last_version: Option<(i64, Frontiers)>, /// The doc's markdown at a version, kept only while the doc has no note links: /// then it is also the export, which a huge doc takes seconds to write. markdown: Option<(VersionVector, std::sync::Arc)>, } impl RoomState { /// Keeps `markdown`, read at `vv`, if the doc is still at that version. fn cache_markdown(&mut self, vv: VersionVector, markdown: std::sync::Arc, links: &[export::LinkTarget]) { self.markdown = (links.is_empty() && vv == self.doc.oplog_vv()).then(|| (vv, markdown)); } fn cached_markdown(&self) -> Option> { let (vv, md) = self.markdown.as_ref()?; (*vv == self.doc.oplog_vv()).then(|| md.clone()) } } /// A snapshot taken under the room lock, still to be stored with its derived text. struct Snapshot { data: Vec, /// The doc's body at the snapshot, for its derived text. body: export::Body, vv: VersionVector, upto_seq: i64, heavy: bool, } pub struct Room { note_id: String, tx: broadcast::Sender, state: AsyncMutex, /// Client updates on their way to the store, in order (see `apply_update`). writes: std::sync::OnceLock>, /// How many of those are not stored yet. queued: std::sync::Arc, /// When the room was last handed out (see [`Hub::evict_idle`]). used: Mutex, } impl Room { fn new( note_id: &str, doc: LoroDoc, last_version: Option<(i64, Frontiers)>, stored: usize, markdown: Option<(VersionVector, std::sync::Arc)>, updates: u64, ) -> Self { let (tx, _) = broadcast::channel(CHANNEL_CAPACITY); Self { note_id: note_id.to_owned(), tx, state: AsyncMutex::new(RoomState { doc, conns: 0, updates_since_snapshot: updates, update_bytes: 0, snapshot_len: stored, text_cost: Duration::ZERO, last_update: std::time::Instant::now(), text_pending: false, snapshot_pending: false, last_version, markdown, }), writes: std::sync::OnceLock::new(), queued: Default::default(), used: Mutex::new(std::time::Instant::now()), } } /// Registers a connection. The receiver is created under the same lock as the /// connection count, so no broadcast can be missed between join and first recv. async fn join(&self) -> broadcast::Receiver { let mut state = self.state.lock().await; state.conns += 1; self.tx.subscribe() } /// Records a version and persists a snapshot when the last connection leaves. async fn leave(self: &std::sync::Arc, store: &std::sync::Arc) { let mut state = self.state.lock().await; state.conns = state.conns.saturating_sub(1); if state.conns == 0 { if let Err(err) = record_version(&mut state, store, &self.note_id).await { eprintln!("version record failed for note {}: {err:#}", self.note_id); } // A reload leaves and joins again: only new updates are worth a snapshot. if state.updates_since_snapshot > 0 { schedule_snapshot(self, &mut state, store).await; } } } /// Frame announcing our version vector, so the peer can send what we lack. pub async fn sync_req_frame(&self) -> Vec { let state = self.state.lock().await; frame(SYNC_REQ, &state.doc.oplog_vv().encode()) } /// Answers a SYNC_REQ payload with an UPDATE frame of what the peer lacks. async fn sync_reply(&self, payload: &[u8]) -> anyhow::Result> { let state = self.state.lock().await; let vv = VersionVector::decode(payload)?; // A fresh peer gets a snapshot: it loads lazily instead of replaying every op. let mode = if vv.is_empty() { ExportMode::Snapshot } else { ExportMode::updates(&vv) }; let updates = blocking(|| state.doc.export(mode))?; Ok(frame(UPDATE, &updates)) } async fn all_updates_frame(&self) -> anyhow::Result> { let state = self.state.lock().await; Ok(frame(UPDATE, &blocking(|| state.doc.export(ExportMode::all_updates()))?)) } /// Imports an UPDATE payload. Returns `true` when it changed the doc, in which /// case it should be broadcast. The store write is queued, not awaited: one write /// of a huge note's text holds the store for seconds, and collaborators would see /// every keystroke that much later. A snapshot only covers updates the doc has /// already imported, and a client resends on reconnect what the server lacks, so /// order and a write lost in a crash are both harmless. async fn apply_update(self: &std::sync::Arc, store: &std::sync::Arc, payload: Bytes) -> anyhow::Result { let mut state = self.state.lock().await; let before = state.doc.oplog_vv(); blocking(|| state.doc.import(&payload))?; if state.doc.oplog_vv() == before { return Ok(false); } let writes = self.writes.get_or_init(|| { let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::(); let (store, note_id, queued) = (store.clone(), self.note_id.clone(), self.queued.clone()); tokio::spawn(async move { while let Some(update) = rx.recv().await { if let Err(err) = store.append_update(¬e_id, &update).await { eprintln!("update write failed for note {note_id}: {err:#}"); } queued.fetch_sub(1, Ordering::Release); } }); tx }); self.queued.fetch_add(1, Ordering::Acquire); let len = payload.len(); let _ = writes.send(payload); count_update(self, &mut state, store, len).await?; Ok(true) } /// The document as it was at `frontiers`, as HTML. The live doc is not changed. pub async fn html_at(&self, frontiers: &Frontiers) -> anyhow::Result { let state = self.state.lock().await; let forked = state.doc.fork_at(frontiers)?; Ok(export::to_html(&forked)) } /// Makes the doc match an earlier version. The change is a new edit on top of the /// history, so it is persisted and broadcast like a client update. The state before /// and after the restore are both recorded as versions, so the restore can be undone. pub async fn restore(self: &std::sync::Arc, store: &std::sync::Arc, frontiers: &Frontiers) -> anyhow::Result<()> { let mut state = self.state.lock().await; let vv_before = state.doc.oplog_vv(); record_version(&mut state, store, &self.note_id).await?; state.doc.revert_to(frontiers)?; state.doc.commit(); if state.doc.oplog_vv() == vv_before { return Ok(()); } let update = blocking(|| state.doc.export(ExportMode::updates(&vv_before)))?; persist_update(self, &mut state, store, &update).await?; // Connection 0 never exists, so every connection receives the restore. self.broadcast(0, frame(UPDATE, &update).into()); record_version(&mut state, store, &self.note_id).await } fn broadcast(&self, conn_id: u64, frame: Bytes) { // Err only means there are no receivers, which is fine. let _ = self.tx.send((conn_id, frame)); } /// Live markdown of the in-memory doc, with note links written as `[[Title]]`. pub async fn markdown_with(&self, store: &Store) -> anyhow::Result { let body = { let state = self.state.lock().await; if let Some(md) = state.cached_markdown() { return Ok(md.to_string()); } blocking(|| export::Body::read(&state.doc)) }; let ids: Vec = body .note_links() .into_iter() .filter_map(|t| match t { export::LinkTarget::Id(id) => Some(id), export::LinkTarget::Title(_) => None, }) .collect(); let titles = store.titles_of(ids).await?; Ok(tokio::task::spawn_blocking(move || body.markdown_with(&|id| titles.get(id).cloned())).await?) } pub async fn html(&self) -> anyhow::Result { self.read(|body| body.html()).await } /// Runs a whole-document read on a blocking thread. Only reading the body holds the /// room (one pass over the text, ~50 ms for 100 MB): rendering it does not. async fn read(&self, f: impl FnOnce(&export::Body) -> T + Send + 'static) -> anyhow::Result { let state = self.state.lock().await; let body = blocking(|| export::Body::read(&state.doc)); drop(state); Ok(tokio::task::spawn_blocking(move || f(&body)).await?) } /// The editor's markup for the doc, shown until the editor takes over. pub async fn editor_html(&self) -> String { let state = self.state.lock().await; note_model::render::preview_html(&state.doc, 128, 100_000) } } /// Stores a changed update, counts it towards the next snapshot, and schedules the /// searchable-text flush. The caller has already imported the update into `state`. async fn persist_update( room: &std::sync::Arc, state: &mut RoomState, store: &std::sync::Arc, payload: &[u8], ) -> anyhow::Result<()> { store.append_update(&room.note_id, payload).await?; count_update(room, state, store, payload.len()).await } /// Counts a stored or queued update towards the next snapshot, and schedules the /// searchable-text flush. async fn count_update(room: &std::sync::Arc, state: &mut RoomState, store: &std::sync::Arc, len: usize) -> anyhow::Result<()> { state.updates_since_snapshot += 1; state.update_bytes += len; state.last_update = std::time::Instant::now(); if state.updates_since_snapshot >= SNAPSHOT_EVERY && state.update_bytes * 16 >= state.snapshot_len { schedule_snapshot(room, state, store).await; } if !state.text_pending { state.text_pending = true; tokio::spawn(flush_text(room.clone(), store.clone())); } Ok(()) } /// Records the doc's current frontiers as a version, unless they are the same as the /// newest recorded version. async fn record_version(state: &mut RoomState, store: &Store, note_id: &str) -> anyhow::Result<()> { let frontiers = state.doc.oplog_frontiers(); if state.last_version.as_ref().is_some_and(|(_, last)| *last == frontiers) { return Ok(()); } let at = now_millis(); store.add_version(note_id, at, &frontiers.encode()).await?; state.last_version = Some((at, frontiers)); Ok(()) } /// Writes the note's title and searchable text after typing pauses. The flag is /// cleared before the doc is read, so an update that arrives during the write /// schedules a new flush. A version is recorded when the last one is 10 minutes old. async fn flush_text(room: std::sync::Arc, store: std::sync::Arc) { let mut permit = None; let (title, body, links) = { let mut state = loop { let state = room.state.lock().await; let quiet = TEXT_FLUSH_DELAY.max(state.text_cost * 2); let idle = state.last_update.elapsed(); if idle >= quiet { break state; } drop(state); tokio::time::sleep(quiet - idle).await; }; // A huge body waits its turn, then reads the doc as it is by then. if note_model::flat::body(&state.doc).len_utf8() > HEAVY_BYTES { drop(state); permit = Some(HEAVY.acquire().await.expect("never closed")); state = room.state.lock().await; } let started = std::time::Instant::now(); state.text_pending = false; let due = state .last_version .as_ref() .is_none_or(|(at, _)| now_millis() - at >= VERSION_EVERY_MS); if due { if let Err(err) = record_version(&mut state, &store, &room.note_id).await { eprintln!("version record failed for note {}: {err:#}", room.note_id); } } // A snapshot just rendered this version: only the title is left to read. if let Some(markdown) = state.cached_markdown() { let title = export::title_of(&state.doc); state.text_cost = started.elapsed(); drop(state); (title, markdown, Vec::new()) } else { let body = blocking(|| export::Body::read(&state.doc)); let vv = state.doc.oplog_vv(); drop(state); let read = tokio::task::spawn_blocking(move || { let (title, markdown, links) = derived_body(&body); (title, std::sync::Arc::new(markdown), links) }) .await; let mut state = room.state.lock().await; state.text_cost = started.elapsed(); if let Ok((_, body, links)) = &read { state.cache_markdown(vv, body.clone(), links); } drop(state); match read { Ok(out) => out, Err(err) => { eprintln!("text read failed for note {}: {err:#}", room.note_id); return; } } } }; if let Err(err) = store.set_title(&room.note_id, &title).await { eprintln!("title write failed for note {}: {err:#}", room.note_id); } if let Err(err) = store.put_text(&room.note_id, &title, &body).await { eprintln!("text write failed for note {}: {err:#}", room.note_id); } if let Err(err) = store.set_links(&room.note_id, &links).await { eprintln!("link index write failed for note {}: {err:#}", room.note_id); } drop(permit); } /// The title, searchable markdown and note links of a doc: three whole-doc reads. fn derived_text(doc: &LoroDoc) -> (String, String, Vec) { derived_body(&export::Body::read(doc)) } fn derived_body(body: &export::Body) -> (String, String, Vec) { (body.title(), body.markdown(), body.note_links()) } /// Takes a snapshot now, or for a huge doc once [`HEAVY`] is free: its snapshot and /// body would otherwise wait in memory beside the text flush that holds it. async fn schedule_snapshot(room: &std::sync::Arc, state: &mut RoomState, store: &std::sync::Arc) { if note_model::flat::body(&state.doc).len_utf8() > HEAVY_BYTES { if !state.snapshot_pending { state.snapshot_pending = true; tokio::spawn(heavy_snapshot(room.clone(), store.clone())); } return; } match take_snapshot(state, store, &room.note_id).await { Ok(snapshot) => { tokio::spawn(write_snapshot(room.clone(), store.clone(), snapshot, None)); } Err(err) => eprintln!("snapshot failed for note {}: {err:#}", room.note_id), } } async fn heavy_snapshot(room: std::sync::Arc, store: std::sync::Arc) { let permit = HEAVY.acquire().await.expect("never closed"); let snapshot = { let mut state = room.state.lock().await; state.snapshot_pending = false; if state.updates_since_snapshot == 0 { return; } match take_snapshot(&mut state, &store, &room.note_id).await { Ok(snapshot) => snapshot, Err(err) => return eprintln!("snapshot failed for note {}: {err:#}", room.note_id), } }; write_snapshot(room, store, snapshot, Some(permit)).await; } /// Takes a snapshot of the doc and reads its body; [`write_snapshot`] renders the /// derived text off the room lock. The update count is read under the lock too, so the snapshot /// claims only updates it holds. async fn take_snapshot(state: &mut RoomState, store: &Store, note_id: &str) -> anyhow::Result { let upto_seq = store.max_seq(note_id).await?; let data = blocking(|| state.doc.export(ExportMode::Snapshot))?; state.updates_since_snapshot = 0; state.update_bytes = 0; state.snapshot_len = data.len(); let heavy = note_model::flat::body(&state.doc).len_utf8() > HEAVY_BYTES; let body = blocking(|| export::Body::read(&state.doc)); Ok(Snapshot { data, body, vv: state.doc.oplog_vv(), upto_seq, heavy }) } /// Stores a snapshot from [`take_snapshot`] with its markdown, title and links. async fn write_snapshot( room: std::sync::Arc, store: std::sync::Arc, snapshot: Snapshot, permit: Option>, ) { let result = async { let Snapshot { data, body, vv, upto_seq, heavy } = snapshot; let permit = match permit { None if heavy => Some(HEAVY.acquire().await?), permit => permit, }; let ((title, markdown, links), export) = tokio::task::spawn_blocking(move || { let derived = derived_body(&body); // Without note links the export is the markdown itself. let export = if derived.2.is_empty() { None } else { body.markdown_deferred() }; (derived, export) }) .await?; if store.put_snapshot(&room.note_id, data, upto_seq, &markdown, &title).await? { store.set_links(&room.note_id, &links).await?; if let Some(export) = export { store.put_export_texts(&[(room.note_id.clone(), upto_seq, export)]).await?; } } room.state.lock().await.cache_markdown(vv, std::sync::Arc::new(markdown), &links); drop(permit); anyhow::Ok(()) } .await; if let Err(err) = result { eprintln!("snapshot failed for note {}: {err:#}", room.note_id); } } fn frame(tag: u8, payload: &[u8]) -> Vec { let mut out = Vec::with_capacity(payload.len() + 1); out.push(tag); out.extend_from_slice(payload); out } /// Drives one WebSocket connection until either side closes it. pub async fn serve_socket(hub: std::sync::Arc, store: std::sync::Arc, room: std::sync::Arc, mut socket: WebSocket) { let conn_id = hub.next_conn_id(); let mut rx = room.join().await; if socket .send(Message::binary(room.sync_req_frame().await)) .await .is_err() { room.leave(&store).await; return; } // The takes of the note, so the editor shows them from the start. for frame in hub.take_frames(&room.note_id) { if socket.send(Message::binary(frame)).await.is_err() { room.leave(&store).await; return; } } loop { tokio::select! { incoming = socket.recv() => { let message = match incoming { Some(Ok(message)) => message, _ => break, }; match message { Message::Binary(bytes) => { if !handle_frame(&room, &store, conn_id, bytes, &mut socket).await { break; } } Message::Close(_) => break, // Text frames are not part of the protocol; ping/pong are handled by topcoat. _ => {} } } event = rx.recv() => match event { Ok((from, frame)) => { if from != conn_id && socket.send(Message::binary(frame)).await.is_err() { break; } } Err(broadcast::error::RecvError::Lagged(_)) => { // Missed frames: push every update; importing known ops is a no-op. let Ok(frame) = room.all_updates_frame().await else { break }; if socket.send(Message::binary(frame)).await.is_err() { break; } } Err(broadcast::error::RecvError::Closed) => break, } } } room.leave(&store).await; } /// Handles one inbound binary frame. Returns `false` when the socket is unusable. async fn handle_frame( room: &std::sync::Arc, store: &std::sync::Arc, conn_id: u64, bytes: Bytes, socket: &mut WebSocket, ) -> bool { let Some(&tag) = bytes.first() else { return true; }; // The frame's payload, sharing its buffer: a huge update is neither copied for the // store write nor for the other connections, which get the frame as it came. let payload = bytes.slice(1..); match tag { SYNC_REQ => match room.sync_reply(&payload).await { Ok(reply) => socket.send(Message::binary(reply)).await.is_ok(), Err(err) => { eprintln!("bad sync request on note {}: {err:#}", room.note_id); true } }, UPDATE => { match room.apply_update(store, payload).await { Ok(true) => room.broadcast(conn_id, bytes), Ok(false) => {} Err(err) => eprintln!("bad update on note {}: {err:#}", room.note_id), } true } EPHEMERAL => { room.broadcast(conn_id, bytes); true } _ => true, } }