Skip to main content

atuin_server_database/
lib.rs

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