Skip to content

Alerts updates #1398

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/about.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,10 @@ pub fn print_about(
current_version,
); // " " " "

if let Some(latest_release) = latest_release {
if latest_release.version > current_version {
print_latest_release(latest_release);
}
if let Some(latest_release) = latest_release
&& latest_release.version > current_version
{
print_latest_release(latest_release);
}
Comment on lines +115 to 119
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Let-chain refactor looks correct; confirm MSRV supports it

The combined if let ... && ... is equivalent to the previous nested checks. Please confirm our MSRV/toolchain supports let-chains.

Run this to check declared toolchain/MSRV:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "==> rust-toolchain files (if any)"
fd -a -H -t f 'rust-toolchain*' | while read -r f; do
  echo "----- $f"
  cat "$f"
done

echo "==> rust-version declared in Cargo.toml files"
fd -a -H -t f Cargo.toml | while read -r f; do
  echo "----- $f"
  rg -n '^\s*rust-version\s*=\s*"(\d+\.\d+(\.\d+)?)"' "$f" || true
done

Length of output: 485


MSRV supports let-chains; please fix the typo in the Cargo.toml reference

Our Cargo.toml declares rust-version = "1.88.0", and let-chains have been stable since Rust 1.65.0, so the refactor is safe under the MSRV.

Please address the remaining typo:

• In src/about.rs (around lines 115–119), correct the misspelled reference to “Cargo.toml” in the nearby comment.

🤖 Prompt for AI Agents
In src/about.rs around lines 115 to 119, there is a typo in the comment
referencing "Cargo.toml". Locate the comment near these lines and correct the
spelling of "Cargo.toml" to ensure it is accurate and consistent. This fix is
safe as let-chains are supported by the declared Rust version.


eprintln!(
Expand Down
284 changes: 284 additions & 0 deletions src/alerts/alert_enums.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,284 @@
/*
* Parseable Server (C) 2022 - 2024 Parseable, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/

use std::{
fmt::{self, Display},
str::FromStr,
};

use chrono::{DateTime, Utc};
use derive_more::derive::FromStr;
use serde::ser::Error;
use ulid::Ulid;

use crate::alerts::{
alert_structs::{AnomalyConfig, ForecastConfig, RollingWindow},
alert_traits::AlertTrait,
};

pub enum AlertTask {
Create(Box<dyn AlertTrait>),
Delete(Ulid),
}

#[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum AlertVersion {
V1,
#[default]
V2,
}

impl From<&str> for AlertVersion {
fn from(value: &str) -> Self {
match value {
"v1" => Self::V1,
"v2" => Self::V2,
_ => Self::V2, // default to v2
}
}
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub enum Severity {
Critical,
High,
#[default]
Medium,
Low,
}

impl Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Severity::Critical => write!(f, "Critical"),
Severity::High => write!(f, "High"),
Severity::Medium => write!(f, "Medium"),
Severity::Low => write!(f, "Low"),
}
}
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum LogicalOperator {
And,
Or,
}

impl Display for LogicalOperator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LogicalOperator::And => write!(f, "AND"),
LogicalOperator::Or => write!(f, "OR"),
}
}
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum AlertType {
Threshold,
Anomaly(AnomalyConfig),
Forecast(ForecastConfig),
}

impl Display for AlertType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AlertType::Threshold => write!(f, "threshold"),
AlertType::Anomaly(_) => write!(f, "anomaly"),
AlertType::Forecast(_) => write!(f, "forecast"),
}
}
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum AlertOperator {
#[serde(rename = ">")]
GreaterThan,
#[serde(rename = "<")]
LessThan,
#[serde(rename = "=")]
Equal,
#[serde(rename = "!=")]
NotEqual,
#[serde(rename = ">=")]
GreaterThanOrEqual,
#[serde(rename = "<=")]
LessThanOrEqual,
}

impl Display for AlertOperator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AlertOperator::GreaterThan => write!(f, ">"),
AlertOperator::LessThan => write!(f, "<"),
AlertOperator::Equal => write!(f, "="),
AlertOperator::NotEqual => write!(f, "!="),
AlertOperator::GreaterThanOrEqual => write!(f, ">="),
AlertOperator::LessThanOrEqual => write!(f, "<="),
}
}
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, FromStr, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum WhereConfigOperator {
#[serde(rename = "=")]
Equal,
#[serde(rename = "!=")]
NotEqual,
#[serde(rename = "<")]
LessThan,
#[serde(rename = ">")]
GreaterThan,
#[serde(rename = "<=")]
LessThanOrEqual,
#[serde(rename = ">=")]
GreaterThanOrEqual,
#[serde(rename = "is null")]
IsNull,
#[serde(rename = "is not null")]
IsNotNull,
#[serde(rename = "ilike")]
ILike,
#[serde(rename = "contains")]
Contains,
#[serde(rename = "begins with")]
BeginsWith,
#[serde(rename = "ends with")]
EndsWith,
#[serde(rename = "does not contain")]
DoesNotContain,
#[serde(rename = "does not begin with")]
DoesNotBeginWith,
#[serde(rename = "does not end with")]
DoesNotEndWith,
}

impl WhereConfigOperator {
/// Convert the enum value to its string representation
pub fn as_str(&self) -> &'static str {
match self {
Self::Equal => "=",
Self::NotEqual => "!=",
Self::LessThan => "<",
Self::GreaterThan => ">",
Self::LessThanOrEqual => "<=",
Self::GreaterThanOrEqual => ">=",
Self::IsNull => "is null",
Self::IsNotNull => "is not null",
Self::ILike => "ilike",
Self::Contains => "contains",
Self::BeginsWith => "begins with",
Self::EndsWith => "ends with",
Self::DoesNotContain => "does not contain",
Self::DoesNotBeginWith => "does not begin with",
Self::DoesNotEndWith => "does not end with",
}
}
}

impl Display for WhereConfigOperator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// We can reuse our as_str method to get the string representation
write!(f, "{}", self.as_str())
}
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum AggregateFunction {
Avg,
Count,
CountDistinct,
Min,
Max,
Sum,
}

impl Display for AggregateFunction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AggregateFunction::Avg => write!(f, "Avg"),
AggregateFunction::Count => write!(f, "Count"),
AggregateFunction::CountDistinct => write!(f, "CountDistinct"),
AggregateFunction::Min => write!(f, "Min"),
AggregateFunction::Max => write!(f, "Max"),
AggregateFunction::Sum => write!(f, "Sum"),
}
}
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum EvalConfig {
RollingWindow(RollingWindow),
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Copy, PartialEq, Default, FromStr)]
#[serde(rename_all = "camelCase")]
pub enum AlertState {
Triggered,
#[default]
NotTriggered,
Disabled,
}

impl Display for AlertState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AlertState::Triggered => write!(f, "triggered"),
AlertState::Disabled => write!(f, "disabled"),
AlertState::NotTriggered => write!(f, "not-triggered"),
}
}
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub enum NotificationState {
#[default]
Notify,
/// Snoozed means the alert will evaluate but no notifications will be sent out
///
/// It is a state which can only be set manually
///
/// user needs to pass the timestamp or the duration (in human time) till which the alert is silenced
Mute(String),
}

impl Display for NotificationState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NotificationState::Notify => write!(f, "notify"),
NotificationState::Mute(till_time) => {
let till = match till_time.as_str() {
"indefinite" => DateTime::<Utc>::MAX_UTC.to_rfc3339(),
_ => DateTime::<Utc>::from_str(till_time)
.map_err(|e| std::fmt::Error::custom(e.to_string()))?
.to_rfc3339(),
};
Comment on lines +270 to +279
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Compilation error in Display implementation

fmt::Error has no custom constructor; the ? operator therefore cannot convert chrono::ParseError into fmt::Error.

-                    _ => DateTime::<Utc>::from_str(till_time)
-                        .map_err(|e| std::fmt::Error::custom(e.to_string()))?
+                    _ => DateTime::<Utc>::from_str(till_time)
+                        .map_err(|_| fmt::Error)?

Also, the use serde::ser::Error; import is now unused and can be removed.

🤖 Prompt for AI Agents
In src/alerts/alert_enums.rs around lines 270 to 279, the Display implementation
incorrectly tries to use fmt::Error::custom, which does not exist, causing a
compilation error. Replace the error mapping to convert the chrono::ParseError
into a plain fmt::Error by returning Err(fmt::Error) directly instead of using
custom. Also, remove the unused import of serde::ser::Error from the file to
clean up unused code.

write!(f, "{till}")
}
}
}
}
Loading
Loading