summaryrefslogtreecommitdiff
path: root/src/boot/app.rs
blob: cd45c38d6a7160c3e31d8b7cf366df61ab19ba0a (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
use sqlx::sqlite::SqlitePool;

use super::Snapshot;
use crate::{
    channel::{self, repo::Provider as _},
    event::{Heartbeat, repo::Provider as _},
    message::repo::Provider as _,
    name,
    user::{self, repo::Provider as _},
};

pub struct Boot<'a> {
    db: &'a SqlitePool,
}

impl<'a> Boot<'a> {
    pub const fn new(db: &'a SqlitePool) -> Self {
        Self { db }
    }

    pub async fn snapshot(&self) -> Result<Snapshot, Error> {
        let mut tx = self.db.begin().await?;
        let resume_point = tx.sequence().current().await?;
        let heartbeat = Heartbeat::TIMEOUT;

        let users = tx.users().all(resume_point).await?;
        let channels = tx.channels().all(resume_point).await?;
        let messages = tx.messages().all(resume_point).await?;

        tx.commit().await?;

        let users = users
            .into_iter()
            .filter_map(|user| user.as_of(resume_point))
            .collect();

        let channels = channels
            .into_iter()
            .filter_map(|channel| channel.as_of(resume_point))
            .collect();

        let messages = messages
            .into_iter()
            .filter_map(|message| message.as_of(resume_point))
            .collect();

        Ok(Snapshot {
            resume_point,
            heartbeat,
            users,
            channels,
            messages,
        })
    }
}

#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub enum Error {
    Name(#[from] name::Error),
    Database(#[from] sqlx::Error),
}

impl From<user::repo::LoadError> for Error {
    fn from(error: user::repo::LoadError) -> Self {
        use user::repo::LoadError;
        match error {
            LoadError::Name(error) => error.into(),
            LoadError::Database(error) => error.into(),
        }
    }
}

impl From<channel::repo::LoadError> for Error {
    fn from(error: channel::repo::LoadError) -> Self {
        use channel::repo::LoadError;
        match error {
            LoadError::Name(error) => error.into(),
            LoadError::Database(error) => error.into(),
        }
    }
}