]> Untitled Git - lemmy.git/blob - crates/db_schema/src/utils.rs
Error enum fixed (#3487)
[lemmy.git] / crates / db_schema / src / utils.rs
1 use crate::{
2   diesel::Connection,
3   diesel_migrations::MigrationHarness,
4   newtypes::DbUrl,
5   CommentSortType,
6   SortType,
7 };
8 use activitypub_federation::{fetch::object_id::ObjectId, traits::Object};
9 use chrono::NaiveDateTime;
10 use deadpool::Runtime;
11 use diesel::{
12   backend::Backend,
13   deserialize::FromSql,
14   pg::Pg,
15   result::{ConnectionError, ConnectionResult, Error as DieselError, Error::QueryBuilderError},
16   serialize::{Output, ToSql},
17   sql_types::Text,
18   PgConnection,
19 };
20 use diesel_async::{
21   pg::AsyncPgConnection,
22   pooled_connection::{
23     deadpool::{Object as PooledConnection, Pool},
24     AsyncDieselConnectionManager,
25   },
26 };
27 use diesel_migrations::EmbeddedMigrations;
28 use futures_util::{future::BoxFuture, FutureExt};
29 use lemmy_utils::{
30   error::{LemmyError, LemmyErrorExt, LemmyErrorType},
31   settings::structs::Settings,
32 };
33 use once_cell::sync::Lazy;
34 use regex::Regex;
35 use rustls::{
36   client::{ServerCertVerified, ServerCertVerifier},
37   ServerName,
38 };
39 use std::{
40   env,
41   env::VarError,
42   sync::Arc,
43   time::{Duration, SystemTime},
44 };
45 use tracing::{error, info};
46 use url::Url;
47
48 const FETCH_LIMIT_DEFAULT: i64 = 10;
49 pub const FETCH_LIMIT_MAX: i64 = 50;
50 const POOL_TIMEOUT: Option<Duration> = Some(Duration::from_secs(5));
51
52 pub type DbPool = Pool<AsyncPgConnection>;
53
54 pub async fn get_conn(pool: &DbPool) -> Result<PooledConnection<AsyncPgConnection>, DieselError> {
55   pool.get().await.map_err(|e| QueryBuilderError(e.into()))
56 }
57
58 pub fn get_database_url_from_env() -> Result<String, VarError> {
59   env::var("LEMMY_DATABASE_URL")
60 }
61
62 pub fn fuzzy_search(q: &str) -> String {
63   let replaced = q.replace('%', "\\%").replace('_', "\\_").replace(' ', "%");
64   format!("%{replaced}%")
65 }
66
67 pub fn limit_and_offset(
68   page: Option<i64>,
69   limit: Option<i64>,
70 ) -> Result<(i64, i64), diesel::result::Error> {
71   let page = match page {
72     Some(page) => {
73       if page < 1 {
74         return Err(QueryBuilderError("Page is < 1".into()));
75       } else {
76         page
77       }
78     }
79     None => 1,
80   };
81   let limit = match limit {
82     Some(limit) => {
83       if !(1..=FETCH_LIMIT_MAX).contains(&limit) {
84         return Err(QueryBuilderError(
85           format!("Fetch limit is > {FETCH_LIMIT_MAX}").into(),
86         ));
87       } else {
88         limit
89       }
90     }
91     None => FETCH_LIMIT_DEFAULT,
92   };
93   let offset = limit * (page - 1);
94   Ok((limit, offset))
95 }
96
97 pub fn limit_and_offset_unlimited(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
98   let limit = limit.unwrap_or(FETCH_LIMIT_DEFAULT);
99   let offset = limit * (page.unwrap_or(1) - 1);
100   (limit, offset)
101 }
102
103 pub fn is_email_regex(test: &str) -> bool {
104   EMAIL_REGEX.is_match(test)
105 }
106
107 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
108   match opt {
109     // An empty string is an erase
110     Some(unwrapped) => {
111       if !unwrapped.eq("") {
112         Some(Some(unwrapped.clone()))
113       } else {
114         Some(None)
115       }
116     }
117     None => None,
118   }
119 }
120
121 pub fn diesel_option_overwrite_to_url(
122   opt: &Option<String>,
123 ) -> Result<Option<Option<DbUrl>>, LemmyError> {
124   match opt.as_ref().map(String::as_str) {
125     // An empty string is an erase
126     Some("") => Ok(Some(None)),
127     Some(str_url) => Url::parse(str_url)
128       .map(|u| Some(Some(u.into())))
129       .with_lemmy_type(LemmyErrorType::InvalidUrl),
130     None => Ok(None),
131   }
132 }
133
134 pub fn diesel_option_overwrite_to_url_create(
135   opt: &Option<String>,
136 ) -> Result<Option<DbUrl>, LemmyError> {
137   match opt.as_ref().map(String::as_str) {
138     // An empty string is nothing
139     Some("") => Ok(None),
140     Some(str_url) => Url::parse(str_url)
141       .map(|u| Some(u.into()))
142       .with_lemmy_type(LemmyErrorType::InvalidUrl),
143     None => Ok(None),
144   }
145 }
146
147 async fn build_db_pool_settings_opt(settings: Option<&Settings>) -> Result<DbPool, LemmyError> {
148   let db_url = get_database_url(settings);
149   let pool_size = settings.map(|s| s.database.pool_size).unwrap_or(5);
150   // We only support TLS with sslmode=require currently
151   let tls_enabled = db_url.contains("sslmode=require");
152   let manager = if tls_enabled {
153     // diesel-async does not support any TLS connections out of the box, so we need to manually
154     // provide a setup function which handles creating the connection
155     AsyncDieselConnectionManager::<AsyncPgConnection>::new_with_setup(&db_url, establish_connection)
156   } else {
157     AsyncDieselConnectionManager::<AsyncPgConnection>::new(&db_url)
158   };
159   let pool = Pool::builder(manager)
160     .max_size(pool_size)
161     .wait_timeout(POOL_TIMEOUT)
162     .create_timeout(POOL_TIMEOUT)
163     .recycle_timeout(POOL_TIMEOUT)
164     .runtime(Runtime::Tokio1)
165     .build()?;
166
167   // If there's no settings, that means its a unit test, and migrations need to be run
168   if settings.is_none() {
169     run_migrations(&db_url);
170   }
171
172   Ok(pool)
173 }
174
175 fn establish_connection(config: &str) -> BoxFuture<ConnectionResult<AsyncPgConnection>> {
176   let fut = async {
177     let rustls_config = rustls::ClientConfig::builder()
178       .with_safe_defaults()
179       .with_custom_certificate_verifier(Arc::new(NoCertVerifier {}))
180       .with_no_client_auth();
181
182     let tls = tokio_postgres_rustls::MakeRustlsConnect::new(rustls_config);
183     let (client, conn) = tokio_postgres::connect(config, tls)
184       .await
185       .map_err(|e| ConnectionError::BadConnection(e.to_string()))?;
186     tokio::spawn(async move {
187       if let Err(e) = conn.await {
188         error!("Database connection failed: {e}");
189       }
190     });
191     AsyncPgConnection::try_from(client).await
192   };
193   fut.boxed()
194 }
195
196 struct NoCertVerifier {}
197
198 impl ServerCertVerifier for NoCertVerifier {
199   fn verify_server_cert(
200     &self,
201     _end_entity: &rustls::Certificate,
202     _intermediates: &[rustls::Certificate],
203     _server_name: &ServerName,
204     _scts: &mut dyn Iterator<Item = &[u8]>,
205     _ocsp_response: &[u8],
206     _now: SystemTime,
207   ) -> Result<ServerCertVerified, rustls::Error> {
208     // Will verify all (even invalid) certs without any checks (sslmode=require)
209     Ok(ServerCertVerified::assertion())
210   }
211 }
212
213 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
214
215 pub fn run_migrations(db_url: &str) {
216   // Needs to be a sync connection
217   let mut conn =
218     PgConnection::establish(db_url).unwrap_or_else(|e| panic!("Error connecting to {db_url}: {e}"));
219   info!("Running Database migrations (This may take a long time)...");
220   let _ = &mut conn
221     .run_pending_migrations(MIGRATIONS)
222     .unwrap_or_else(|e| panic!("Couldn't run DB Migrations: {e}"));
223   info!("Database migrations complete.");
224 }
225
226 pub async fn build_db_pool(settings: &Settings) -> Result<DbPool, LemmyError> {
227   build_db_pool_settings_opt(Some(settings)).await
228 }
229
230 pub async fn build_db_pool_for_tests() -> DbPool {
231   build_db_pool_settings_opt(None)
232     .await
233     .expect("db pool missing")
234 }
235
236 pub fn get_database_url(settings: Option<&Settings>) -> String {
237   // The env var should override anything in the settings config
238   match get_database_url_from_env() {
239     Ok(url) => url,
240     Err(e) => match settings {
241       Some(settings) => settings.get_database_url(),
242       None => panic!("Failed to read database URL from env var LEMMY_DATABASE_URL: {e}"),
243     },
244   }
245 }
246
247 pub fn naive_now() -> NaiveDateTime {
248   chrono::prelude::Utc::now().naive_utc()
249 }
250
251 pub fn post_to_comment_sort_type(sort: SortType) -> CommentSortType {
252   match sort {
253     SortType::Active | SortType::Hot => CommentSortType::Hot,
254     SortType::New | SortType::NewComments | SortType::MostComments => CommentSortType::New,
255     SortType::Old => CommentSortType::Old,
256     SortType::TopHour
257     | SortType::TopSixHour
258     | SortType::TopTwelveHour
259     | SortType::TopDay
260     | SortType::TopAll
261     | SortType::TopWeek
262     | SortType::TopYear
263     | SortType::TopMonth
264     | SortType::TopThreeMonths
265     | SortType::TopSixMonths
266     | SortType::TopNineMonths => CommentSortType::Top,
267   }
268 }
269
270 static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
271   Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
272     .expect("compile email regex")
273 });
274
275 pub mod functions {
276   use diesel::sql_types::{BigInt, Text, Timestamp};
277
278   sql_function! {
279     fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
280   }
281
282   sql_function!(fn lower(x: Text) -> Text);
283 }
284
285 pub const DELETED_REPLACEMENT_TEXT: &str = "*Permanently Deleted*";
286
287 impl ToSql<Text, Pg> for DbUrl {
288   fn to_sql(&self, out: &mut Output<Pg>) -> diesel::serialize::Result {
289     <std::string::String as ToSql<Text, Pg>>::to_sql(&self.0.to_string(), &mut out.reborrow())
290   }
291 }
292
293 impl<DB: Backend> FromSql<Text, DB> for DbUrl
294 where
295   String: FromSql<Text, DB>,
296 {
297   fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
298     let str = String::from_sql(value)?;
299     Ok(DbUrl(Box::new(Url::parse(&str)?)))
300   }
301 }
302
303 impl<Kind> From<ObjectId<Kind>> for DbUrl
304 where
305   Kind: Object + Send + 'static,
306   for<'de2> <Kind as Object>::Kind: serde::Deserialize<'de2>,
307 {
308   fn from(id: ObjectId<Kind>) -> Self {
309     DbUrl(Box::new(id.into()))
310   }
311 }
312
313 #[cfg(test)]
314 mod tests {
315   use super::{fuzzy_search, *};
316   use crate::utils::is_email_regex;
317
318   #[test]
319   fn test_fuzzy_search() {
320     let test = "This %is% _a_ fuzzy search";
321     assert_eq!(
322       fuzzy_search(test),
323       "%This%\\%is\\%%\\_a\\_%fuzzy%search%".to_string()
324     );
325   }
326
327   #[test]
328   fn test_email() {
329     assert!(is_email_regex("gush@gmail.com"));
330     assert!(!is_email_regex("nada_neutho"));
331   }
332
333   #[test]
334   fn test_diesel_option_overwrite() {
335     assert_eq!(diesel_option_overwrite(&None), None);
336     assert_eq!(diesel_option_overwrite(&Some(String::new())), Some(None));
337     assert_eq!(
338       diesel_option_overwrite(&Some("test".to_string())),
339       Some(Some("test".to_string()))
340     );
341   }
342
343   #[test]
344   fn test_diesel_option_overwrite_to_url() {
345     assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
346     assert!(matches!(
347       diesel_option_overwrite_to_url(&Some(String::new())),
348       Ok(Some(None))
349     ));
350     assert!(diesel_option_overwrite_to_url(&Some("invalid_url".to_string())).is_err());
351     let example_url = "https://example.com";
352     assert!(matches!(
353       diesel_option_overwrite_to_url(&Some(example_url.to_string())),
354       Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()
355     ));
356   }
357 }