Skip to content

Commit 1e1d19d

Browse files
committed
refactor + changes
- refactored code for clippy - modified the base path for prism
1 parent 95ebc74 commit 1e1d19d

File tree

9 files changed

+73
-51
lines changed

9 files changed

+73
-51
lines changed

src/alerts/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -883,7 +883,7 @@ pub struct AlertsInfo {
883883
triggered: u64,
884884
low: u64,
885885
medium: u64,
886-
high: u64
886+
high: u64,
887887
}
888888

889889
// TODO: add RBAC
@@ -920,6 +920,6 @@ pub async fn get_alerts_info() -> Result<AlertsInfo, AlertError> {
920920
triggered,
921921
low,
922922
medium,
923-
high
923+
high,
924924
})
925-
}
925+
}

src/handlers/http/home.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@
1818

1919
use actix_web::{web, HttpRequest, Responder};
2020

21-
use crate::{home::{generate_home_response, HomeError}, utils::actix::extract_session_key_from_req};
22-
21+
use crate::{
22+
home::{generate_home_response, HomeError},
23+
utils::actix::extract_session_key_from_req,
24+
};
2325

2426
/// Fetches the data to populate Prism's home
2527
///
@@ -31,8 +33,7 @@ pub async fn home_api(req: HttpRequest) -> Result<impl Responder, HomeError> {
3133
let key = extract_session_key_from_req(&req)
3234
.map_err(|err| HomeError::Anyhow(anyhow::Error::msg(err.to_string())))?;
3335

34-
let res = generate_home_response(&key)
35-
.await?;
36+
let res = generate_home_response(&key).await?;
3637

3738
Ok(web::Json(res))
38-
}
39+
}

src/handlers/http/mod.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,16 @@ pub mod users;
4848
pub const MAX_EVENT_PAYLOAD_SIZE: usize = 10485760;
4949
pub const API_BASE_PATH: &str = "api";
5050
pub const API_VERSION: &str = "v1";
51+
pub const PRISM_BASE_PATH: &str = "prism";
5152

5253
pub fn base_path() -> String {
5354
format!("/{API_BASE_PATH}/{API_VERSION}")
5455
}
5556

57+
pub fn prism_base_path() -> String {
58+
format!("/{API_BASE_PATH}/{PRISM_BASE_PATH}/{API_VERSION}")
59+
}
60+
5661
pub fn metrics_path() -> String {
5762
format!("{}/metrics", base_path())
5863
}

src/handlers/http/modal/query_server.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ use std::thread;
2121
use crate::alerts::ALERTS;
2222
use crate::correlation::CORRELATIONS;
2323
use crate::handlers::airplane;
24-
use crate::handlers::http::base_path;
2524
use crate::handlers::http::cluster::{self, init_cluster_metrics_schedular};
2625
use crate::handlers::http::middleware::{DisAllowRootUser, RouteExt};
26+
use crate::handlers::http::{base_path, prism_base_path};
2727
use crate::handlers::http::{logstream, MAX_EVENT_PAYLOAD_SIZE};
2828
use crate::handlers::http::{rbac, role};
2929
use crate::hottier::HotTierManager;
@@ -69,9 +69,9 @@ impl ParseableServer for QueryServer {
6969
.service(Server::get_counts_webscope())
7070
.service(Server::get_metrics_webscope())
7171
.service(Server::get_alerts_webscope())
72-
.service(Self::get_cluster_web_scope())
73-
.service(Server::get_prism_home()),
72+
.service(Self::get_cluster_web_scope()),
7473
)
74+
.service(web::scope(&prism_base_path()).service(Server::get_prism_home()))
7575
.service(Server::get_generated());
7676
}
7777

src/handlers/http/modal/server.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use crate::handlers::http::about;
2626
use crate::handlers::http::alerts;
2727
use crate::handlers::http::base_path;
2828
use crate::handlers::http::health_check;
29+
use crate::handlers::http::prism_base_path;
2930
use crate::handlers::http::query;
3031
use crate::handlers::http::users::dashboards;
3132
use crate::handlers::http::users::filters;
@@ -87,9 +88,9 @@ impl ParseableServer for Server {
8788
.service(Self::get_user_role_webscope())
8889
.service(Self::get_counts_webscope())
8990
.service(Self::get_alerts_webscope())
90-
.service(Self::get_metrics_webscope())
91-
.service(Self::get_prism_home()),
91+
.service(Self::get_metrics_webscope()),
9292
)
93+
.service(web::scope(&prism_base_path()).service(Self::get_prism_home()))
9394
.service(Self::get_ingest_otel_factory())
9495
.service(Self::get_generated());
9596
}

src/home/mod.rs

Lines changed: 47 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,21 @@
1616
*
1717
*/
1818

19-
2019
use actix_web::http::header::ContentType;
21-
use chrono::Local;
20+
use chrono::Utc;
2221
use http::StatusCode;
2322
use itertools::Itertools;
2423
use serde::Serialize;
2524

