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: move kinesis to src/ #1269

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

refactor: move kinesis to src/ #1269

wants to merge 2 commits into from

Conversation

de-sh
Copy link
Contributor

@de-sh de-sh commented Mar 25, 2025

Fixes #XXXX.

Description

  • Moves to src/kinesis.rs
  • Adds tests to improve coverage

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

  • New Features
    • Introduced a dedicated module for processing Kinesis log data.
    • Added functionality to parse Kinesis logs into a queryable JSON format.
  • Refactor
    • Reorganized import statements for improved clarity.
  • Tests
    • Expanded test coverage to ensure accurate decoding and robust error handling in log ingestion.

Copy link

coderabbitai bot commented Mar 25, 2025

Walkthrough

This pull request removes the legacy Kinesis log parsing functionality from the HTTP handlers and reintroduces it in a new module. The functionality originally in src/handlers/http/kinesis.rs has been relocated to a new file at src/kinesis.rs, where the same parsing logic is implemented along with unit tests. Additionally, the module declaration in src/handlers/http/mod.rs is removed, and a new module is added in src/lib.rs. Minor adjustments were made in the import statements of src/handlers/http/modal/utils/ingest_utils.rs to accommodate these structural changes.

Changes

File(s) Summary of Changes
src/handlers/http/kinesis.rs Removed: Deleted file containing the Kinesis log parsing logic (structs Message, Data and function flatten_kinesis_logs).
src/handlers/http/mod.rs Modified: Removed the module declaration for kinesis, detaching its functionality from the HTTP handlers.
src/handlers/http/modal/utils/ingest_utils.rs Modified: Reorganized import statements; consolidated and adjusted paths for flatten_kinesis_logs and Message.
src/kinesis.rs and src/lib.rs Added: Introduced new file src/kinesis.rs with Kinesis log parsing logic (including the redefined Message, Data and flatten_kinesis_logs), along with unit tests; updated src/lib.rs to add the kinesis module.

Sequence Diagram(s)

sequenceDiagram
    participant C as Caller
    participant F as flatten_kinesis_logs
    participant B as Base64 Decoder
    participant J as JSON Deserializer

    C->>F: Call flatten_kinesis_logs(Message)
    F->>F: Iterate over each record
    F->>B: Decode base64 data
    B-->>F: Decoded string
    F->>J: Deserialize JSON
    J-->>F: JSON object (or error)
    F->>F: Append request_id & timestamp
    F-->>C: Return vector of JSON objects
Loading

Poem

I'm a nimble rabbit with a coding flair,
Hopping through modules with debuggable care.
Old paths removed, new paths begin,
Code rearranged like carrots in a bin.
With every hop, our log parsing sings—
Cheers to clean code and fresh beginnings!
🐰💻

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@de-sh de-sh marked this pull request as ready for review March 25, 2025 06:43
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/kinesis.rs (2)

24-34: Validate naming of structs and ensure future extensibility.

The Message struct and the nested Data struct are named generically. If there's any chance that these data structures evolve to handle more Kinesis event fields (e.g. metadata), consider giving them more descriptive names or making them more flexible. Otherwise, they look fine for the current scope.


87-227: Great coverage of typical scenarios.

The tests thoroughly validate typical Kinesis logs, successfully confirming base64 decoding, correct JSON structure, and proper handling of malformed data. You might want to add a test for an empty records array to ensure correct behavior in that edge case.

🛑 Comments failed to post (1)
src/kinesis.rs (1)

36-85: 🛠️ Refactor suggestion

Avoid panicking on invalid data.

Calling unwrap() on base64 decoding and JSON parsing causes a full panic if data is malformed. While there’s a test that verifies this behavior, you might consider returning an error or skipping malformed records rather than bringing down the entire server in production.

