Skip to content
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

refactor: utility Minute handles slotting by minute #1203

Open
wants to merge 8 commits into
base: main
Choose a base branch
from

Conversation

de-sh
Copy link
Contributor

@de-sh de-sh commented Feb 21, 2025

Fixes #XXXX.

Description

  1. Time is directly formatted into the expected name format
  2. Improved tests and sensible conversion to improve readability

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

  • Refactor

    • Streamlined file naming to use a unified format that consolidates date, hour, and minute components.
    • Enhanced time-handling logic for consistent filename generation.
  • Chores

    • Removed the outdated time conversion utility.
  • Tests

    • Adjusted validation tests to reflect the new file naming format.
    • Added new tests for the Minute struct to validate functionality.
  • New Features

    • Introduced a new Minute struct for improved minute handling and slot generation.

Copy link

coderabbitai bot commented Feb 21, 2025

Walkthrough

The pull request refactors the filename generation logic within the Stream struct by introducing a new Minute struct from the utils::time module. The previous minute_to_slot function has been removed, and its functionality has been integrated into the Minute struct. This change consolidates the date and hour into a streamlined filename format. Test cases have been updated to ensure consistency with the new implementation.

Changes

File Change Summary
src/parseable/streams.rs Updated filename generation in the Stream struct; replaced minute_to_slot with Minute::to_slot and consolidated date/hour formatting. Adjusted tests accordingly.
src/utils/mod.rs Removed the minute_to_slot function along with its associated error handling and slot range calculation logic.
src/utils/time.rs Introduced new Minute struct with implementations of TryFrom<u32> and From<NaiveDateTime>. Updated generate_minute_prefixes to use the to_slot method for slot conversion.

Sequence Diagram(s)

sequenceDiagram
    participant S as Stream
    participant T as Timestamp (NaiveDateTime)
    participant M as Minute
    participant P as Path Formatter
    S->>T: Retrieve current timestamp
    T-->>M: Convert timestamp to Minute (via From)
    M->>M: Validate minute using TryFrom
    M-->>S: Return slot range via to_slot()
    S->>P: Format filename with date and slot range
Loading

Poem

I’m a little rabbit, hopping with glee,
Watching code changes as clear as can be.
Minutes now bloom into slots so tight,
Paths shine in order, oh what a sight!
Carrots and code—springing into the light!
Happy hops in every byte!
🥕🐇


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 83f7756 and f512ecd.

