Skip to content

Commit 67b5fd8

Browse files
committed
cleanup
1 parent f458cea commit 67b5fd8

File tree

20 files changed

+421
-500
lines changed

20 files changed

+421
-500
lines changed

Cargo.lock

Lines changed: 279 additions & 263 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/app/core/Cargo.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ tracing-test = "0.2"
1515

1616
[dependencies]
1717
anyhow = { version = "1", features = ["backtrace"] }
18-
async-trait = "0.1"
1918
bytes = "1"
2019
chrono = { version = "0.4", features = ["serde"] }
2120
chrono-tz = { version = "0.6", features = ["serde"] }
@@ -31,7 +30,7 @@ memmap = "0.7"
3130
ndarray = { version = "0.15", features = ["rayon"] }
3231
num = "0.4"
3332
rand = "0.8"
34-
rust-s3 = { version = "0.28", default-features = false, features = ["tokio-rustls-tls"] }
33+
rust-s3 = { version = "0.30", default-features = false, features = ["tokio-rustls-tls"] }
3534
serde = { version = "1", features = ["derive"] }
3635
serde_json = "1"
3736
sqlx = { version = "0.5", default-features = false, features = ["any", "chrono", "postgres", "runtime-tokio-rustls", "sqlite"] }

crates/app/core/alert.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ use crate::{
44
App, AppState,
55
};
66
use anyhow::Result;
7+
use modelfox_id::Id;
78
use serde::{Deserialize, Serialize};
89
use sqlx::prelude::*;
910
use std::{borrow::BorrowMut, fmt, io, str::FromStr};
10-
use modelfox_id::Id;
1111
use time::{macros::format_description, OffsetDateTime};
1212
use url::Url;
1313

@@ -252,17 +252,17 @@ impl App {
252252
) -> Result<Vec<Alert>> {
253253
let rows = sqlx::query(
254254
"
255-
select
256-
alerts.data
257-
from
258-
monitors
259-
join
260-
alerts
261-
on
262-
monitors.id = alerts.monitor_id
263-
where
264-
monitors.model_id = $1
265-
",
255+
select
256+
alerts.data
257+
from
258+
monitors
259+
join
260+
alerts
261+
on
262+
monitors.id = alerts.monitor_id
263+
where
264+
monitors.model_id = $1
265+
",
266266
)
267267
.bind(model_id.to_string())
268268
.fetch_all(txn.borrow_mut())

crates/app/core/lib.rs

Lines changed: 5 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,7 @@ use lettre::AsyncTransport;
1010
use lettre::Transport;
1111
use serde::Serialize;
1212
use sqlx::postgres::PgPoolOptions;
13-
use std::{
14-
path::PathBuf,
15-
sync::{Arc, RwLock},
16-
};
13+
use std::sync::{Arc, RwLock};
1714
use storage::InMemoryStorage;
1815
use tokio::sync::{mpsc, oneshot};
1916
use url::Url;
@@ -177,44 +174,6 @@ pub async fn migrate_inner(database_url: Url) -> Result<()> {
177174
Ok(())
178175
}
179176

180-
/// Retrieve the user cache directory using the `dirs` crate.
181-
pub fn cache_path() -> Result<PathBuf> {
182-
let cache_dir =
183-
dirs::cache_dir().ok_or_else(|| anyhow!("failed to find user cache directory"))?;
184-
let modelfox_cache_dir = cache_dir.join("modelfox");
185-
std::fs::create_dir_all(&modelfox_cache_dir).map_err(|_| {
186-
anyhow!(
187-
"failed to create modelfox cache directory in {}",
188-
modelfox_cache_dir.display()
189-
)
190-
})?;
191-
Ok(modelfox_cache_dir)
192-
}
193-
194-
/// Retrieve the user data directory using the `dirs` crate.
195-
pub fn data_path() -> Result<PathBuf> {
196-
let data_dir = dirs::data_dir().ok_or_else(|| anyhow!("failed to find user data directory"))?;
197-
let modelfox_data_dir = data_dir.join("modelfox");
198-
std::fs::create_dir_all(&modelfox_data_dir).map_err(|_| {
199-
anyhow!(
200-
"failed to create modelfox data directory in {}",
201-
modelfox_data_dir.display()
202-
)
203-
})?;
204-
Ok(modelfox_data_dir)
205-
}
206-
207-
/// Retrieve the default database url, which is a sqlite database in the user data directory.
208-
pub fn default_database_url() -> Url {
209-
let modelfox_database_path = data_path().unwrap().join("db").join("modelfox.db");
210-
std::fs::create_dir_all(modelfox_database_path.parent().unwrap()).unwrap();
211-
let url = format!(
212-
"sqlite:{}",
213-
modelfox_database_path.to_str().unwrap().to_owned()
214-
);
215-
Url::parse(&url).unwrap()
216-
}
217-
218177
impl App {
219178
pub async fn new(options: Options) -> Result<Self> {
220179
// Create the database pool.
@@ -314,6 +273,10 @@ impl App {
314273
self.state.smtp_transport.clone()
315274
}
316275

276+
pub fn options(&self) -> &Options {
277+
&self.state.options
278+
}
279+
317280
/// Send a message to the monitor checker and wait for it to reply back indicating it has run.
318281
#[tracing::instrument(level = "info", skip_all)]
319282
pub async fn sync_tasks(&self) -> Result<()> {
@@ -392,13 +355,6 @@ pub async fn reset_database(database_url: &Option<Url>) -> Result<()> {
392355
Ok(())
393356
}
394357

395-
/// Remove all contents of the data dir, including the database
396-
pub async fn reset_data(database_url: &Option<Url>) -> Result<()> {
397-
reset_database(database_url).await?;
398-
std::fs::remove_dir_all(data_path()?)?;
399-
Ok(())
400-
}
401-
402358
pub fn path_components(request: &http::Request<hyper::Body>) -> Vec<&str> {
403359
request.uri().path().split('/').skip(1).collect::<Vec<_>>()
404360
}

crates/app/core/options.rs

Lines changed: 0 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use crate::{data_path, default_database_url, App};
21
use std::net::IpAddr;
32
use std::path::PathBuf;
43
use url::Url;
@@ -58,45 +57,3 @@ impl Options {
5857
self.auth.is_some()
5958
}
6059
}
61-
62-
impl Default for Options {
63-
fn default() -> Self {
64-
let host: IpAddr = if let Ok(host) = std::env::var("HOST") {
65-
host.parse()
66-
.expect("Could not parse HOST environment variable")
67-
} else {
68-
"0.0.0.0".parse().unwrap()
69-
};
70-
let port = if let Ok(port) = std::env::var("PORT") {
71-
port.parse()
72-
.expect("Could not parse PORT environment variable")
73-
} else {
74-
8080u16
75-
};
76-
let database = DatabaseOptions {
77-
max_connections: None,
78-
url: default_database_url(),
79-
};
80-
let storage = StorageOptions::Local(LocalStorageOptions {
81-
path: data_path()
82-
.expect("Could not read or create modelfox data directory")
83-
.join("data"),
84-
});
85-
Options {
86-
auth: None,
87-
cookie_domain: None,
88-
database,
89-
host,
90-
port,
91-
smtp: None,
92-
storage,
93-
url: None,
94-
}
95-
}
96-
}
97-
98-
impl App {
99-
pub fn options(&self) -> &Options {
100-
&self.state.options
101-
}
102-
}

crates/app/core/storage.rs

Lines changed: 18 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
use crate::App;
22
use anyhow::{anyhow, Result};
3-
use async_trait::async_trait;
43
use bytes::Bytes;
54
use modelfox_id::Id;
65
use std::{
76
collections::HashMap,
87
path::PathBuf,
98
sync::{Arc, RwLock},
109
};
11-
use tokio::fs;
1210

1311
#[derive(Debug)]
1412
#[allow(clippy::large_enum_variant)]
@@ -75,17 +73,6 @@ impl TryFrom<BytesOrFilePath> for PathBuf {
7573
}
7674
}
7775

78-
/// This trait represents types which can serve as storage buckets for the ModelFox app.
79-
#[async_trait]
80-
trait StorageTrait {
81-
/// Retrieve an entity from storage.
82-
async fn get(&self, entity: StorageEntity, id: Id) -> Result<BytesOrFilePath>;
83-
/// Add the provided bytes to the storage.
84-
async fn set(&self, entity: StorageEntity, id: Id, data: &[u8]) -> Result<()>;
85-
/// Delete an item from storage.
86-
async fn remove(&self, entity: StorageEntity, id: Id) -> Result<()>;
87-
}
88-
8976
impl Storage {
9077
pub async fn get(&self, entity: StorageEntity, id: Id) -> Result<BytesOrFilePath> {
9178
match self {
@@ -126,8 +113,7 @@ impl Default for InMemoryStorage {
126113
}
127114
}
128115

129-
#[async_trait]
130-
impl StorageTrait for InMemoryStorage {
116+
impl InMemoryStorage {
131117
async fn get(&self, _entity: StorageEntity, id: Id) -> Result<BytesOrFilePath> {
132118
let storage = Arc::clone(&self.storage);
133119
let ret = if let Ok(read_guard) = storage.read() {
@@ -159,8 +145,7 @@ impl StorageTrait for InMemoryStorage {
159145
}
160146
}
161147

162-
#[async_trait]
163-
impl StorageTrait for LocalStorage {
148+
impl LocalStorage {
164149
async fn get(&self, entity: StorageEntity, id: Id) -> Result<BytesOrFilePath> {
165150
let entity_path = self.path.join(entity.dir_name());
166151
let path = entity_path.join(id.to_string());
@@ -169,16 +154,16 @@ impl StorageTrait for LocalStorage {
169154

170155
async fn set(&self, entity: StorageEntity, id: Id, data: &[u8]) -> Result<()> {
171156
let entity_path = self.path.join(entity.dir_name());
172-
fs::create_dir_all(&entity_path).await?;
157+
tokio::fs::create_dir_all(&entity_path).await?;
173158
let item_path = entity_path.join(id.to_string());
174-
fs::write(item_path, data).await?;
159+
tokio::fs::write(item_path, data).await?;
175160
Ok(())
176161
}
177162

178163
async fn remove(&self, entity: StorageEntity, id: Id) -> Result<()> {
179164
let entity_path = self.path.join(entity.dir_name());
180165
let item_path = entity_path.join(id.to_string());
181-
fs::remove_file(item_path).await?;
166+
tokio::fs::remove_file(item_path).await?;
182167
Ok(())
183168
}
184169
}
@@ -193,65 +178,54 @@ impl S3Storage {
193178
cache_path: PathBuf,
194179
) -> Result<S3Storage> {
195180
let credentials =
196-
s3::creds::Credentials::new(Some(&access_key), Some(&secret_key), None, None, None)
197-
.map_err(|e| anyhow!(e.to_string()))?;
181+
s3::creds::Credentials::new(Some(&access_key), Some(&secret_key), None, None, None)?;
198182
let bucket = s3::Bucket::new(
199183
&bucket,
200184
s3::Region::Custom { region, endpoint },
201185
credentials,
202-
)
203-
.map_err(|e| anyhow!(e.to_string()))?;
186+
)?;
204187
Ok(S3Storage { bucket, cache_path })
205188
}
206189
}
207190

208-
#[async_trait]
209-
impl StorageTrait for S3Storage {
191+
impl S3Storage {
210192
async fn get(&self, entity: StorageEntity, id: Id) -> Result<BytesOrFilePath> {
211193
// Attempt to retrieve the item from the cache.
212194
let entity_cache_path = self.cache_path.join(entity.dir_name());
213195
let item_cache_path = entity_cache_path.join(id.to_string());
214-
if fs::metadata(&item_cache_path).await.is_ok() {
196+
if tokio::fs::metadata(&item_cache_path).await.is_ok() {
215197
return Ok(BytesOrFilePath::from(item_cache_path));
216198
}
217199
// Retrieve the item from s3 and cache it.
218-
let (data, _) = self
219-
.bucket
220-
.get_object(&key_for_item(entity, id))
221-
.await
222-
.map_err(|e| anyhow!(e.to_string()))?;
200+
let (data, _) = self.bucket.get_object(&key_for_item(entity, id)).await?;
223201
// Add the item to the cache.
224-
fs::create_dir_all(&entity_cache_path).await?;
225-
fs::write(&item_cache_path, data).await?;
202+
tokio::fs::create_dir_all(&entity_cache_path).await?;
203+
tokio::fs::write(&item_cache_path, data).await?;
226204
Ok(BytesOrFilePath::from(item_cache_path))
227205
}
228206

229207
async fn set(&self, entity: StorageEntity, id: Id, data: &[u8]) -> Result<()> {
230208
let entity_cache_path = self.cache_path.join(entity.dir_name());
231-
fs::create_dir_all(&entity_cache_path).await?;
209+
tokio::fs::create_dir_all(&entity_cache_path).await?;
232210
let item_cache_path = entity_cache_path.join(id.to_string());
233211
// Upload the item to s3.
234212
self.bucket
235213
.put_object(&key_for_item(entity, id), data)
236-
.await
237-
.map_err(|e| anyhow!(e.to_string()))?;
214+
.await?;
238215
// Add the item to the cache.
239-
fs::write(item_cache_path, data).await?;
216+
tokio::fs::write(item_cache_path, data).await?;
240217
Ok(())
241218
}
242219

243220
async fn remove(&self, entity: StorageEntity, id: Id) -> Result<()> {
244221
// Remove the item from the cache if it exists.
245222
let entity_cache_path = self.cache_path.join(entity.dir_name());
246223
let item_cache_path = entity_cache_path.join(id.to_string());
247-
if fs::metadata(&item_cache_path).await.is_ok() {
248-
fs::remove_file(item_cache_path).await?;
224+
if tokio::fs::metadata(&item_cache_path).await.is_ok() {
225+
tokio::fs::remove_file(item_cache_path).await?;
249226
}
250227
// Remove the item from s3.
251-
self.bucket
252-
.delete_object(&key_for_item(entity, id))
253-
.await
254-
.map_err(|e| anyhow!(e.to_string()))?;
228+
self.bucket.delete_object(&key_for_item(entity, id)).await?;
255229
Ok(())
256230
}
257231
}

0 commit comments

Comments
 (0)