Skip to main content

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 update_user_password(&self, u: &User) -> DbResult<()>;
111
112    async fn count_history(&self, user: &User) -> DbResult<i64>;
113    async fn count_history_cached(&self, user: &User) -> DbResult<i64>;
114
115    async fn delete_user(&self, u: &User) -> DbResult<()>;
116    async fn delete_history(&self, user: &User, id: String) -> DbResult<()>;
117    async fn deleted_history(&self, user: &User) -> DbResult<Vec<String>>;
118    async fn delete_store(&self, user: &User) -> DbResult<()>;
119
120    async fn add_records(&self, user: &User, record: &[Record<EncryptedData>]) -> DbResult<()>;
121    async fn next_records(
122        &self,
123        user: &User,
124        host: HostId,
125        tag: String,
126        start: Option<RecordIdx>,
127        count: u64,
128    ) -> DbResult<Vec<Record<EncryptedData>>>;
129
130    // Return the tail record ID for each store, so (HostID, Tag, TailRecordID)
131    async fn status(&self, user: &User) -> DbResult<RecordStatus>;
132
133    async fn count_history_range(&self, user: &User, range: Range<OffsetDateTime>)
134    -> DbResult<i64>;
135
136    async fn list_history(
137        &self,
138        user: &User,
139        created_after: OffsetDateTime,
140        since: OffsetDateTime,
141        host: &str,
142        page_size: i64,
143    ) -> DbResult<Vec<History>>;
144
145    async fn add_history(&self, history: &[NewHistory]) -> DbResult<()>;
146
147    async fn oldest_history(&self, user: &User) -> DbResult<History>;
148
149    #[instrument(skip_all)]
150    async fn calendar(
151        &self,
152        user: &User,
153        period: TimePeriod,
154        tz: UtcOffset,
155    ) -> DbResult<HashMap<u64, TimePeriodInfo>> {
156        let mut ret = HashMap::new();
157        let iter: Box<dyn Iterator<Item = DbResult<(u64, Range<Date>)>> + Send> = match period {
158            TimePeriod::Year => {
159                // First we need to work out how far back to calculate. Get the
160                // oldest history item
161                let oldest = self
162                    .oldest_history(user)
163                    .await?
164                    .timestamp
165                    .to_offset(tz)
166                    .year();
167                let current_year = OffsetDateTime::now_utc().to_offset(tz).year();
168
169                // All the years we need to get data for
170                // The upper bound is exclusive, so include current +1
171                let years = oldest..current_year + 1;
172
173                Box::new(years.map(|year| {
174                    let start = Date::from_calendar_date(year, time::Month::January, 1)?;
175                    let end = Date::from_calendar_date(year + 1, time::Month::January, 1)?;
176
177                    Ok((year as u64, start..end))
178                }))
179            }
180
181            TimePeriod::Month { year } => {
182                let months =
183                    std::iter::successors(Some(Month::January), |m| Some(m.next())).take(12);
184
185                Box::new(months.map(move |month| {
186                    let start = Date::from_calendar_date(year, month, 1)?;
187                    let days = start.month().length(year);
188                    let end = start + Duration::days(days as i64);
189
190                    Ok((month as u64, start..end))
191                }))
192            }
193
194            TimePeriod::Day { year, month } => {
195                let days = 1..month.length(year);
196                Box::new(days.map(move |day| {
197                    let start = Date::from_calendar_date(year, month, day)?;
198                    let end = start
199                        .next_day()
200                        .ok_or_else(|| DbError::Other(eyre::eyre!("no next day?")))?;
201
202                    Ok((day as u64, start..end))
203                }))
204            }
205        };
206
207        for x in iter {
208            let (index, range) = x?;
209
210            let start = range.start.with_time(Time::MIDNIGHT).assume_offset(tz);
211            let end = range.end.with_time(Time::MIDNIGHT).assume_offset(tz);
212
213            let count = self.count_history_range(user, start..end).await?;
214
215            ret.insert(
216                index,
217                TimePeriodInfo {
218                    count: count as u64,
219                    hash: "".to_string(),
220                },
221            );
222        }
223
224        Ok(ret)
225    }
226}