📒 Files selected for processing (2)
  • src/parseable/streams.rs (4 hunks)
  • src/utils/time.rs (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/utils/time.rs
  • src/parseable/streams.rs
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: coverage
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu

🪧 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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

@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: 0

🧹 Nitpick comments (2)
src/utils/time.rs (2)

267-271: Add documentation for the block field and usage examples.

While the struct is documented, it would be helpful to:

  1. Document the block field explaining its purpose and valid range.
  2. Add usage examples in the struct documentation.
 /// Describes a minute block
+/// 
+/// Represents a minute value (0-59) and provides methods for converting it to a slot range.
+/// 
+/// # Examples
+/// 
+/// ```
+/// use crate::utils::time::Minute;
+/// 
+/// let minute = Minute::try_from(15).unwrap();
+/// assert_eq!(minute.to_slot(10), "10-19");
+/// ```
 #[derive(Debug, Clone, Copy)]
 pub struct Minute {
+    /// The minute value (0-59)
     block: u32,
 }

273-284: Consider using a custom error type for better error messages.

The current implementation returns the invalid value as the error, which doesn't provide much context. Consider creating a dedicated error type.

+#[derive(Debug, thiserror::Error)]
+pub enum MinuteError {
+    #[error("Invalid minute value {0}, must be less than 60")]
+    InvalidMinute(u32),
+}
+
 impl TryFrom<u32> for Minute {
-    type Error = u32;
+    type Error = MinuteError;

     /// Returns a Minute if block is an acceptable minute value, else returns it as is
     fn try_from(block: u32) -> Result<Self, Self::Error> {
         if block >= 60 {
-            return Err(block);
+            return Err(MinuteError::InvalidMinute(block));
         }

         Ok(Self { block })
     }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between db7c74a and 6e1dd5c.

📒 Files selected for processing (3)
  • src/parseable/streams.rs (5 hunks)
  • src/utils/mod.rs (0 hunks)
  • src/utils/time.rs (3 hunks)
💤 Files with no reviewable changes (1)
  • src/utils/mod.rs
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: coverage
🔇 Additional comments (2)
src/utils/time.rs (1)

232-233: LGTM! Improved error handling and encapsulation.

The refactoring improves type safety by using try_from for validation and encapsulates the slot conversion logic in the Minute struct.

src/parseable/streams.rs (1)

160-164: LGTM! Consistent path format updates.

The changes consistently apply the new path format and leverage the Minute struct for slot calculations, improving maintainability.

Also applies to: 862-865, 896-899

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 21, 2025
Copy link

@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

🧹 Nitpick comments (2)
src/utils/time.rs (2)

282-293: Add tests for TryFrom implementation.

The error handling looks good, but there are no tests for the TryFrom implementation.

Add these test cases to the test module:

#[test]
fn test_minute_try_from() {
    assert!(Minute::try_from(0).is_ok());
    assert!(Minute::try_from(59).is_ok());
    assert!(Minute::try_from(60).is_err());
    assert!(Minute::try_from(61).is_err());
}

303-316: Optimize to_slot method.

The method could be more efficient by avoiding redundant calculations.

 pub fn to_slot(self, data_granularity: u32) -> String {
-    let block_n = self.block / data_granularity;
-    let block_start = block_n * data_granularity;
     if data_granularity == 1 {
-        return format!("{block_start:02}");
+        return format!("{:02}", self.block);
     }
 
+    let block_start = (self.block / data_granularity) * data_granularity;
     let block_end = (block_n + 1) * data_granularity - 1;
     format!("{block_start:02}-{block_end:02}")
 }

Also, consider adding documentation for the parameters and return value:

/// Convert minutes to a slot range
///
/// # Arguments
///
/// * `data_granularity` - The size of each slot in minutes
///
/// # Returns
///
/// A string representing the slot range:
/// - For granularity=1: "MM" where MM is the zero-padded minute
/// - For granularity>1: "SS-EE" where SS is the slot start and EE is the slot end
///
/// # Examples
///
/// ```
/// let minute = Minute::try_from(15).unwrap();
/// assert_eq!(minute.to_slot(1), "15");
/// assert_eq!(minute.to_slot(10), "10-19");
/// ```
pub fn to_slot(self, data_granularity: u32) -> String {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e1dd5c and 8b48680.

📒 Files selected for processing (2)
  • src/parseable/streams.rs (5 hunks)
  • src/utils/time.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/parseable/streams.rs
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: coverage
🔇 Additional comments (2)
src/utils/time.rs (2)

19-19: LGTM!

The addition of NaiveDateTime to the imports is necessary for the new Minute struct's functionality.


267-277: LGTM! Well-documented struct with clear examples.

The documentation clearly explains the purpose and provides helpful examples.

Copy link

@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

🧹 Nitpick comments (1)
src/utils/time.rs (1)

474-502: Add test cases for edge cases and error scenarios.

Consider adding tests for:

  • Invalid data_granularity (0)
  • Overflow scenarios in slot calculations
+    #[test]
+    fn invalid_data_granularity() {
+        let minute = Minute::try_from(30).unwrap();
+        assert_eq!(minute.to_slot(0), "00");
+    }
+
+    #[test]
+    fn overflow_in_slot_calculation() {
+        let minute = Minute::try_from(59).unwrap();
+        assert_eq!(minute.to_slot(u32::MAX), "00");
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8b48680 and 5a8dcb0.

📒 Files selected for processing (1)
  • src/utils/time.rs (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: coverage
🔇 Additional comments (2)
src/utils/time.rs (2)

231-236: Enhance error handling and prevent potential overflow.

The current implementation has two potential issues:

  1. Silent error handling with if let Ok() makes debugging harder
  2. Unprotected multiplication of block * data_granularity could overflow

Apply this diff to address both issues:

-        let mut push_prefix = |block: u32| {
-            if let Ok(minute) = Minute::try_from(block * data_granularity) {
-                let prefix = format!("{hour_prefix}minute={}/", minute.to_slot(data_granularity));
-                prefixes.push(prefix);
-            }
-        };
+        let mut push_prefix = |block: u32| {
+            match block.checked_mul(data_granularity) {
+                Some(minute_value) => {
+                    match Minute::try_from(minute_value) {
+                        Ok(minute) => {
+                            let prefix = format!("{hour_prefix}minute={}/", minute.to_slot(data_granularity));
+                            prefixes.push(prefix);
+                        }
+                        Err(invalid_minute) => {
+                            log::warn!(
+                                "Invalid minute value {} generated from block {} and granularity {}",
+                                invalid_minute, block, data_granularity
+                            );
+                        }
+                    }
+                }
+                None => {
+                    log::warn!(
+                        "Overflow detected when multiplying block {} with granularity {}",
+                        block, data_granularity
+                    );
+                }
+            }
+        };

267-277: LGTM! Well-documented struct with clear examples.

The documentation clearly explains the purpose and usage of the Minute struct.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 21, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants