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

use crate::{
    clock::DateTime,
    events::{broadcaster::Broadcaster, repo::message::Provider as _, types::ChannelEvent},
    repo::channel::{Channel, 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 channel = tx
            .channels()
            .create(name, created_at)
            .await
            .map_err(|err| CreateError::from_duplicate_name(err, name))?;
        tx.commit().await?;

        self.events
            .broadcast(&ChannelEvent::created(channel.clone()));

        Ok(channel)
    }

    pub async fn all(&self) -> Result<Vec<Channel>, InternalError> {
        let mut tx = self.db.begin().await?;
        let channels = tx.channels().all().await?;
        tx.commit().await?;

        Ok(channels)
    }

    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 sequence = tx.message_events().assign_sequence(&channel).await?;
            let event = tx
                .channels()
                .delete_expired(&channel, sequence, relative_to)
                .await?;
            events.push(event);
        }

        tx.commit().await?;

        for event in events {
            self.events.broadcast(&event);
        }

        Ok(())
    }
}

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

impl CreateError {
    fn from_duplicate_name(error: sqlx::Error, name: &str) -> Self {
        if let Some(error) = error.as_database_error() {
            if error.is_unique_violation() {
                return Self::DuplicateName(name.into());
            }
        }

        Self::from(error)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum InternalError {
    #[error(transparent)]
    DatabaseError(#[from] sqlx::Error),
}