Skip to content

Commit

Permalink
refactoring storage
Browse files Browse the repository at this point in the history
Signed-off-by: simonsan <[email protected]>
  • Loading branch information
simonsan committed Mar 27, 2024
1 parent f9ee382 commit 3a7d995
Show file tree
Hide file tree
Showing 21 changed files with 594 additions and 472 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ clap = { workspace = true, optional = true, features = ["env", "wrap_help", "der
directories = { workspace = true }
displaydoc = { workspace = true }
dotenvy = { workspace = true }
eyre = { workspace = true }
getset = { workspace = true }
itertools = { workspace = true }
merge = { workspace = true }
Expand Down
14 changes: 9 additions & 5 deletions crates/core/src/commands/adjust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{
commands::UpdateOptions,
config::PaceConfig,
error::{ActivityLogErrorKind, PaceResult, UserMessage},
prelude::ActivityStorage,
prelude::{ActivityStorage, PaceErrorKind},
service::activity_store::ActivityStore,
storage::{ActivityQuerying, ActivityWriteOps, SyncStorage},
};
Expand Down Expand Up @@ -165,10 +165,12 @@ impl AdjustCommandOptions {

debug!("Parsed time: {date_time:?}");

let activity_store = ActivityStore::with_storage(storage)?;
let activity_store =
ActivityStore::with_storage(storage).map_err(PaceErrorKind::Storage)?;

let activity_item = activity_store
.most_recent_active_activity()?
.most_recent_active_activity()
.map_err(PaceErrorKind::Storage)?
.ok_or_else(|| ActivityLogErrorKind::NoActiveActivityToAdjust)?;

debug!("Most recent active activity item: {:?}", activity_item);
Expand Down Expand Up @@ -212,10 +214,12 @@ impl AdjustCommandOptions {
}
}

_ = activity_store.update_activity(guid, activity.clone(), UpdateOptions::default())?;
_ = activity_store
.update_activity(guid, activity.clone(), UpdateOptions::default())
.map_err(PaceErrorKind::Storage)?;

if activity_item.activity() != &activity {
activity_store.sync()?;
activity_store.sync().map_err(PaceErrorKind::Storage)?;
return Ok(UserMessage::new(format!(
"{} has been adjusted.",
activity_item.activity()
Expand Down
11 changes: 7 additions & 4 deletions crates/core/src/commands/begin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
config::PaceConfig,
domain::activity::{Activity, ActivityKind},
error::{PaceResult, UserMessage},
prelude::ActivityStorage,
prelude::{ActivityStorage, PaceErrorKind},
service::activity_store::ActivityStore,
storage::{ActivityStateManagement, SyncStorage},
};
Expand Down Expand Up @@ -144,13 +144,16 @@ impl BeginCommandOptions {
.tags(tags)
.build();

let activity_store = ActivityStore::with_storage(storage)?;
let activity_store =
ActivityStore::with_storage(storage).map_err(PaceErrorKind::Storage)?;

let activity_item = activity_store.begin_activity(activity)?;
let activity_item = activity_store
.begin_activity(activity)
.map_err(PaceErrorKind::Storage)?;

debug!("Started Activity: {:?}", activity_item);

activity_store.sync()?;
activity_store.sync().map_err(PaceErrorKind::Storage)?;

Ok(UserMessage::new(format!("{}", activity_item.activity())))
}
Expand Down
12 changes: 8 additions & 4 deletions crates/core/src/commands/end.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{
commands::EndOptions,
config::PaceConfig,
error::{PaceResult, UserMessage},
prelude::ActivityStorage,
prelude::{ActivityStorage, PaceErrorKind},
service::activity_store::ActivityStore,
storage::{ActivityStateManagement, SyncStorage},
};
Expand Down Expand Up @@ -98,11 +98,15 @@ impl EndCommandOptions {

debug!("Parsed date time: {:?}", date_time);

let activity_store = ActivityStore::with_storage(storage)?;
let activity_store =
ActivityStore::with_storage(storage).map_err(PaceErrorKind::Storage)?;

let end_opts = EndOptions::builder().end_time(date_time).build();

let user_message = (activity_store.end_all_activities(end_opts)?).map_or_else(
let user_message = (activity_store
.end_all_activities(end_opts)
.map_err(PaceErrorKind::Storage)?)
.map_or_else(
|| "No unfinished activities to end.".to_string(),
|unfinished_activities| {
let mut msgs = vec![];
Expand All @@ -116,7 +120,7 @@ impl EndCommandOptions {
},
);

activity_store.sync()?;
activity_store.sync().map_err(PaceErrorKind::Storage)?;

Ok(UserMessage::new(user_message))
}
Expand Down
23 changes: 13 additions & 10 deletions crates/core/src/commands/hold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::{
config::PaceConfig,
domain::intermission::IntermissionAction,
error::{PaceResult, UserMessage},
prelude::ActivityStorage,
prelude::{ActivityStorage, PaceErrorKind},
service::activity_store::ActivityStore,
storage::{ActivityStateManagement, SyncStorage},
};
Expand Down Expand Up @@ -119,18 +119,21 @@ impl HoldCommandOptions {

debug!("Hold options: {hold_opts:?}");

let activity_store = ActivityStore::with_storage(storage)?;
let activity_store =
ActivityStore::with_storage(storage).map_err(PaceErrorKind::Storage)?;

let user_message =
if let Some(activity) = activity_store.hold_most_recent_active_activity(hold_opts)? {
debug!("Held {}", activity.activity());
let user_message = if let Some(activity) = activity_store
.hold_most_recent_active_activity(hold_opts)
.map_err(PaceErrorKind::Storage)?
{
debug!("Held {}", activity.activity());

activity_store.sync()?;
activity_store.sync().map_err(PaceErrorKind::Storage)?;

format!("Held {}", activity.activity())
} else {
"No unfinished activities to hold.".to_string()
};
format!("Held {}", activity.activity())
} else {
"No unfinished activities to hold.".to_string()
};

Ok(UserMessage::new(user_message))
}
Expand Down
41 changes: 22 additions & 19 deletions crates/core/src/commands/now.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{
config::PaceConfig,
domain::{activity::ActivityItem, filter::ActivityFilterKind},
error::{PaceResult, UserMessage},
prelude::ActivityStorage,
prelude::{ActivityStorage, PaceErrorKind},
service::activity_store::ActivityStore,
storage::{ActivityQuerying, ActivityReadOps},
};
Expand Down Expand Up @@ -38,28 +38,31 @@ impl NowCommandOptions {
config: &PaceConfig,
storage: Arc<dyn ActivityStorage>,
) -> PaceResult<UserMessage> {
let activity_store = ActivityStore::with_storage(storage)?;
let activity_store =
ActivityStore::with_storage(storage).map_err(PaceErrorKind::Storage)?;

let user_message = (activity_store.list_current_activities(ActivityFilterKind::Active)?)
.map_or_else(
|| "No activities are currently running.".to_string(),
|activities| {
debug!("Current Activities: {:?}", activities);
let user_message = (activity_store
.list_current_activities(ActivityFilterKind::Active)
.map_err(PaceErrorKind::Storage)?)
.map_or_else(
|| "No activities are currently running.".to_string(),
|activities| {
debug!("Current Activities: {:?}", activities);

// Get the activity items
let activity_items = activities
.iter()
.flat_map(|activity_id| activity_store.read_activity(*activity_id))
.collect::<Vec<ActivityItem>>();
// Get the activity items
let activity_items = activities
.iter()
.flat_map(|activity_id| activity_store.read_activity(*activity_id))
.collect::<Vec<ActivityItem>>();

let mut msgs = vec![];
for activity in &activity_items {
msgs.push(format!("{}", activity.activity()));
}
let mut msgs = vec![];
for activity in &activity_items {
msgs.push(format!("{}", activity.activity()));
}

msgs.join("\n")
},
);
msgs.join("\n")
},
);

Ok(UserMessage::new(user_message))
}
Expand Down
10 changes: 6 additions & 4 deletions crates/core/src/commands/reflect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::{
config::PaceConfig,
domain::{activity::ActivityKind, filter::FilterOptions, reflection::ReflectionsFormatKind},
error::{PaceResult, TemplatingErrorKind, UserMessage},
prelude::ActivityStorage,
prelude::{ActivityStorage, PaceErrorKind},
service::{activity_store::ActivityStore, activity_tracker::ActivityTracker},
template::{PaceReflectionTemplate, TEMPLATES},
};
Expand Down Expand Up @@ -147,14 +147,16 @@ impl ReflectCommandOptions {
PaceTimeZoneKind::NotSet,
))?;

let activity_store = ActivityStore::with_storage(storage)?;
let activity_store =
ActivityStore::with_storage(storage).map_err(PaceErrorKind::Storage)?;

let activity_tracker = ActivityTracker::with_activity_store(activity_store);

debug!("Displaying reflection for time frame: {}", time_frame);

let Some(reflection) =
activity_tracker.generate_reflection(FilterOptions::from(self), time_frame)?
let Some(reflection) = activity_tracker
.generate_reflection(FilterOptions::from(self), time_frame)
.map_err(PaceErrorKind::Storage)?
else {
return Ok(UserMessage::new(
"No activities found for the specified time frame",
Expand Down
1 change: 0 additions & 1 deletion crates/core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,6 @@ pub enum ActivityLogStorageKind {
#[default]
File,
Database,
#[cfg(test)]
InMemory,
}

Expand Down
43 changes: 27 additions & 16 deletions crates/core/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
//! Error types and Result module.
use displaydoc::Display;
use eyre::Result as EyreResult;
use miette::Diagnostic;
use pace_time::error::PaceTimeErrorKind;
use std::{error::Error, io, path::PathBuf};
use thiserror::Error;

use crate::domain::activity::{Activity, ActivityGuid};

macro_rules! impl_pace_error_marker {
($error:ty) => {
impl PaceErrorMarker for $error {}
};
}

/// Result type that is being returned from test functions and methods that can fail and thus have errors.
pub type TestResult<T> = Result<T, Box<dyn Error + 'static>>;

Expand All @@ -17,6 +24,9 @@ pub type PaceResult<T> = Result<T, PaceError>;
/// Result type that is being returned from methods that have optional return values and can fail thus having [`PaceError`]s.
pub type PaceOptResult<T> = PaceResult<Option<T>>;

pub type PaceStorageResult<T> = EyreResult<T>;
pub type PaceStorageOptResult<T> = EyreResult<Option<T>>;

/// User message type that is being returned from methods that need to print a message to the user.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserMessage {
Expand Down Expand Up @@ -102,9 +112,6 @@ impl PaceError {
#[non_exhaustive]
#[derive(Error, Debug, Display)]
pub enum PaceErrorKind {
// /// [`CommandErrorKind`] describes the errors that can happen while executing a high-level command
// #[error(transparent)]
// Command(#[from] CommandErrorKind),
/// [`std::io::Error`]
#[error(transparent)]
StdIo(#[from] std::io::Error),
Expand Down Expand Up @@ -153,15 +160,16 @@ pub enum PaceErrorKind {
/// Configuration file not found, please run `pace setup config` to initialize `pace`
ParentDirNotFound(PathBuf),

/// Database storage not implemented, yet!
DatabaseStorageNotImplemented,

/// There is no path available to store the activity log
NoPathAvailable,

/// Templating error: {0}
#[error(transparent)]
Template(#[from] TemplatingErrorKind),

/// Storage error: {0}
#[error(transparent)]
Storage(#[from] eyre::Report),
}

/// [`ActivityLogErrorKind`] describes the errors that can happen while dealing with the activity log.
Expand Down Expand Up @@ -297,20 +305,23 @@ pub enum ActivityStoreErrorKind {

/// Missing category for activity: {0}
MissingCategoryForActivity(ActivityGuid),

/// Creating ActivityStore from storage failed
CreatingFromStorageFailed,
}

trait PaceErrorMarker: Error {}

impl PaceErrorMarker for std::io::Error {}
impl PaceErrorMarker for toml::de::Error {}
impl PaceErrorMarker for toml::ser::Error {}
impl PaceErrorMarker for serde_json::Error {}
impl PaceErrorMarker for chrono::ParseError {}
impl PaceErrorMarker for chrono::OutOfRangeError {}
impl PaceErrorMarker for ActivityLogErrorKind {}
impl PaceErrorMarker for PaceTimeErrorKind {}
impl PaceErrorMarker for ActivityStoreErrorKind {}
impl PaceErrorMarker for TemplatingErrorKind {}
impl_pace_error_marker!(std::io::Error);
impl_pace_error_marker!(toml::de::Error);
impl_pace_error_marker!(toml::ser::Error);
impl_pace_error_marker!(serde_json::Error);
impl_pace_error_marker!(chrono::ParseError);
impl_pace_error_marker!(chrono::OutOfRangeError);
impl_pace_error_marker!(ActivityLogErrorKind);
impl_pace_error_marker!(PaceTimeErrorKind);
impl_pace_error_marker!(ActivityStoreErrorKind);
impl_pace_error_marker!(TemplatingErrorKind);

impl<E> From<E> for PaceError
where
Expand Down
4 changes: 2 additions & 2 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ pub mod prelude {
status::ActivityStatusKind,
},
error::{
ActivityLogErrorKind, PaceError, PaceErrorKind, PaceOptResult, PaceResult, TestResult,
UserMessage,
ActivityLogErrorKind, PaceError, PaceErrorKind, PaceOptResult, PaceResult,
PaceStorageOptResult, PaceStorageResult, TestResult, UserMessage,
},
service::{activity_store::ActivityStore, activity_tracker::ActivityTracker},
storage::{
Expand Down
Loading

0 comments on commit 3a7d995

Please sign in to comment.