Skip to content

Commit f6bc1da

Browse files
author
bconn98
committed
chore: cleaner error handling with Result
1 parent 83fd3ed commit f6bc1da

File tree

1 file changed

+42
-33
lines changed
  • src/append/rolling_file/policy/compound/trigger

1 file changed

+42
-33
lines changed

src/append/rolling_file/policy/compound/trigger/time.rs

Lines changed: 42 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -73,17 +73,9 @@ impl Default for TimeTriggerInterval {
7373
}
7474

7575
#[derive(Debug, Error)]
76-
enum TimeTrigerIntervalError {
77-
#[error("The 'Seconds' time trigger interval value is out of bounds, ensure it fits within an i64: : '{0:?}'")]
78-
Second(TimeTriggerInterval),
79-
#[error("The 'Minutes' time trigger interval value is out of bounds, ensure it fits within an i64: : '{0:?}'")]
80-
Minute(TimeTriggerInterval),
81-
#[error("The 'Hours' time trigger interval value is out of bounds, ensure it fits within an i64: : '{0:?}'")]
82-
Hour(TimeTriggerInterval),
83-
#[error("The 'Days' time trigger interval value is out of bounds, ensure it fits within an i64: : '{0:?}'")]
84-
Day(TimeTriggerInterval),
85-
#[error("The 'Weeks' time trigger interval value is out of bounds, ensure it fits within an i64: : '{0:?}'")]
86-
Week(TimeTriggerInterval),
76+
enum TimeTriggerIntervalError {
77+
#[error("The '{0}' value specified as a time trigger is out of bounds, ensure it fits within an i64: : '{1:?}'")]
78+
OutOfBounds(String, TimeTriggerInterval),
8779
}
8880

8981
#[cfg(feature = "config_parsing")]
@@ -188,7 +180,7 @@ impl<'de> serde::Deserialize<'de> for TimeTriggerInterval {
188180
impl TimeTrigger {
189181
/// Returns a new trigger which rolls the log once it has passed the
190182
/// specified time.
191-
pub fn new(config: TimeTriggerConfig) -> TimeTrigger {
183+
pub fn new(config: TimeTriggerConfig) -> anyhow::Result<TimeTrigger> {
192184
#[cfg(test)]
193185
let current = {
194186
let now: std::time::Duration = SystemTime::now()
@@ -203,9 +195,8 @@ impl TimeTrigger {
203195

204196
#[cfg(not(test))]
205197
let current = Local::now();
206-
// In the case where bad user input results in an invalid next time, provide a valid time.
207-
let next_time = TimeTrigger::get_next_time(current, config.interval, config.modulate)
208-
.unwrap_or(current + Duration::try_seconds(1_i64).unwrap());
198+
// TODO: Design an implement error handling at a project level scope instead of panic
199+
let next_time = TimeTrigger::get_next_time(current, config.interval, config.modulate)?;
209200
let next_roll_time = if config.max_random_delay > 0 {
210201
let random_delay = rand::thread_rng().gen_range(0..config.max_random_delay);
211202
// This is a valid unwrap because chrono::Duration::try_milliseconds accepts an i64
@@ -220,17 +211,17 @@ impl TimeTrigger {
220211
next_time
221212
};
222213

223-
TimeTrigger {
214+
Ok(TimeTrigger {
224215
config,
225216
next_roll_time: RwLock::new(next_roll_time),
226-
}
217+
})
227218
}
228219

229220
fn get_next_time(
230221
current: DateTime<Local>,
231222
interval: TimeTriggerInterval,
232223
modulate: bool,
233-
) -> Result<DateTime<Local>, TimeTrigerIntervalError> {
224+
) -> Result<DateTime<Local>, TimeTriggerIntervalError> {
234225
let year = current.year();
235226
if let TimeTriggerInterval::Year(n) = interval {
236227
let n = n as i32;
@@ -259,18 +250,21 @@ impl TimeTrigger {
259250
let weekday = current.weekday().num_days_from_monday() as i64; // Monday is the first day of the week
260251
let time = Local.with_ymd_and_hms(year, month, day, 0, 0, 0).unwrap();
261252
let increment = if modulate { n - week0 % n } else { n };
262-
let dur = Duration::try_weeks(increment)
263-
.ok_or(TimeTrigerIntervalError::Week(interval))?
264-
- Duration::try_days(weekday).ok_or(TimeTrigerIntervalError::Day(interval))?;
253+
let dur = Duration::try_weeks(increment).ok_or(
254+
TimeTriggerIntervalError::OutOfBounds("Weeks".to_owned(), interval),
255+
)? - Duration::try_days(weekday).ok_or(
256+
TimeTriggerIntervalError::OutOfBounds("Days".to_owned(), interval),
257+
)?;
265258
return Ok(time + dur);
266259
}
267260

268261
if let TimeTriggerInterval::Day(n) = interval {
269262
let ordinal0 = current.ordinal0() as i64;
270263
let time = Local.with_ymd_and_hms(year, month, day, 0, 0, 0).unwrap();
271264
let increment = if modulate { n - ordinal0 % n } else { n };
272-
let dur =
273-
Duration::try_days(increment).ok_or(TimeTrigerIntervalError::Day(interval))?;
265+
let dur = Duration::try_days(increment).ok_or(
266+
TimeTriggerIntervalError::OutOfBounds("Days".to_owned(), interval),
267+
)?;
274268
return Ok(time + dur);
275269
}
276270

@@ -280,8 +274,9 @@ impl TimeTrigger {
280274
.with_ymd_and_hms(year, month, day, hour, 0, 0)
281275
.unwrap();
282276
let increment = if modulate { n - (hour as i64) % n } else { n };
283-
let dur =
284-
Duration::try_hours(increment).ok_or(TimeTrigerIntervalError::Hour(interval))?;
277+
let dur = Duration::try_hours(increment).ok_or(
278+
TimeTriggerIntervalError::OutOfBounds("Hours".to_owned(), interval),
279+
)?;
285280
return Ok(time + dur);
286281
}
287282

@@ -291,8 +286,9 @@ impl TimeTrigger {
291286
.with_ymd_and_hms(year, month, day, hour, min, 0)
292287
.unwrap();
293288
let increment = if modulate { n - (min as i64) % n } else { n };
294-
let dur = Duration::try_minutes(increment)
295-
.ok_or(TimeTrigerIntervalError::Minute(interval))?;
289+
let dur = Duration::try_minutes(increment).ok_or(
290+
TimeTriggerIntervalError::OutOfBounds("Minutes".to_owned(), interval),
291+
)?;
296292
return Ok(time + dur);
297293
}
298294

@@ -302,8 +298,9 @@ impl TimeTrigger {
302298
.with_ymd_and_hms(year, month, day, hour, min, sec)
303299
.unwrap();
304300
let increment = if modulate { n - (sec as i64) % n } else { n };
305-
let dur = Duration::try_seconds(increment)
306-
.ok_or(TimeTrigerIntervalError::Second(interval))?;
301+
let dur = Duration::try_seconds(increment).ok_or(
302+
TimeTriggerIntervalError::OutOfBounds("Seconds".to_owned(), interval),
303+
)?;
307304
return Ok(time + dur);
308305
}
309306
panic!("Should not reach here!");
@@ -329,7 +326,7 @@ impl Trigger for TimeTrigger {
329326
let mut next_roll_time = self.next_roll_time.write().unwrap();
330327
let is_trigger = current >= *next_roll_time;
331328
if is_trigger {
332-
let tmp = TimeTrigger::new(self.config);
329+
let tmp = TimeTrigger::new(self.config)?;
333330
let time_new = tmp.next_roll_time.read().unwrap();
334331
*next_roll_time = *time_new;
335332
}
@@ -368,7 +365,7 @@ impl Deserialize for TimeTriggerDeserializer {
368365
config: TimeTriggerConfig,
369366
_: &Deserializers,
370367
) -> anyhow::Result<Box<dyn Trigger>> {
371-
Ok(Box::new(TimeTrigger::new(config)))
368+
Ok(Box::new(TimeTrigger::new(config)?))
372369
}
373370
}
374371

@@ -396,7 +393,7 @@ mod test {
396393
max_random_delay: 0,
397394
};
398395

399-
let trigger = TimeTrigger::new(config);
396+
let trigger = TimeTrigger::new(config).unwrap();
400397

401398
MockClock::advance_system_time(Duration::from_millis(millis / 2));
402399
let result1 = trigger.trigger(&logfile).unwrap();
@@ -526,6 +523,18 @@ mod test {
526523
max_random_delay: 0,
527524
};
528525
let trigger = TimeTrigger::new(config);
529-
assert!(trigger.is_pre_process());
526+
assert!(trigger.unwrap().is_pre_process());
527+
}
528+
529+
#[test]
530+
fn test_err() {
531+
let config = TimeTriggerConfig {
532+
interval: TimeTriggerInterval::Day(i64::MAX),
533+
modulate: false,
534+
max_random_delay: 0,
535+
};
536+
537+
let trigger = TimeTrigger::new(config);
538+
assert!(trigger.is_err());
530539
}
531540
}

0 commit comments

Comments
 (0)