Skip to content

Updates #1412

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 1 commit into
base: main
Choose a base branch
from
Open

Updates #1412

wants to merge 1 commit into from

Conversation

parmesant
Copy link
Contributor

@parmesant parmesant commented Aug 22, 2025

  • respect alert state during modification
  • validation for notification snooze time

Fixes #XXXX.

Description


This PR has:

  • been tested to ensure log ingestion and log query works.
  • added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
  • added documentation for new or modified features or behaviors.

Summary by CodeRabbit

  • Bug Fixes

    • Prevented scheduling alerts with a UTC timestamp in the past.
    • Updating an alert to Disabled no longer triggers unnecessary task deletion or restart.
  • Improvements

    • Validation error now explicitly lists valid notification state options (notify, human-time, UTC datetime, indefinite).
    • Modifying disabled alerts skips task-management steps for more predictable, less noisy behavior.

Copy link
Contributor

coderabbitai bot commented Aug 22, 2025

Walkthrough

Adds UTC timestamp validation to reject past times in update_notification_state, expands the InvalidStateChange message to mention indefinite, and in PUT /alerts/{alert_id} computes is_disabled to skip task deletion/restart when the new state is Disabled. No public signatures changed.

Changes

Cohort / File(s) Summary of Changes
Alert state update & task management
src/handlers/http/alerts.rs
- Validate provided UTC timestamp is not in the past; return InvalidStateChange if it is.
- Expanded InvalidStateChange message to include indefinite as a valid option.
- In PUT /alerts/{alert_id} compute is_disabled = new_alert.get_state().eq(&AlertState::Disabled) and skip task delete/restart when Disabled.
- Other update/delete/write flows unchanged; only task-management steps gated by Disabled.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant H as AlertsHandler
  participant DB as Storage
  participant S as Scheduler

  rect rgb(250,250,255)
  C->>H: PUT /alerts/{id} with new state (maybe UTC ts)
  H->>H: Parse new state, compute is_disabled
  H->>DB: Update alert record
  alt is_disabled == true
    note right of H: Skip task deletion/restart
    H-->>C: 200 OK
  else is_disabled == false
    H->>S: Delete existing scheduled task (if any)
    H->>S: Restart/reschedule task
    H-->>C: 200 OK
  end
  end
Loading
sequenceDiagram
  autonumber
  participant X as Caller
  participant H as update_notification_state

  X->>H: Request with state / optional UTC timestamp
  alt UTC timestamp provided
    H->>H: Check timestamp >= now (UTC)
    alt timestamp < now
      H-->>X: Error InvalidStateChange ("Provided time is < Now")
    else timestamp >= now
      H-->>X: Proceed
    end
  else No UTC timestamp
    note right of H: Accept `notify` | human-time | UTC | `indefinite`
    H-->>X: Proceed
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • bugfixes #1395 — Touches src/handlers/http/alerts.rs; refactors handler/state update flow and overlaps with state-handling and scheduling logic changes in this PR.

Poem

I hop at timestamps, never late—
Past times denied at the gate.
If Disabled## Walkthrough
Adds UTC timestamp validation to reject past times in update_notification_state, expands the InvalidStateChange message to mention indefinite, and in PUT /alerts/{alert_id} computes is_disabled to skip task deletion/restart when the new state is Disabled. No public signatures changed.

Changes

Cohort / File(s) Summary of Changes
Alert state update & task management
src/handlers/http/alerts.rs
- Validate provided UTC timestamp is not in the past; return InvalidStateChange if it is.
- Expanded InvalidStateChange message to include indefinite as a valid option.
- In PUT /alerts/{alert_id} compute is_disabled = new_alert.get_state().eq(&AlertState::Disabled) and skip task delete/restart when Disabled.
- Other update/delete/write flows unchanged; only task-management steps gated by Disabled.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant H as AlertsHandler
  participant DB as Storage
  participant S as Scheduler

  rect rgb(250,250,255)
  C->>H: PUT /alerts/{id} with new state (maybe UTC ts)
  H->>H: Parse new state, compute is_disabled
  H->>DB: Update alert record
  alt is_disabled == true
    note right of H: Skip task deletion/restart
    H-->>C: 200 OK
  else is_disabled == false
    H->>S: Delete existing scheduled task (if any)
    H->>S: Restart/reschedule task
    H-->>C: 200 OK
  end
  end
Loading
sequenceDiagram
  autonumber
  participant X as Caller
  participant H as update_notification_state

  X->>H: Request with state / optional UTC timestamp
  alt UTC timestamp provided
    H->>H: Check timestamp >= now (UTC)
    alt timestamp < now
      H-->>X: Error InvalidStateChange ("Provided time is < Now")
    else timestamp >= now
      H-->>X: Proceed
    end
  else No UTC timestamp
    note right of H: Accept `notify` | human-time | UTC | `indefinite`
    H-->>X: Proceed
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • bugfixes #1395 — Touches src/handlers/http/alerts.rs; refactors handler/state update flow and overlaps with state-handling and scheduling logic changes in this PR.

