Skip to content

Commit

Permalink
Refactor unwrap to improve error handling
Browse files Browse the repository at this point in the history
- Refactor `Mutex<bool>` to `AtomicBool` to prevent potential panics and enhance performance.
  • Loading branch information
BLYKIM committed Dec 31, 2024
1 parent ffef4d1 commit eab96b0
Show file tree
Hide file tree
Showing 9 changed files with 36 additions and 30 deletions.
5 changes: 3 additions & 2 deletions src/graphql/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2669,8 +2669,9 @@ fn export_statistic_file(
loop {
match iter.next() {
Some(Ok(item)) => {
// replace new value (min_index's vector value is always exist)
*iter_next_values.get_mut(min_index).unwrap() = item;
*iter_next_values
.get_mut(min_index)
.expect("The index is one of the actual elements in the vector, so it is always valid.") = item;

Check warning on line 2674 in src/graphql/export.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/export.rs#L2672-L2674

Added lines #L2672 - L2674 were not covered by tests
break;
}
Some(Err(_)) => {
Expand Down
3 changes: 1 addition & 2 deletions src/graphql/statistics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,8 +224,7 @@ fn gen_statistics(
for idx in next_candidate {
if let Some(iter) = stats_iters.get_mut(idx) {
if let Some(item) = iter.next() {
// replace new value (value is always exist)
*iter_next_values.get_mut(idx).unwrap() = item;
*iter_next_values.get_mut(idx).expect("`next_candidate` is generated during iteration over `iter_next_values`, ensuring all its indices are valid within the latter.") = item;

Check warning on line 227 in src/graphql/statistics.rs

View check run for this annotation

Codecov / codecov/patch

src/graphql/statistics.rs#L227

Added line #L227 was not covered by tests
} else {
// No value to call with the iterator.
let _ = stats_iters.remove(idx);
Expand Down
6 changes: 4 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,10 @@ extern crate proc_macro;
/// ```
#[proc_macro_derive(ConvertGraphQLEdgesNode, attributes(graphql_client_type))]
pub fn derive_from_graphql_client_autogen(input: TokenStream) -> TokenStream {
derive_from_graphql_client_autogen_2(input.into())
.unwrap()
derive_from_graphql_client_autogen_2(input.clone().into())
.unwrap_or_else(|e| {
panic!("ConvertGraphQLEdgesNode macro is not correctly used for {input:?}: {e}")

Check warning on line 170 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L170

Added line #L170 was not covered by tests
})
.into()
}

Expand Down
14 changes: 7 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ use std::{
fs,
net::SocketAddr,
path::Path,
sync::{Arc, Mutex},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};

Expand Down Expand Up @@ -126,7 +129,7 @@ async fn main() -> Result<()> {
let notify_shutdown = Arc::new(Notify::new());
let notify_reboot = Arc::new(Notify::new());
let notify_power_off = Arc::new(Notify::new());
let retain_flag = Arc::new(Mutex::new(false));
let retain_flag = Arc::new(AtomicBool::new(false));

Check warning on line 132 in src/main.rs

View check run for this annotation

Codecov / codecov/patch

src/main.rs#L132

Added line #L132 was not covered by tests

let database = if let Some(settings) = settings.clone() {
let (db_path, db_options) = db_path_and_option(
Expand Down Expand Up @@ -312,11 +315,8 @@ async fn main() -> Result<()> {

if is_reboot || is_power_off || is_reload_config {
loop {
{
let retain_flag = retain_flag.lock().unwrap();
if !*retain_flag {
break;
}
if !retain_flag.load(Ordering::Relaxed) {
break;

Check warning on line 319 in src/main.rs

View check run for this annotation

Codecov / codecov/patch

src/main.rs#L318-L319

Added lines #L318 - L319 were not covered by tests
}
sleep(Duration::from_millis(SERVER_REBOOT_DELAY)).await;
}
Expand Down
8 changes: 6 additions & 2 deletions src/peer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -717,8 +717,12 @@ async fn update_to_new_peer_list(
if let Err(e) = insert_toml_peers(&mut doc, Some(data)) {
error!("{e:?}");
}
if let Err(e) = write_toml_file(&doc, &path.unwrap()) {
error!("{e:?}");
if let Some(path) = path {
if let Err(e) = write_toml_file(&doc, &path) {
error!("{e:?}");
}

Check warning on line 723 in src/peer.rs

View check run for this annotation

Codecov / codecov/patch

src/peer.rs#L720-L723

Added lines #L720 - L723 were not covered by tests
} else {
error!("Configuration path is None, unable to write to the TOML file.");

Check warning on line 725 in src/peer.rs

View check run for this annotation

Codecov / codecov/patch

src/peer.rs#L725

Added line #L725 was not covered by tests
}
}

Expand Down
3 changes: 1 addition & 2 deletions src/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,8 +528,7 @@ where
info!("start hog's publish stream : {:?}", record_type);
}
NodeType::Crusher => {
// crusher's policy Id always exists.
let id = msg.id().unwrap();
let id = msg.id().expect("Crusher always sends RequestCrusherStream with an id, so this value is guaranteed to exist.");
send_crusher_stream_start_message(&mut sender, id)
.await
.map_err(|e| anyhow!("Failed to write crusher start message: {}", e))?;
Expand Down
7 changes: 5 additions & 2 deletions src/publish/implement.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{net::IpAddr, vec};

use anyhow::{bail, Result};
use anyhow::{anyhow, bail, Result};
use giganto_client::publish::stream::{NodeType, RequestCrusherStream, RequestHogStream};

pub trait RequestStreamMessage {
Expand All @@ -13,14 +13,17 @@ pub trait RequestStreamMessage {

impl RequestStreamMessage for RequestHogStream {
fn channel_key(&self, sensor: Option<String>, record_type: &str) -> Result<Vec<String>> {
let sensor = sensor.ok_or_else(|| {
anyhow!("Failed to generate semi-supervised channel key, sensor is required.")

Check warning on line 17 in src/publish/implement.rs

View check run for this annotation

Codecov / codecov/patch

src/publish/implement.rs#L17

Added line #L17 was not covered by tests
})?;
if let Some(ref sensor_list) = self.sensor {
let hog_keys = sensor_list
.iter()
.map(|target_sensor| {
let mut key = String::new();
key.push_str(&NodeType::Hog.to_string());
key.push('\0');
key.push_str(sensor.as_ref().unwrap());
key.push_str(&sensor);
key.push('\0');
key.push_str(target_sensor);
key.push('\0');
Expand Down
18 changes: 8 additions & 10 deletions src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ use std::{
ops::Deref,
path::{Path, PathBuf},
process::exit,
sync::{Arc, Mutex},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::{Duration, Instant},
};

Expand Down Expand Up @@ -943,7 +946,7 @@ pub async fn retain_periodically(
retention_period: Duration,
db: Database,
notify_shutdown: Arc<Notify>,
running_flag: Arc<Mutex<bool>>,
running_flag: Arc<AtomicBool>,

Check warning on line 949 in src/storage.rs

View check run for this annotation

Codecov / codecov/patch

src/storage.rs#L949

Added line #L949 was not covered by tests
) -> Result<()> {
const DEFAULT_FROM_TIMESTAMP_NANOS: i64 = 61_000_000_000;
const ONE_DAY_TIMESTAMP_NANOS: i64 = 86_400_000_000_000;
Expand All @@ -955,10 +958,8 @@ pub async fn retain_periodically(
select! {
_ = itv.tick() => {
info!("Begin to cleanup the database.");
{
let mut running_flag = running_flag.lock().unwrap();
*running_flag = true;
}
running_flag.store(true, Ordering::Relaxed);

Check warning on line 962 in src/storage.rs

View check run for this annotation

Codecov / codecov/patch

src/storage.rs#L961-L962

Added lines #L961 - L962 were not covered by tests
let now = Utc::now();
let mut retention_timestamp = now
.timestamp_nanos_opt()
Expand Down Expand Up @@ -1037,10 +1038,7 @@ pub async fn retain_periodically(
}
}
info!("Database cleanup completed.");
{
let mut running_flag = running_flag.lock().unwrap();
*running_flag = false;
}
running_flag.store(false, Ordering::Relaxed);

Check warning on line 1041 in src/storage.rs

View check run for this annotation

Codecov / codecov/patch

src/storage.rs#L1041

Added line #L1041 was not covered by tests
},
() = notify_shutdown.notified() => {
return Ok(());
Expand Down
2 changes: 1 addition & 1 deletion src/storage/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ where
continue;
};
let new_key = StorageKey::builder()
.start_key(&netflow_raw_event.sensor().unwrap())
.start_key(&netflow_raw_event.sensor().expect("Netflow source field is always populated during processing, ensuring sensor value exists."))
.end_key(timestamp)
.build();
store.append(&new_key.key(), &value)?;
Expand Down

0 comments on commit eab96b0

Please sign in to comment.