use std::sync::Arc;
use frontend::AppContext;
use frontend::event_hub_client::EventHubClient;
#[derive(Clone)]
pub struct DocumentBackend {
inner: Arc<BackendInner>,
}
struct BackendInner {
ctx: AppContext,
client: EventHubClient,
}
impl DocumentBackend {
pub fn new() -> Self {
let ctx = AppContext::new();
let client = EventHubClient::new(&ctx.event_hub);
client.start(ctx.shutdown_rx.clone());
Self {
inner: Arc::new(BackendInner { ctx, client }),
}
}
pub(crate) fn shared_ctx(&self) -> &AppContext {
&self.inner.ctx
}
pub(crate) fn client(&self) -> &EventHubClient {
&self.inner.client
}
}
impl Default for DocumentBackend {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for DocumentBackend {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DocumentBackend")
.field(
"documents_sharing_it",
&(Arc::strong_count(&self.inner) - 1),
)
.finish()
}
}
impl Drop for BackendInner {
fn drop(&mut self) {
self.ctx.shutdown();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{DocumentEvent, TextDocument};
use frontend::common::event::{LongOperationEvent, Origin};
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};
const LIMIT: Duration = Duration::from_secs(10);
#[test]
fn a_document_destroyed_on_the_pump_leaves_the_backend_usable() {
let backend = DocumentBackend::new();
let (completing_tx, completing_rx) = mpsc::channel();
let probe = backend.client().subscribe(
Origin::LongOperation(LongOperationEvent::Completed),
move |_| {
let _ = completing_tx.send(());
},
);
let doomed = TextDocument::new_in(&backend);
let sibling = TextDocument::new_in(&backend);
let history = Arc::clone(&doomed.inner.lock().ctx.undo_redo_manager);
let held = history.lock();
let operation = doomed
.set_djot("Gone by the time its import is announced.")
.expect("start the import");
let reached_callback = completing_rx.recv_timeout(LIMIT).is_ok() && {
let deadline = Instant::now() + LIMIT;
while Arc::strong_count(&doomed.inner) < 2 && Instant::now() < deadline {
thread::yield_now();
}
Arc::strong_count(&doomed.inner) >= 2
};
assert!(
reached_callback,
"the import's completion did not reach the document's callback within \
{LIMIT:?}, so the interleaving this test forces never happened"
);
drop(doomed);
drop(held);
drop(operation);
let (outcome_tx, outcome_rx) = mpsc::channel();
let host_backend = backend.clone();
thread::spawn(move || {
drop(sibling);
let fresh = TextDocument::new_in(&host_backend);
let imported = fresh
.set_djot("Still delivered.")
.ok()
.and_then(|op| op.wait_timeout(LIMIT))
.is_some_and(|result| result.is_ok());
let deadline = Instant::now() + LIMIT;
let mut delivered = false;
while imported && !delivered && Instant::now() < deadline {
delivered = fresh
.poll_events()
.iter()
.any(|e| matches!(e, DocumentEvent::LongOperationFinished { .. }));
if !delivered {
thread::sleep(Duration::from_millis(5));
}
}
let _ = outcome_tx.send((imported, delivered));
});
let outcome = outcome_rx.recv_timeout(LIMIT * 3);
if outcome.is_err() {
std::mem::forget(probe);
}
let (imported, delivered) = outcome.unwrap_or_else(|_| {
panic!(
"dropping a sibling document and building a new one in the backend did \
not return within {:?} after a document was destroyed on the pump: the \
pump is waiting on the subscriber map it holds itself",
LIMIT * 3
)
});
assert!(imported, "the new document's import did not complete");
assert!(
delivered,
"the new document's import finished but its event never arrived: the pump \
stopped delivering after destroying a document"
);
}
}