Poem

I hop at timestamps, never late—
Past times denied at the gate.
If Disabled, tasks stand still,
Otherwise they run with will.
— A punctual rabbit 🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3acc0da and cf439d0.

📒 Files selected for processing (1)
  • src/handlers/http/alerts.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/handlers/http/alerts.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: coverage
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/handlers/http/alerts.rs (1)

443-451: Mirror POST validations to prevent divide-by-zero and invalid schedules in modify_alert.

Unlike POST, PUT lacks checks for eval_freq == 0, notif_freq == 0, and notif_freq > eval_freq. This can panic on division by zero and allow invalid schedules.

Apply this diff before computing times:

     let eval_freq = new_config.get_eval_frequency();
     let notif_freq = new_config.notification_config.interval;
+    // Mirror POST validations to prevent invalid schedules
+    if eval_freq == 0 {
+        return Err(AlertError::ValidationFailure("Eval frequency cannot be 0".into()));
+    }
+    if notif_freq == 0 {
+        return Err(AlertError::ValidationFailure("Notification interval cannot be 0".into()));
+    }
+    if notif_freq > eval_freq {
+        return Err(AlertError::ValidationFailure(
+            "Notification interval cannot exceed evaluation frequency".into(),
+        ));
+    }
     let times = if (eval_freq / notif_freq) == 0 {
         1
     } else {
         (eval_freq / notif_freq) as usize
     };
🧹 Nitpick comments (1)
src/handlers/http/alerts.rs (1)

314-316: Clarify the invalid-input message for snooze state.

Minor copy improvement for readability and examples.

Apply this tweak (already included in the larger refactor above):

-                    "Invalid notification state change request. Expected `notify`, `indefinite` or human-time or UTC datetime. Got `{}`",
-                    &new_notification_state.state
+                    "Invalid notification state change request. Expected one of: `notify`, `indefinite`, human-time duration (e.g., \"15m\"), or UTC RFC3339 datetime. Got `{}`",
+                    state_str
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 0e35b07 and 3acc0da.

📒 Files selected for processing (1)
  • src/handlers/http/alerts.rs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: coverage
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
🔇 Additional comments (2)
src/handlers/http/alerts.rs (2)

493-495: LGTM: restart is correctly gated by Disabled state.

Only starting the task when not Disabled is correct and aligns with the PR objective.


295-320: Apply stronger snooze-time validation in alerts handler

Chrono v0.4.39 (your repo’s version) supports chrono::Duration::from_std, so this refactor is safe to apply.

File: src/handlers/http/alerts.rs (lines 295–320)

-    let new_notification_state = match new_notification_state.state.as_str() {
+    let state_str = new_notification_state.state.trim();
+    let now = Utc::now();
+    let new_notification_state = match state_str {
         "notify" => NotificationState::Notify,
-        "indefinite" => NotificationState::Mute("indefinite".into()),
+        "indefinite" => NotificationState::Mute("indefinite".into()),
         _ => {
             // either human time or datetime in UTC
-            let till_time = if let Ok(duration) =
-                humantime::parse_duration(&new_notification_state.state)
-            {
-                (Utc::now() + duration).to_rfc3339()
-            } else if let Ok(timestamp) = DateTime::<Utc>::from_str(&new_notification_state.state) {
+            let till_time = if let Ok(std_dur) = humantime::parse_duration(state_str) {
+                if std_dur.is_zero() {
+                    return Err(AlertError::InvalidStateChange(
+                        "Invalid notification state change request. Duration must be > 0.".into(),
+                    ));
+                }
+                let chrono_dur = chrono::Duration::from_std(std_dur).map_err(|_| {
+                    AlertError::InvalidStateChange(
+                        "Invalid notification state change request. Duration is out of range."
+                            .into(),
+                    )
+                })?;
+                (now + chrono_dur).to_rfc3339()
+            } else if let Ok(timestamp) = DateTime::<Utc>::from_str(state_str) {
                 // must be datetime UTC then
-                if timestamp < Utc::now() {
+                if timestamp <= now {
                     return Err(AlertError::InvalidStateChange(
-                        "Invalid notification state change request. Provided time is < Now".into(),
+                        "Invalid notification state change request. Provided time must be in the future."
+                            .into(),
                     ));
                 }
                 timestamp.to_rfc3339()
             } else {
                 return Err(AlertError::InvalidStateChange(format!(
-                    "Invalid notification state change request. Expected `notify`, `indefinite` or human-time or UTC datetime. Got `{}`",
-                    &new_notification_state.state
+                    "Invalid notification state change request. Expected one of: `notify`, `indefinite`, human-time duration (e.g., \"15m\"), or UTC RFC3339 datetime. Got `{}`",
+                    state_str
                 )));
             };
             NotificationState::Mute(till_time)
         }
     };

- respect alert state during modification
- validation for notification snooze time
Copy link
Member

@nitisht nitisht left a comment

Choose a reason for hiding this comment

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

Please use proper PR header and commit message

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants