summaryrefslogtreecommitdiff
path: root/src/channel/app.rs
blob: 46eaba8baeaf0e61b36a1e5332bf07c398e7f0f1 (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
use chrono::TimeDelta;
use itertools::Itertools;
use sqlx::sqlite::SqlitePool;

use super::{repo::Provider as _, Channel, History, Id};
use crate::{
    clock::DateTime,
    db::{Duplicate as _, NotFound as _},
    event::{repo::Provider as _, Broadcaster, Event, Sequence},
    message::repo::Provider as _,
};

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

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

    pub async fn create(&self, name: &str, created_at: &DateTime) -> Result<Channel, CreateError> {
        let mut tx = self.db.begin().await?;
        let created = tx.sequence().next(created_at).await?;
        let channel = tx
            .channels()
            .create(name, &created)
            .await
            .duplicate(|| CreateError::DuplicateName(name.into()))?;
        tx.commit().await?;

        self.events
            .broadcast(channel.events().map(Event::from).collect::<Vec<_>>());

        Ok(channel.as_created())
    }

    // This function is careless with respect to time, and gets you the channel as
    // it exists in the specific moment when you call it.
    pub async fn get(&self, channel: &Id) -> Result<Option<Channel>, sqlx::Error> {
        let mut tx = self.db.begin().await?;
        let channel = tx.channels().by_id(channel).await.optional()?;
        tx.commit().await?;

        Ok(channel.iter().flat_map(History::events).collect())
    }

    pub async fn delete(&self, channel: &Id, deleted_at: &DateTime) -> Result<(), Error> {
        let mut tx = self.db.begin().await?;

        let channel = tx
            .channels()
            .by_id(channel)
            .await
            .not_found(|| Error::NotFound(channel.clone()))?;

        let mut events = Vec::new();

        let messages = tx.messages().in_channel(&channel, None).await?;
        for message in messages {
            let deleted = tx.sequence().next(deleted_at).await?;
            let message = tx.messages().delete(message.id(), &deleted).await?;
            events.extend(
                message
                    .events()
                    .filter(Sequence::start_from(deleted.sequence))
                    .map(Event::from),
            );
        }

        let deleted = tx.sequence().next(deleted_at).await?;
        let channel = tx.channels().delete(channel.id(), &deleted).await?;
        events.extend(
            channel
                .events()
                .filter(Sequence::start_from(deleted.sequence))
                .map(Event::from),
        );

        tx.commit().await?;

        self.events.broadcast(events);

        Ok(())
    }

    pub async fn expire(&self, relative_to: &DateTime) -> Result<(), sqlx::Error> {
        // Somewhat arbitrarily, expire after 90 days.
        let expire_at = relative_to.to_owned() - TimeDelta::days(90);

        let mut tx = self.db.begin().await?;
        let expired = tx.channels().expired(&expire_at).await?;

        let mut events = Vec::with_capacity(expired.len());
        for channel in expired {
            let deleted = tx.sequence().next(relative_to).await?;
            let channel = tx.channels().delete(&channel, &deleted).await?;
            events.push(
                channel
                    .events()
                    .filter(Sequence::start_from(deleted.sequence)),
            );
        }

        tx.commit().await?;

        self.events.broadcast(
            events
                .into_iter()
                .kmerge_by(Sequence::merge)
                .map(Event::from)
                .collect::<Vec<_>>(),
        );

        Ok(())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum CreateError {
    #[error("channel named {0} already exists")]
    DuplicateName(String),
    #[error(transparent)]
    Database(#[from] sqlx::Error),
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("channel {0} not found")]
    NotFound(Id),
    #[error(transparent)]
    Database(#[from] sqlx::Error),
}