Skip to main content

text_document/
backend.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 Cyril Jacquet
3
4//! A backend several documents can share.
5//!
6//! Every [`TextDocument`](crate::TextDocument) built by [`TextDocument::new`](crate::TextDocument::new)
7//! owns a whole application context: a store, an undo manager, an event hub, and
8//! an OS thread draining that hub. That is right for one document and wrong for
9//! a hundred. A host that opens a document per scene of a manuscript pays a
10//! hundred threads to display one book, and each thread reserves eight megabytes
11//! of address space for a loop that is idle almost all of the time.
12//!
13//! # What can be shared, and what cannot
14//!
15//! Not the store, and not the undo stack. Every repository's `snapshot` and
16//! `restore` take and put back the **whole** store (see
17//! `Transaction::snapshot_store`), so two documents sharing one would undo and
18//! roll each other back. Each document keeps its own.
19//!
20//! The event hub can be shared, and that is where the thread is. One hub means
21//! one drain, so a backend holds one [`EventHubClient`] and one thread however
22//! many documents are built in it.
23//!
24//! # Telling one document's events from another's
25//!
26//! With a shared hub, every document's long-operation subscription sees every
27//! document's long-operation events. Each document therefore records the ids of
28//! the operations it started and ignores an event carrying any other id. The
29//! filter lives in the document, inside the lock the callback already takes, so
30//! there is no second structure to keep in step and no second lock to order
31//! against the first.
32//!
33//! # Lifetime
34//!
35//! The pump stops when the backend drops, not when a document does: a document
36//! that shut the hub down on its own way out would stop delivery for every
37//! sibling still open. Hold the backend for as long as any document built in it.
38
39use std::sync::Arc;
40
41use frontend::AppContext;
42use frontend::event_hub_client::EventHubClient;
43
44/// A shared document backend: one event hub, one pump thread, one
45/// long-operation manager, for any number of documents.
46///
47/// Cheap to clone (an `Arc`), and every clone names the same backend. Build one
48/// per project, or per whatever scope wants its documents to share a thread, and
49/// create documents in it with
50/// [`TextDocument::new_in`](crate::TextDocument::new_in).
51#[derive(Clone)]
52pub struct DocumentBackend {
53    inner: Arc<BackendInner>,
54}
55
56struct BackendInner {
57    /// The context whose hub, shutdown channel and long-operation manager every
58    /// document in this backend shares. Its own store and undo stack are unused:
59    /// each document brings its own, because undo works on a whole store.
60    ctx: AppContext,
61    /// The one drain, and the one thread. Documents subscribe here.
62    client: EventHubClient,
63}
64
65impl DocumentBackend {
66    /// Build a backend, starting its single event pump.
67    pub fn new() -> Self {
68        let ctx = AppContext::new();
69        let client = EventHubClient::new(&ctx.event_hub);
70        client.start(ctx.shutdown_rx.clone());
71        Self {
72            inner: Arc::new(BackendInner { ctx, client }),
73        }
74    }
75
76    /// The context documents built here share.
77    pub(crate) fn shared_ctx(&self) -> &AppContext {
78        &self.inner.ctx
79    }
80
81    /// The client documents built here subscribe on.
82    pub(crate) fn client(&self) -> &EventHubClient {
83        &self.inner.client
84    }
85}
86
87impl Default for DocumentBackend {
88    fn default() -> Self {
89        Self::new()
90    }
91}
92
93impl std::fmt::Debug for DocumentBackend {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        f.debug_struct("DocumentBackend")
96            .field(
97                "documents_sharing_it",
98                &(Arc::strong_count(&self.inner) - 1),
99            )
100            .finish()
101    }
102}
103
104impl Drop for BackendInner {
105    /// Stop the pump. This is the only place that may: a document doing it on
106    /// its own way out would stop delivery for every sibling still open.
107    fn drop(&mut self) {
108        self.ctx.shutdown();
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use crate::{DocumentEvent, TextDocument};
116    use frontend::common::event::{LongOperationEvent, Origin};
117    use std::sync::mpsc;
118    use std::thread;
119    use std::time::{Duration, Instant};
120
121    /// How long a step that takes microseconds is given before the test calls the
122    /// backend stuck. A deadlock fails the test the same way however long this is,
123    /// so it is generous enough that a loaded CI runner cannot fail it by being slow.
124    const LIMIT: Duration = Duration::from_secs(10);
125
126    /// A document whose last handle is dropped while the pump is inside one of its
127    /// callbacks is destroyed on the pump thread, and the backend has to survive it.
128    ///
129    /// A long-operation callback upgrades the document's weak reference for as long
130    /// as it runs. When the host drops every handle of its own meanwhile, which is
131    /// what closing a tab or ending a test does right after an import returned, that
132    /// upgrade is the last reference, and the document's subscription tokens drop on
133    /// the pump. The pump used to hold the subscriber map across every callback, so
134    /// those tokens waited on the pump itself, and every later subscribe or
135    /// unsubscribe in the backend waited on them: building or dropping any sibling
136    /// document hung the host thread for good.
137    ///
138    /// The interleaving is forced rather than hoped for. The doomed document's
139    /// `Completed` callback takes its undo manager after upgrading, so holding that
140    /// lock parks the pump inside the callback with the reference in hand for as long
141    /// as the test needs to drop its own.
142    #[test]
143    fn a_document_destroyed_on_the_pump_leaves_the_backend_usable() {
144        let backend = DocumentBackend::new();
145
146        // Registered before any document, so on a `Completed` event the pump calls
147        // it first: once it has spoken, every `Progress` event is behind the pump.
148        let (completing_tx, completing_rx) = mpsc::channel();
149        let probe = backend.client().subscribe(
150            Origin::LongOperation(LongOperationEvent::Completed),
151            move |_| {
152                let _ = completing_tx.send(());
153            },
154        );
155
156        let doomed = TextDocument::new_in(&backend);
157        // Outlives `doomed`. Dropping it afterwards is what used to hang the host.
158        let sibling = TextDocument::new_in(&backend);
159
160        // Taken before the import starts, so the pump cannot get past it first. The
161        // import itself never touches the undo manager, only the callback does.
162        let history = Arc::clone(&doomed.inner.lock().ctx.undo_redo_manager);
163        let held = history.lock();
164        let operation = doomed
165            .set_djot("Gone by the time its import is announced.")
166            .expect("start the import");
167
168        let reached_callback = completing_rx.recv_timeout(LIMIT).is_ok() && {
169            // The pump's upgrade is the second reference, beside the test's own.
170            let deadline = Instant::now() + LIMIT;
171            while Arc::strong_count(&doomed.inner) < 2 && Instant::now() < deadline {
172                thread::yield_now();
173            }
174            Arc::strong_count(&doomed.inner) >= 2
175        };
176        assert!(
177            reached_callback,
178            "the import's completion did not reach the document's callback within \
179             {LIMIT:?}, so the interleaving this test forces never happened"
180        );
181
182        // The pump now holds the only reference. Releasing the undo manager lets the
183        // callback finish and destroy the document on the pump thread.
184        drop(doomed);
185        drop(held);
186        drop(operation);
187
188        // Everything the host does next goes through the subscriber map, so it runs
189        // on a thread of its own: a backend that deadlocked fails this test instead
190        // of hanging the test binary.
191        let (outcome_tx, outcome_rx) = mpsc::channel();
192        let host_backend = backend.clone();
193        thread::spawn(move || {
194            drop(sibling);
195            let fresh = TextDocument::new_in(&host_backend);
196            let imported = fresh
197                .set_djot("Still delivered.")
198                .ok()
199                .and_then(|op| op.wait_timeout(LIMIT))
200                .is_some_and(|result| result.is_ok());
201            // `wait` only proves the worker ran. The finished event proves the pump
202            // is still delivering, since it is what bridges that event in.
203            let deadline = Instant::now() + LIMIT;
204            let mut delivered = false;
205            while imported && !delivered && Instant::now() < deadline {
206                delivered = fresh
207                    .poll_events()
208                    .iter()
209                    .any(|e| matches!(e, DocumentEvent::LongOperationFinished { .. }));
210                if !delivered {
211                    thread::sleep(Duration::from_millis(5));
212                }
213            }
214            let _ = outcome_tx.send((imported, delivered));
215        });
216
217        let outcome = outcome_rx.recv_timeout(LIMIT * 3);
218        if outcome.is_err() {
219            // Dropping the probe would lock the map the stuck pump holds, and the
220            // test would hang in its own unwinding instead of failing.
221            std::mem::forget(probe);
222        }
223        let (imported, delivered) = outcome.unwrap_or_else(|_| {
224            panic!(
225                "dropping a sibling document and building a new one in the backend did \
226                 not return within {:?} after a document was destroyed on the pump: the \
227                 pump is waiting on the subscriber map it holds itself",
228                LIMIT * 3
229            )
230        });
231        assert!(imported, "the new document's import did not complete");
232        assert!(
233            delivered,
234            "the new document's import finished but its event never arrived: the pump \
235             stopped delivering after destroying a document"
236        );
237    }
238}