summaryrefslogtreecommitdiff
path: root/src/channel/app.rs
blob: c060b239117c189bd00167156a3f638f0dd4e16b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
use std::collections::{hash_map::Entry, HashMap};
use std::sync::{Arc, Mutex, MutexGuard};

use futures::{
    stream::{self, StreamExt as _, TryStreamExt as _},
    Stream,
};
use sqlx::sqlite::SqlitePool;
use tokio::sync::broadcast::{channel, Sender};
use tokio_stream::wrappers::BroadcastStream;

use super::repo::{
    channels::{Id as ChannelId, Provider as _},
    messages::{Id as MessageId, Message as StoredMessage, Provider as _},
};
use crate::{
    clock::DateTime,
    error::BoxedError,
    login::repo::logins::{Login, Provider as _},
};

pub struct Channels<'a> {
    db: &'a SqlitePool,
    broadcaster: &'a Broadcaster,
}

impl<'a> Channels<'a> {
    pub const fn new(db: &'a SqlitePool, broadcaster: &'a Broadcaster) -> Self {
        Self { db, broadcaster }
    }

    pub async fn create(&self, name: &str) -> Result<(), BoxedError> {
        let mut tx = self.db.begin().await?;
        let channel = tx.channels().create(name).await?;
        self.broadcaster.register_channel(&channel);
        tx.commit().await?;

        Ok(())
    }

    pub async fn send(
        &self,
        login: &Login,
        channel: &ChannelId,
        body: &str,
        sent_at: &DateTime,
    ) -> Result<(), BoxedError> {
        let mut tx = self.db.begin().await?;
        let message = tx
            .messages()
            .create(&login.id, channel, body, sent_at)
            .await?;
        let message = Message::from_login(login, message);
        tx.commit().await?;

        self.broadcaster.broadcast(channel, message);
        Ok(())
    }

    pub async fn events(
        &self,
        channel: &ChannelId,
    ) -> Result<impl Stream<Item = Result<Message, BoxedError>>, BoxedError> {
        let live_messages = self.broadcaster.listen(channel).map_err(BoxedError::from);

        let db = self.db.clone();
        let mut tx = self.db.begin().await?;
        let stored_messages = tx.messages().all(channel).await?;
        let stored_messages = stream::iter(stored_messages).then(move |msg| {
            // The exact series of moves and clones here is the result of trial
            // and error, and is likely the best I can do, given:
            //
            // * This closure _can't_ keep a reference to self, for lifetime
            //   reasons;
            // * The closure will be executed multiple times, so it can't give
            //   up `db`; and
            // * The returned future can't keep a reference to `db` as doing
            //   so would allow refs to the closure's `db` to outlive the
            //   closure itself.
            //
            // Fortunately, cloning the pool is acceptable - sqlx pools were
            // designed to be cloned and the only thing actually cloned is a
            // single `Arc`. This whole chain of clones just ends up producing
            // cheap handles to a single underlying "real" pool.
            let db = db.clone();
            async move {
                let mut tx = db.begin().await?;
                let msg = Message::from_stored(&mut tx, msg).await?;
                tx.commit().await?;

                Ok(msg)
            }
        });
        tx.commit().await?;

        Ok(stored_messages.chain(live_messages))
    }
}

#[derive(Clone, Debug, serde::Serialize)]
pub struct Message {
    pub id: MessageId,
    pub sender: Login,
    pub body: String,
    pub sent_at: DateTime,
}

impl Message {
    async fn from_stored(
        tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
        message: StoredMessage,
    ) -> Result<Self, BoxedError> {
        let sender = tx.logins().by_id(&message.sender).await?;

        let message = Self {
            sender,
            id: message.id,
            body: message.body,
            sent_at: message.sent_at,
        };

        Ok(message)
    }

    fn from_login(sender: &Login, message: StoredMessage) -> Self {
        // Panic as this logic is enforced by the caller anyways. This "can't
        // happen," other than via programming mistakes, and cannot be fixed
        // by config changes or changing user behaviours.
        assert_eq!(
            message.sender, sender.id,
            "broadcast message must have the same sender ({}) as the stored message ({})",
            sender.id, message.sender,
        );

        Self {
            sender: sender.clone(),
            id: message.id,
            body: message.body,
            sent_at: message.sent_at,
        }
    }
}

// Clones will share the same senders collection.
#[derive(Clone)]
pub struct Broadcaster {
    // The use of std::sync::Mutex, and not tokio::sync::Mutex, follows Tokio's
    // own advice: <https://tokio.rs/tokio/tutorial/shared-state>. Methods that
    // lock it must be sync.
    senders: Arc<Mutex<HashMap<ChannelId, Sender<Message>>>>,
}

impl Broadcaster {
    pub async fn from_database(db: &SqlitePool) -> Result<Self, BoxedError> {
        let mut tx = db.begin().await?;
        let channels = tx.channels().all().await?;
        tx.commit().await?;

        let channels = channels.iter().map(|c| &c.id);
        let broadcaster = Self::new(channels);
        Ok(broadcaster)
    }

    fn new<'i>(channels: impl IntoIterator<Item = &'i ChannelId>) -> Self {
        let senders: HashMap<_, _> = channels
            .into_iter()
            .cloned()
            .map(|id| (id, Self::make_sender()))
            .collect();

        Self {
            senders: Arc::new(Mutex::new(senders)),
        }
    }

    // panic: if ``channel`` is already registered.
    pub fn register_channel(&self, channel: &ChannelId) {
        match self.senders().entry(channel.clone()) {
            // This ever happening indicates a serious logic error.
            Entry::Occupied(_) => panic!("duplicate channel registration for channel {channel}"),
            Entry::Vacant(entry) => {
                entry.insert(Self::make_sender());
            }
        }
    }

    // panic: if ``channel`` has not been previously registered, and was not
    // part of the initial set of channels.
    pub fn broadcast(&self, channel: &ChannelId, message: Message) {
        let tx = self.sender(channel);

        // Per the Tokio docs, the returned error is only used to indicate that
        // there are no receivers. In this use case, that's fine; a lack of
        // listening consumers (chat clients) when a message is sent isn't an
        // error.
        let _ = tx.send(message);
    }

    // panic: if ``channel`` has not been previously registered, and was not
    // part of the initial set of channels.
    pub fn listen(&self, channel: &ChannelId) -> BroadcastStream<Message> {
        let rx = self.sender(channel).subscribe();

        BroadcastStream::from(rx)
    }

    // panic: if ``channel`` has not been previously registered, and was not
    // part of the initial set of channels.
    fn sender(&self, channel: &ChannelId) -> Sender<Message> {
        self.senders()[channel].clone()
    }

    fn senders(&self) -> MutexGuard<HashMap<ChannelId, Sender<Message>>> {
        self.senders.lock().unwrap() // propagate panics when mutex is poisoned
    }

    fn make_sender() -> Sender<Message> {
        // Queue depth of 16 chosen entirely arbitrarily. Don't read too much
        // into it.
        let (tx, _) = channel(16);
        tx
    }
}