Skip to content

Commit 891e881

Browse files
committed
refactor: replace RwLock with LazyLock and AtomicBool for speeeedddd
1 parent f6a2517 commit 891e881

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

src/handlers/http/resource_check.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
*
1717
*/
1818

19+
use std::sync::{atomic::AtomicBool, Arc, LazyLock};
20+
1921
use actix_web::{
2022
body::MessageBody,
2123
dev::{ServiceRequest, ServiceResponse},
@@ -24,13 +26,12 @@ use actix_web::{
2426
middleware::Next,
2527
};
2628
use tokio::{select, time::{interval, Duration}};
27-
use tokio::sync::RwLock;
2829
use tracing::{warn, trace, info};
2930

3031
use crate::analytics::{SYS_INFO, refresh_sys_info};
3132
use crate::parseable::PARSEABLE;
3233

33-
static RESOURCE_CHECK_ENABLED: RwLock<bool> = RwLock::const_new(true);
34+
static RESOURCE_CHECK_ENABLED:LazyLock<Arc<AtomicBool>> = LazyLock::new(|| Arc::new(AtomicBool::new(false)));
3435

3536
/// Spawn a background task to monitor system resources
3637
pub fn spawn_resource_monitor(shutdown_rx: tokio::sync::oneshot::Receiver<()>) {
@@ -86,9 +87,9 @@ pub fn spawn_resource_monitor(shutdown_rx: tokio::sync::oneshot::Receiver<()>) {
8687
resource_ok = false;
8788
}
8889

89-
let previous_state = *RESOURCE_CHECK_ENABLED.read().await;
90-
*RESOURCE_CHECK_ENABLED.write().await = resource_ok;
91-
90+
let previous_state = RESOURCE_CHECK_ENABLED.load(std::sync::atomic::Ordering::SeqCst);
91+
RESOURCE_CHECK_ENABLED.store(resource_ok, std::sync::atomic::Ordering::SeqCst);
92+
9293
// Log state changes
9394
if previous_state != resource_ok {
9495
if resource_ok {
@@ -114,8 +115,8 @@ pub async fn check_resource_utilization_middleware(
114115
next: Next<impl MessageBody>,
115116
) -> Result<ServiceResponse<impl MessageBody>, Error> {
116117

117-
let resource_ok = *RESOURCE_CHECK_ENABLED.read().await;
118-
118+
let resource_ok = RESOURCE_CHECK_ENABLED.load(std::sync::atomic::Ordering::SeqCst);
119+
119120
if !resource_ok {
120121
let error_msg = "Server resources over-utilized";
121122
warn!("Rejecting request to {} due to resource constraints", req.path());

0 commit comments

Comments
 (0)