atuin_server_database/
lib.rs

1#![forbid(unsafe_code)]
2
3pub mod calendar;
4pub mod models;
5
6use std::{
7    collections::HashMap,
8    fmt::{Debug, Display},
9    ops::Range,
10};
11
12use self::{
13    calendar::{TimePeriod, TimePeriodInfo},
14    models::{History, NewHistory, NewSession, NewUser, Session, User},
15};
16use async_trait::async_trait;
17use atuin_common::record::{EncryptedData, HostId, Record, RecordIdx, RecordStatus};
18use serde::{Deserialize, Serialize};
19use time::{Date, Duration, Month, OffsetDateTime, Time, UtcOffset};
20use tracing::instrument;
21
22#[derive(Debug)]
23pub enum DbError {
24    NotFound,
25    Other(eyre::Report),
26}
27
28impl Display for DbError {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        write!(f, "{self:?}")
31    }
32}
33
34impl<T: std::error::Error + Into<time::error::Error>> From<T> for DbError {
35    fn from(value: T) -> Self {
36        DbError::Other(value.into().into())
37    }
38}
39
40impl std::error::Error for DbError {}
41
42pub type DbResult<T> = Result<T, DbError>;
43
44#[derive(Debug, PartialEq)]
45pub enum DbType {
46    Postgres,
47    Sqlite,
48    Unknown,
49}
50
51#[derive(Clone, Deserialize, Serialize)]
52pub struct DbSettings {
53    pub db_uri: String,
54    /// Optional URI for read replicas. If set, read-only queries will use this connection.
55    pub read_db_uri: Option<String>,
56}
57
58impl DbSettings {
59    pub fn db_type(&self) -> DbType {
60        if self.db_uri.starts_with("postgres://") || self.db_uri.starts_with("postgresql://") {
61            DbType::Postgres
62        } else if self.db_uri.starts_with("sqlite://") {
63            DbType::Sqlite
64        } else {
65            DbType::Unknown
66        }
67    }
68}
69
70fn redact_db_uri(uri: &str) -> String {
71    url::Url::parse(uri)
72        .map(|mut url| {
73            let _ = url.set_password(Some("****"));
74            url.to_string()
75        })
76        .unwrap_or_else(|_| uri.to_string())
77}
78
79// Do our best to redact passwords so they're not logged in the event of an error.
80impl Debug for DbSettings {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        if self.db_type() == DbType::Postgres {
83            let redacted_uri = redact_db_uri(&self.db_uri);
84            let redacted_read_uri = self.read_db_uri.as_ref().map(|uri| redact_db_uri(uri));
85            f.debug_struct("DbSettings")
86                .field("db_uri", &redacted_uri)
87                .field("read_db_uri", &redacted_read_uri)
88                .finish()
89        } else {
90            f.debug_struct("DbSettings")
91                .field("db_uri", &self.db_uri)
92                .field("read_db_uri", &self.read_db_uri)
93                .finish()
94        }
95    }
96}
97
98#[async_trait]
99pub trait Database: Sized + Clone + Send + Sync + 'static {
100    async fn new(settings: &DbSettings) -> DbResult<Self>;
101
102    async fn get_session(&self, token: &str) -> DbResult<Session>;
103    async fn get_session_user(&self, token: &str) -> DbResult<User>;
104    async fn add_session(&self, session: &NewSession) -> DbResult<()>;
105
106    async fn get_user(&self, username: &str) -> DbResult<User>;
107    async fn get_user_session(&self, u: &User) -> DbResult<Session>;
108    async fn add_user(&self, user: &NewUser) -> DbResult<i64>;
109
110    async fn user_verified(&self, id: i64) -> DbResult<bool>;
111    async fn verify_user(&self, id: i64) -> DbResult<()>;
112    async fn user_verification_token(&self, id: i64) -> DbResult<String>;
113
114    async fn update_user_password(&self, u: &User) -> DbResult<()>;
115
116    async fn total_history(&self) -> DbResult<i64>;
117    async fn count_history(&self, user: &User) -> DbResult<i64>;
118    async fn count_history_cached(&self, user: &User) -> DbResult<i64>;
119
120    async fn delete_user(&self, u: &User) -> DbResult<()>;
121    async fn delete_history(&self, user: &User, id: String) -> DbResult<()>;
122    async fn deleted_history(&self, user: &User) -> DbResult<Vec<String>>;
123    async fn delete_store(&self, user: &User) -> DbResult<()>;
124
125    async fn add_records(&self, user: &User, record: &[Record<EncryptedData>]) -> DbResult<()>;
126    async fn next_records(
127        &self,
128        user: &User,
129        host: HostId,
130        tag: String,
131        start: Option<RecordIdx>,
132        count: u64,
133    ) -> DbResult<Vec<Record<EncryptedData>>>;
134
135    // Return the tail record ID for each store, so (HostID, Tag, TailRecordID)
136    async fn status(&self, user: &User) -> DbResult<RecordStatus>;
137
138    async fn count_history_range(&self, user: &User, range: Range<OffsetDateTime>)
139    -> DbResult<i64>;
140
141    async fn list_history(
142        &self,
143        user: &User,
144        created_after: OffsetDateTime,
145        since: OffsetDateTime,
146        host: &str,
147        page_size: i64,
148    ) -> DbResult<Vec<History>>;
149
150    async fn add_history(&self, history: &[NewHistory]) -> DbResult<()>;
151
152    async fn oldest_history(&self, user: &User) -> DbResult<History>;
153
154    #[instrument(skip_all)]
155    async fn calendar(
156        &self,
157        user: &User,
158        period: TimePeriod,
159        tz: UtcOffset,
160    ) -> DbResult<HashMap<u64, TimePeriodInfo>> {
161        let mut ret = HashMap::new();
162        let iter: Box<dyn Iterator<Item = DbResult<(u64, Range<Date>)>> + Send> = match period {
163            TimePeriod::Year => {
164                // First we need to work out how far back to calculate. Get the
165                // oldest history item
166                let oldest = self
167                    .oldest_history(user)
168                    .await?
169                    .timestamp
170                    .to_offset(tz)
171                    .year();
172                let current_year = OffsetDateTime::now_utc().to_offset(tz).year();
173
174                // All the years we need to get data for
175                // The upper bound is exclusive, so include current +1
176                let years = oldest..current_year + 1;
177
178                Box::new(years.map(|year| {
179                    let start = Date::from_calendar_date(year, time::Month::January, 1)?;
180                    let end = Date::from_calendar_date(year + 1, time::Month::January, 1)?;
181
182                    Ok((year as u64, start..end))
183                }))
184            }
185
186            TimePeriod::Month { year } => {
187                let months =
188                    std::iter::successors(Some(Month::January), |m| Some(m.next())).take(12);
189
190                Box::new(months.map(move |month| {
191                    let start = Date::from_calendar_date(year, month, 1)?;
192                    let days = start.month().length(year);
193                    let end = start + Duration::days(days as i64);
194
195                    Ok((month as u64, start..end))
196                }))
197            }
198
199            TimePeriod::Day { year, month } => {
200                let days = 1..month.length(year);
201                Box::new(days.map(move |day| {
202                    let start = Date::from_calendar_date(year, month, day)?;
203                    let end = start
204                        .next_day()
205                        .ok_or_else(|| DbError::Other(eyre::eyre!("no next day?")))?;
206
207                    Ok((day as u64, start..end))
208                }))
209            }
210        };
211
212        for x in iter {
213            let (index, range) = x?;
214
215            let start = range.start.with_time(Time::MIDNIGHT).assume_offset(tz);
216            let end = range.end.with_time(Time::MIDNIGHT).assume_offset(tz);
217
218            let count = self.count_history_range(user, start..end).await?;
219
220            ret.insert(
221                index,
222                TimePeriodInfo {
223                    count: count as u64,
224                    hash: "".to_string(),
225                },
226            );
227        }
228
229        Ok(ret)
230    }
231}