use crate::caller::Caller;
use crate::events::NotesEvent;
use crate::seam::Seam;
use crate::store::{Change, NotesStore};
use async_stream::stream;
use futures::Stream;
use std::sync::Arc;
use tokio::sync::broadcast::error::RecvError;
pub const LOOK_EVERY: std::time::Duration = std::time::Duration::from_secs(15);
pub const TEXT_EVERY: std::time::Duration = std::time::Duration::from_secs(1);
enum Woke {
Moved,
Due,
Heard(Result<Change, RecvError>),
}
fn text_of(doc: &crate::events::Note) -> NotesEvent {
NotesEvent::Text { id: doc.id.clone(), revision: doc.revision, body: doc.body.clone().unwrap_or_default(), by: doc.by.clone(), at: doc.at }
}
struct Following {
caller: Caller,
moved: Option<tokio::sync::watch::Receiver<u64>>,
}
impl Following {
fn of(caller: Caller) -> Self {
let moved = caller.reach().generation().map(|g| {
let mut rx = g.subscribe();
rx.mark_unchanged();
rx
});
Self { caller, moved }
}
async fn changed(&mut self) {
let expiry = async {
match self.caller.expires_at() {
Some(at) => {
let until = std::time::Duration::from_secs((at - crate::store::now()).max(0) as u64);
tokio::time::sleep(until + std::time::Duration::from_millis(5)).await
}
None => std::future::pending().await,
}
};
let generation = async {
match self.moved.as_mut() {
Some(rx) => {
if rx.changed().await.is_err() {
std::future::pending::<()>().await
}
}
None => std::future::pending().await,
}
};
tokio::select! {
() = generation => {}
() = expiry => {}
() = tokio::time::sleep(LOOK_EVERY) => {}
}
}
}
fn said(change: Change, one: bool) -> Option<NotesEvent> {
let shown = |d: crate::events::Note| if one { d } else { d.summary() };
Some(match change {
Change::Created(doc) => NotesEvent::Created { note: shown(doc) },
Change::Updated { doc, update, seq, session } => {
NotesEvent::Updated { id: doc.id.clone(), seq, update: if one { update } else { String::new() }, at: doc.at, by: doc.by.clone(), session, note: Some(doc.summary()) }
}
Change::Renamed(doc) => NotesEvent::Renamed { id: doc.id.clone(), title: doc.title.clone(), revision: doc.revision, at: doc.at, by: doc.by.clone(), note: Some(shown(doc)) },
Change::Deleted { id, at, by, .. } => NotesEvent::Deleted { id, at, by },
Change::Squashed { id, until, removed, at, by, .. } => NotesEvent::Squashed { id, until, removed, at, by },
Change::Present { present, .. } if one => NotesEvent::Present { present },
Change::Left { id, session, client, .. } if one => NotesEvent::Left { id, session, client },
Change::Present { .. } | Change::Left { .. } => return None,
Change::Asked { thread, .. } => NotesEvent::Asked { thread },
Change::Replied { thread, .. } => NotesEvent::Replied { thread },
Change::Resolved { thread, .. } => NotesEvent::Resolved { thread },
Change::SlotChanged { slot, .. } => NotesEvent::SlotChanged { id: slot.id.clone(), slot },
Change::BuildingChanged { slot, .. } => NotesEvent::BuildingChanged { id: slot.id.clone(), building: slot.building.clone(), slot },
Change::PropsChanged { slot, by, .. } => NotesEvent::PropsChanged { id: slot.id.clone(), props: slot.props.clone(), by, slot },
Change::Marked { mark, .. } => NotesEvent::MarkChanged { id: mark.id.clone(), mark },
Change::Unmarked { id, mark, .. } => NotesEvent::MarkRemoved { id, mark },
})
}
pub(crate) fn watch(store: Arc<NotesStore>, seam: Seam, user: Caller, id: Option<String>, session: Option<String>, text: bool) -> impl Stream<Item = NotesEvent> + Send + 'static {
let mut rx = store.subscribe();
stream! {
let mut _held = None;
let mut unsaid: Option<crate::events::Note> = None;
let mut due: Option<tokio::time::Instant> = None;
let mut opened = None;
if text && id.is_none() {
yield NotesEvent::Error { message: "text follows one note: name its id".into() };
return;
}
if let Some(id) = &id {
match crate::streams::reached(&store, &seam, &user, id, "notes.watch").await {
Ok(doc) => {
if let Some(session) = session.as_deref().filter(|s| !store.taken(id, s, user.principal())) {
store.arrive(id, &doc.org, session, &user.who(), true, None, None);
_held = Some(crate::presence::Held { store: Arc::clone(&store), id: id.clone(), session: session.to_string() });
}
opened = Some(doc);
}
Err(ev) => {
yield ev;
return;
}
}
}
yield NotesEvent::Watching { id: id.clone() };
if let (true, Some(doc)) = (text, opened.as_ref()) {
yield text_of(doc);
}
let mut following = Following::of(user);
loop {
let woke = tokio::select! {
biased;
() = following.changed() => Woke::Moved,
() = async { match due { Some(at) => tokio::time::sleep_until(at).await, None => std::future::pending().await } } => Woke::Due,
r = rx.recv() => Woke::Heard(r),
};
if let Err((reason, message)) = following.caller.again() {
yield NotesEvent::WatchClosed { reason, message };
return;
}
match woke {
Woke::Moved => continue,
Woke::Due => {
due = None;
if let Some(doc) = unsaid.take() {
yield text_of(&doc);
}
}
Woke::Heard(Ok(change)) => {
if id.as_deref().is_some_and(|id| id != change.id()) {
continue;
}
match seam.holds(following.caller.context(), "notes.watch", change.org()) {
Ok(true) => {}
Ok(false) => continue,
Err(message) => {
yield NotesEvent::Error { message };
return;
}
}
if let (true, Change::Updated { doc, .. }) = (text, &change) {
unsaid = Some(doc.clone());
due.get_or_insert_with(|| tokio::time::Instant::now() + TEXT_EVERY);
}
if let (Change::Updated { session: Some(from), .. }, Some(mine)) = (&change, session.as_deref()) {
if from == mine {
continue;
}
}
let gone = matches!(change, Change::Deleted { .. }) && id.is_some();
if gone {
if let Some(doc) = unsaid.take() {
yield text_of(&doc);
}
}
if let Some(ev) = said(change, id.is_some()) {
yield ev;
}
if gone {
return;
}
}
Woke::Heard(Err(RecvError::Lagged(missed))) => {
yield NotesEvent::Lagged { missed };
if let (true, Some(id)) = (text, id.as_deref()) {
if let Ok(doc) = store.get(id).await {
unsaid = Some(doc);
due.get_or_insert_with(|| tokio::time::Instant::now() + TEXT_EVERY);
}
}
}
Woke::Heard(Err(RecvError::Closed)) => return,
}
}
}
}