26-
use crate::{alerts::{get_alerts_info, AlertError, AlertsInfo, ALERTS}, correlation::{CorrelationError, CORRELATIONS}, handlers::http::logstream::{error::StreamError, get_stats_date}, parseable::PARSEABLE, rbac::{map::SessionKey, role::Action, Users}, stats::Stats, users::{dashboards::DASHBOARDS, filters::FILTERS}};
25+
use crate::{
26+
alerts::{get_alerts_info, AlertError, AlertsInfo, ALERTS},
27+
correlation::{CorrelationError, CORRELATIONS},
28+
handlers::http::logstream::{error::StreamError, get_stats_date},
29+
parseable::PARSEABLE,
30+
rbac::{map::SessionKey, role::Action, Users},
31+
stats::Stats,
32+
users::{dashboards::DASHBOARDS, filters::FILTERS},
33+
};
2734

2835
#[derive(Debug, Serialize, Default)]
2936
struct StreamInfo {
@@ -43,7 +50,7 @@ struct DatedStats {
4350
#[derive(Debug, Serialize)]
4451
struct TitleAndId {
4552
title: String,
46-
id: String
53+
id: String,
4754
}
4855

4956
#[derive(Debug, Serialize)]
@@ -54,77 +61,82 @@ pub struct HomeResponse {
5461
stream_info: StreamInfo,
5562
stats_details: Vec<DatedStats>,
5663
stream_titles: Vec<String>,
57-
58-
64+
5965
dashboard_titles: Vec<TitleAndId>,
6066
filter_titles: Vec<TitleAndId>,
61-
6267
}
6368

6469
pub async fn generate_home_response(key: &SessionKey) -> Result<HomeResponse, HomeError> {
65-
6670
let user_id = if let Some(user_id) = Users.get_username_from_session(key) {
6771
user_id
6872
} else {
6973
return Err(HomeError::Anyhow(anyhow::Error::msg("User does not exist")));
7074
};
7175

7276
// get all stream titles
73-
let stream_titles = PARSEABLE.streams
77+
let stream_titles: Vec<String> = PARSEABLE
78+
.streams
7479
.list()
75-
.iter()
80+
.into_iter()
7681
.filter(|logstream| {
77-
Users.authorize(key.clone(), Action::ListStream, Some(&logstream), None) == crate::rbac::Response::Authorized
82+
Users.authorize(key.clone(), Action::ListStream, Some(logstream), None)
83+
== crate::rbac::Response::Authorized
7884
})
79-
.map(|logstream| logstream.clone())
80-
.collect_vec();
85+
.collect();
8186

82-
// get all alert titles (TODO: RBAC)
87+
// get all alert IDs (TODO: RBAC)
8388
// do we need to move alerts into the PARSEABLE struct?
8489
let alert_titles = ALERTS
8590
.list_alerts_for_user(key.clone())
8691
.await?
8792
.iter()
8893
.map(|alert| TitleAndId {
8994
title: alert.title.clone(),
90-
id: alert.id.to_string()
95+
id: alert.id.to_string(),
9196
})
9297
.collect_vec();
9398

99+
// get correlation IDs
94100
let correlation_titles = CORRELATIONS
95101
.list_correlations(key)
96102
.await?
97103
.iter()
98104
.map(|corr| TitleAndId {
99105
title: corr.title.clone(),
100-
id: corr.id.clone()
106+
id: corr.id.clone(),
101107
})
102108
.collect_vec();
103109

110+
// get dashboard IDs
104111
let dashboard_titles = DASHBOARDS
105112
.list_dashboards_by_user(&user_id)
106113
.iter()
107114
.map(|dashboard| TitleAndId {
108115
title: dashboard.name.clone(),
109-
id: dashboard.dashboard_id.as_ref().unwrap().clone()
116+
id: dashboard.dashboard_id.as_ref().unwrap().clone(),
110117
})
111118
.collect_vec();
112119

120+
// get filter IDs
113121
let filter_titles = FILTERS
114122
.list_filters_by_user(&user_id)
115123
.iter()
116-
.map(|filter| {
117-
TitleAndId {
118-
title: filter.filter_name.clone(),
119-
id: filter.filter_id.as_ref().unwrap().clone()
120-
}
124+
.map(|filter| TitleAndId {
125+
title: filter.filter_name.clone(),
126+
id: filter.filter_id.as_ref().unwrap().clone(),
121127
})
122128
.collect_vec();
123-
129+
130+
// get alerts info (distribution of alerts based on severity and state)
124131
let alerts_info = get_alerts_info().await?;
125132

133+
// generate dates for date-wise stats
126134
let dates = (0..7)
127-
.map(|i| Local::now().checked_sub_signed(chrono::Duration::days(i)).unwrap())
135+
.map(|i| {
136+
Utc::now()
137+
.checked_sub_signed(chrono::Duration::days(i))
138+
.unwrap()
139+
})
128140
.map(|date| date.format("%Y-%m-%d").to_string())
129141
.collect_vec();
130142

@@ -133,17 +145,20 @@ pub async fn generate_home_response(key: &SessionKey) -> Result<HomeResponse, Ho
133145
let mut summary = StreamInfo::default();
134146

135147
for date in dates.iter() {
136-
let mut details = DatedStats::default();
137-
details.date = date.clone();
148+
let mut details = DatedStats {
149+
date: date.clone(),
150+
..Default::default()
151+
};
138152

139153
for stream in stream_titles.iter() {
140-
let stats = get_stats_date(stream, &date)
141-
.await?;
154+
let stats = get_stats_date(stream, date).await?;
142155

156+
// collect date-wise stats for all streams
143157
details.events += stats.events;
144158
details.ingestion_size += stats.ingestion;
145159
details.storage_size += stats.storage;
146160

161+
// collect all 7-day stats for all streams
147162
summary.stats_summary.events += stats.events;
148163
summary.stats_summary.ingestion += stats.ingestion;
149164
summary.stats_summary.storage += stats.storage;
@@ -160,7 +175,7 @@ pub async fn generate_home_response(key: &SessionKey) -> Result<HomeResponse, Ho
160175
correlation_titles,
161176
dashboard_titles,
162177
filter_titles,
163-
alerts_info
178+
alerts_info,
164179
})
165180
}
166181

@@ -173,7 +188,7 @@ pub enum HomeError {
173188
#[error("CorrelationError: {0}")]
174189
CorrelationError(#[from] CorrelationError),
175190
#[error("StreamError: {0}")]
176-
StreamError(#[from] StreamError)
191+
StreamError(#[from] StreamError),
177192
}
178193

179194
impl actix_web::ResponseError for HomeError {
@@ -182,7 +197,7 @@ impl actix_web::ResponseError for HomeError {
182197
HomeError::Anyhow(_) => StatusCode::INTERNAL_SERVER_ERROR,
183198
HomeError::AlertError(e) => e.status_code(),
184199
HomeError::CorrelationError(e) => e.status_code(),
185-
HomeError::StreamError(e) => e.status_code()
200+
HomeError::StreamError(e) => e.status_code(),
186201
}
187202
}
188203

@@ -191,4 +206,4 @@ impl actix_web::ResponseError for HomeError {
191206
.insert_header(ContentType::plaintext())
192207
.body(self.to_string())
193208
}
194-
}
209+
}

src/metadata.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
*/
1818

1919
use arrow_schema::{DataType, Field, Schema, TimeUnit};
20-
use chrono::{Local, NaiveDateTime};
20+
use chrono::{NaiveDateTime, Utc};
2121
use serde::{Deserialize, Serialize};
2222
use std::collections::HashMap;
2323
use std::num::NonZeroU32;
@@ -105,7 +105,7 @@ impl LogStreamMetadata {
105105
) -> Self {
106106
LogStreamMetadata {
107107
created_at: if created_at.is_empty() {
108-
Local::now().to_rfc3339()
108+
Utc::now().to_rfc3339()
109109
} else {
110110
created_at
111111
},

src/parseable/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use std::{collections::HashMap, num::NonZeroU32, path::PathBuf, str::FromStr, sy
2222
use actix_web::http::header::HeaderMap;
2323
use arrow_schema::{Field, Schema};
2424
use bytes::Bytes;
25-
use chrono::Local;
25+
use chrono::Utc;
2626
use clap::{error::ErrorKind, Parser};
2727
use http::{header::CONTENT_TYPE, HeaderName, HeaderValue, StatusCode};
2828
use once_cell::sync::Lazy;
@@ -567,7 +567,7 @@ impl Parseable {
567567
let storage = self.storage.get_object_store();
568568

569569
let meta = ObjectStoreFormat {
570-
created_at: Local::now().to_rfc3339(),
570+
created_at: Utc::now().to_rfc3339(),
571571
permissions: vec![Permisssion::new(PARSEABLE.options.username.clone())],
572572
stream_type,
573573
time_partition: (!time_partition.is_empty()).then(|| time_partition.to_string()),

src/storage/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use crate::{
2626
utils::json::{deserialize_string_as_true, serialize_bool_as_true},
2727
};
2828

29-
use chrono::Local;
29+
use chrono::Utc;
3030
use serde::{Deserialize, Serialize};
3131

3232
use std::fmt::Debug;
@@ -208,7 +208,7 @@ impl Default for ObjectStoreFormat {
208208
schema_version: SchemaVersion::V1, // Newly created streams should be v1
209209
objectstore_format: CURRENT_OBJECT_STORE_VERSION.to_string(),
210210
stream_type: StreamType::UserDefined,
211-
created_at: Local::now().to_rfc3339(),
211+
created_at: Utc::now().to_rfc3339(),
212212
first_event_at: None,
213213
owner: Owner::new("".to_string(), "".to_string()),
214214
permissions: vec![Permisssion::new("parseable".to_string())],

0 commit comments

Comments
 (0)