-pub fn flatten_kinesis_logs(message: Message) -> Vec<Value> {
+pub fn flatten_kinesis_logs(message: Message) -> Result<Vec<Value>, SomeErrorType> {
    ...
-        let bytes = STANDARD.decode(record.data.clone()).unwrap();
+        let bytes = STANDARD.decode(record.data.clone())
+            .map_err(|e| SomeErrorType::DecodeError(e.to_string()))?;
    ...
-        let json_string: String = String::from_utf8(bytes).unwrap();
+        let json_string: String = String::from_utf8(bytes)
+            .map_err(|e| SomeErrorType::Utf8Error(e.to_string()))?;
    ...
-        let json: serde_json::Value = serde_json::from_str(&json_string).unwrap();
+        let json: serde_json::Value = serde_json::from_str(&json_string)
+            .map_err(|e| SomeErrorType::SerdeError(e.to_string()))?;
    ...
-            Err(error) => panic!("Failed to deserialize JSON: {}", error),
+            Err(error) => return Err(SomeErrorType::JsonDeserialization(error.to_string())),
    ...
}

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 25, 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/kinesis.rs (2)

183-196: Consider adding more error test cases

While you have a test for invalid base64 data, consider adding tests for other error scenarios like malformed JSON after decoding valid base64, or empty records array.

If you implement the error handling suggestion above, you should update this test to verify errors are returned rather than expecting panics:

#[test]
fn malformed_json_after_base64_decoding_returns_error() {
    let message: Message = serde_json::from_value(json!({
        "requestId": "9b848d8a-2d89-474b-b073-04b8e5232210".to_string(),
        "timestamp": 1705026780451_i64,
        "records": [ {
            "data": "invalid_base64_data".to_string(),
        }],
    }))
    .unwrap();

    let result = flatten_kinesis_logs(message);
    assert!(result.is_err());
}

72-79: Use consistent string conversion methods

The code uses both to_owned() and to_string() for similar string conversions. Consider standardizing on one approach for consistency.

 kinesis_json.insert(
     "requestId".to_owned(),
     Value::String(message.request_id.clone()),
 );
 kinesis_json.insert(
-    "timestamp".to_owned(),
+    "timestamp".to_string(),
     Value::String(message.timestamp.to_string()),
 );

Or alternatively:

 kinesis_json.insert(
-    "requestId".to_owned(),
+    "requestId".to_string(),
     Value::String(message.request_id.clone()),
 );
 kinesis_json.insert(
-    "timestamp".to_owned(),
+    "timestamp".to_string(),
     Value::String(message.timestamp.to_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 f57aff1 and 5b5f802.

📒 Files selected for processing (1)
  • src/kinesis.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • 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 Kafka x86_64-unknown-linux-gnu
  • GitHub Check: coverage
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
🔇 Additional comments (4)
src/kinesis.rs (4)

24-34: Good structure definition for Kinesis message format

The Message and Data structs are well-defined with appropriate serialization attributes. The #[serde(rename_all = "camelCase")] attribute ensures proper JSON mapping.


36-59: Good documentation with clear format examples

The comments provide excellent explanations of the input and output formats with concrete examples, making the code self-documenting and easy to understand.


87-142: Comprehensive test coverage for base64 decoding functionality

The test case thoroughly validates the flattening process, ensuring that base64 data is correctly decoded and all expected fields are present with the right values.


144-181: Good test for metadata field addition

This test properly verifies that the requestId and timestamp are correctly added to each record in the output.

Comment on lines +60 to +85
pub fn flatten_kinesis_logs(message: Message) -> Vec<Value> {
let mut vec_kinesis_json = Vec::new();

for record in message.records.iter() {
let bytes = STANDARD.decode(record.data.clone()).unwrap();
let json_string: String = String::from_utf8(bytes).unwrap();
let json: serde_json::Value = serde_json::from_str(&json_string).unwrap();
let mut kinesis_json: Map<String, Value> = match serde_json::from_value(json) {
Ok(value) => value,
Err(error) => panic!("Failed to deserialize JSON: {}", error),
};

kinesis_json.insert(
"requestId".to_owned(),
Value::String(message.request_id.clone()),
);
kinesis_json.insert(
"timestamp".to_owned(),
Value::String(message.timestamp.to_string()),
);

vec_kinesis_json.push(Value::Object(kinesis_json));
}

vec_kinesis_json
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling to avoid potential panics

The function uses multiple unwrap() calls which will cause the program to panic if errors occur. Consider using proper error handling with Result types instead.

-pub fn flatten_kinesis_logs(message: Message) -> Vec<Value> {
+pub fn flatten_kinesis_logs(message: Message) -> Result<Vec<Value>, Box<dyn std::error::Error>> {
     let mut vec_kinesis_json = Vec::new();
 
     for record in message.records.iter() {
-        let bytes = STANDARD.decode(record.data.clone()).unwrap();
-        let json_string: String = String::from_utf8(bytes).unwrap();
-        let json: serde_json::Value = serde_json::from_str(&json_string).unwrap();
-        let mut kinesis_json: Map<String, Value> = match serde_json::from_value(json) {
-            Ok(value) => value,
-            Err(error) => panic!("Failed to deserialize JSON: {}", error),
-        };
+        let bytes = STANDARD.decode(&record.data)?;
+        let json_string = String::from_utf8(bytes)?;
+        let json: serde_json::Value = serde_json::from_str(&json_string)?;
+        let mut kinesis_json: Map<String, Value> = serde_json::from_value(json)?;
 
         kinesis_json.insert(
             "requestId".to_owned(),
-            Value::String(message.request_id.clone()),
+            Value::String(message.request_id.to_owned()),
         );
         kinesis_json.insert(
             "timestamp".to_owned(),
             Value::String(message.timestamp.to_string()),
         );
 
         vec_kinesis_json.push(Value::Object(kinesis_json));
     }
 
-    vec_kinesis_json
+    Ok(vec_kinesis_json)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn flatten_kinesis_logs(message: Message) -> Vec<Value> {
let mut vec_kinesis_json = Vec::new();
for record in message.records.iter() {
let bytes = STANDARD.decode(record.data.clone()).unwrap();
let json_string: String = String::from_utf8(bytes).unwrap();
let json: serde_json::Value = serde_json::from_str(&json_string).unwrap();
let mut kinesis_json: Map<String, Value> = match serde_json::from_value(json) {
Ok(value) => value,
Err(error) => panic!("Failed to deserialize JSON: {}", error),
};
kinesis_json.insert(
"requestId".to_owned(),
Value::String(message.request_id.clone()),
);
kinesis_json.insert(
"timestamp".to_owned(),
Value::String(message.timestamp.to_string()),
);
vec_kinesis_json.push(Value::Object(kinesis_json));
}
vec_kinesis_json
}
pub fn flatten_kinesis_logs(message: Message) -> Result<Vec<Value>, Box<dyn std::error::Error>> {
let mut vec_kinesis_json = Vec::new();
for record in message.records.iter() {
let bytes = STANDARD.decode(&record.data)?;
let json_string = String::from_utf8(bytes)?;
let json: serde_json::Value = serde_json::from_str(&json_string)?;
let mut kinesis_json: Map<String, Value> = serde_json::from_value(json)?;
kinesis_json.insert(
"requestId".to_owned(),
Value::String(message.request_id.to_owned()),
);
kinesis_json.insert(
"timestamp".to_owned(),
Value::String(message.timestamp.to_string()),
);
vec_kinesis_json.push(Value::Object(kinesis_json));
}
Ok(vec_kinesis_json)
}

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.

1 participant