Skip to main content

lb_rs/service/
events.rs

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