Skip to main content

lb_rs/service/
events.rs

1pub use tokio::sync::broadcast::{self, Receiver, Sender};
2use tracing::*;
3use uuid::Uuid;
4
5use crate::{Lb, LbErrKind};
6
7#[derive(Clone)]
8pub struct EventSubs {
9    tx: Sender<Event>,
10}
11
12#[derive(Clone, Debug)]
13pub enum Event {
14    /// A metadata for a given id or it's descendants changed. The id returned
15    /// may be deleted. Updates to document contents will not cause this
16    /// message to be sent (unless a document was deleted).
17    MetadataChanged(Actor),
18
19    /// The contents of this document have changed either by this lb
20    /// library or as a result of sync
21    DocumentWritten(Uuid, Actor),
22
23    PendingSharesChanged,
24
25    Sync(SyncIncrement),
26
27    StatusUpdated,
28
29    UserSignedIn,
30}
31
32#[derive(Debug, Clone, PartialEq)]
33pub enum Actor {
34    /// A write initiated locally. The id identifies the writer (e.g. a
35    /// workspace instance) so subscribers can tell their own writes apart
36    /// from writes by other workspaces or tools sharing this lb.
37    User(Option<Uuid>),
38    Sync,
39}
40
41impl Default for EventSubs {
42    fn default() -> Self {
43        let (tx, _) = broadcast::channel::<Event>(10000);
44        Self { tx }
45    }
46}
47
48impl EventSubs {
49    pub(crate) fn pending_shares_changed(&self) {
50        self.queue(Event::PendingSharesChanged);
51    }
52
53    pub(crate) fn meta_changed(&self, actor: Actor) {
54        self.queue(Event::MetadataChanged(actor));
55    }
56
57    pub(crate) fn doc_written(&self, id: Uuid, actor: Actor) {
58        self.queue(Event::DocumentWritten(id, actor));
59    }
60
61    pub(crate) fn sync_update(&self, s: SyncIncrement) {
62        self.queue(Event::Sync(s));
63    }
64
65    pub(crate) fn status_updated(&self) {
66        self.queue(Event::StatusUpdated);
67    }
68
69    /// executed after root and account are created
70    pub(crate) fn signed_in(&self) {
71        self.queue(Event::UserSignedIn);
72    }
73
74    fn queue(&self, evt: Event) {
75        if let Err(e) = self.tx.send(evt.clone()) {
76            error!(?evt, ?e, "could not queue");
77        }
78    }
79}
80
81impl Lb {
82    pub fn subscribe(&self) -> Receiver<Event> {
83        self.events.tx.subscribe()
84    }
85}
86
87#[derive(Debug, Clone)]
88pub enum SyncIncrement {
89    SyncStarted,
90    PullingDocument(Uuid, bool),
91    PushingDocument(Uuid, bool),
92    SyncFinished(Option<LbErrKind>),
93}