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

Update/kafka implementations #3753

Merged

Conversation

NicholasTurner23
Copy link
Contributor

@NicholasTurner23 NicholasTurner23 commented Oct 24, 2024

Description

This PR cleans up the kafka implementations by improving error handling.

Summary by CodeRabbit

  • New Features

    • Enhanced error handling in device retrieval process, ensuring smoother message processing from Kafka.
    • Simplified message consumption interface for improved clarity and usability.
  • Bug Fixes

    • Improved robustness of message handling, reducing the likelihood of interruptions during processing.
  • Documentation

    • Updated method signatures to reflect recent changes for better developer understanding.

Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request involve significant updates to the AirQoDataUtils and MessageBrokerUtils classes within the airqo_etl_utils module. Enhancements to the get_devices method focus on improving error handling and message processing from Kafka, including better JSON decoding and the introduction of an auto_commit parameter. In the MessageBrokerUtils, modifications include the addition of a timeout configuration for message production and the removal of the from_beginning parameter from the consume_from_topic method, streamlining its interface and functionality.

Changes

File Path Change Summary
src/workflows/airqo_etl_utils/airqo_utils.py - Updated get_devices method for improved error handling and JSON decoding.
- Introduced auto_commit parameter, replacing from_beginning in Kafka consumer config.
src/workflows/airqo_etl_utils/message_broker_utils.py - Added request.timeout.ms to producer_config in _send_message method.
- Removed from_beginning parameter from consume_from_topic method signature.

Possibly related PRs

Suggested reviewers

  • Baalmart
  • BenjaminSsempala
  • Psalmz777

🎉 In the realm of code where changes take flight,
Error handling shines, making things right.
Kafka messages flow, with a new guiding hand,
Robust and clear, like a well-crafted band.
So here’s to the updates, both clever and bright,
In the world of AirQo, we soar to new height! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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 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
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: 0

🧹 Outside diff range and nitpick comments (3)
src/workflows/airqo_etl_utils/message_broker_utils.py (2)

155-155: LGTM! Consider extracting timeout values to constants.

The addition of request.timeout.ms aligns well with existing timeout configurations and provides better resilience against network issues. However, consider extracting the timeout values (300000ms) to class-level constants for better maintainability.

 class MessageBrokerUtils:
+    DEFAULT_TIMEOUT_MS = 300000  # 5 minutes
     MAX_MESSAGE_SIZE = 1 * 1024 * 1024

Line range hint 266-267: Enhance error handling for consumer errors.

Consider improving error handling by adding more context and implementing retries for recoverable errors:

                 if msg.error():
-                    logger.exception(f"Consumer error: {msg.error()}")
+                    error_code = msg.error().code()
+                    if error_code in (KafkaError._PARTITION_EOF, KafkaError._TIMED_OUT):
+                        logger.warning(f"Recoverable consumer error: {msg.error()}")
+                        continue
+                    logger.exception(f"Fatal consumer error ({error_code}): {msg.error()}")
                     continue

         except Exception as e:
-            logger.exception(f"Error while consuming messages from topic {topic}: {e}")
+            logger.exception(
+                f"Unexpected error while consuming messages from topic {topic}. "
+                f"Group: {group_id}, Error: {str(e)}"
+            )

Don't forget to add the import:

from confluent_kafka import KafkaError

Also applies to: 271-272

src/workflows/airqo_etl_utils/airqo_utils.py (1)

1055-1060: Enhance error handling for message key and value processing.

The new implementation adds proper JSON decoding error handling, which is good. However, consider these improvements:

  1. The error handling could be more specific about which message failed
  2. The continue statement after the exception handler is redundant

Apply this diff to improve the error handling:

-                key = message.get("key", None)
-                try:
-                    value = json.loads(message.get("value", None))
-                except json.JSONDecodeError as e:
-                    logger.exception(f"Error decoding JSON: {e}")
-                    continue
+                key = message.get("key", None)
+                value = message.get("value", None)
+                try:
+                    value = json.loads(value) if value else None
+                except json.JSONDecodeError as e:
+                    logger.exception(f"Error decoding JSON for message with key {key}: {e}")
+                    continue
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f934d29 and 660381c.

📒 Files selected for processing (2)
  • src/workflows/airqo_etl_utils/airqo_utils.py (2 hunks)
  • src/workflows/airqo_etl_utils/message_broker_utils.py (1 hunks)
🔇 Additional comments (3)
src/workflows/airqo_etl_utils/message_broker_utils.py (1)

Line range hint 213-224: Verify impact of removing from_beginning parameter.

While simplifying the API is good, we should ensure all existing consumers are updated to use offset parameter if they previously relied on from_beginning.

Additionally, consider enhancing the docstring to better explain offset behavior:

         offset: Optional[int] = None,
         wait_time_sec: int = 30,
         streaming: bool = False,
     ) -> Any:
         """
         Consume messages from a Kafka topic and return them.
+
+        Note: To start consuming from the beginning of the topic, set both
+        auto_offset_reset='earliest' and offset=0. For normal consumption,
+        leave offset as None and use auto_offset_reset to control the initial position.

         Args:
             topic: The Kafka topic to consume from.
             group_id: The consumer group ID.
src/workflows/airqo_etl_utils/airqo_utils.py (2)

1043-1043: LGTM: Good addition of json module and Kafka configuration.

The explicit import of the json module and setting auto_commit=False are good practices:

  • JSON module allows for proper error handling during message decoding
  • Disabling auto-commit provides better control over message consumption

Also applies to: 1052-1052


Line range hint 1043-1089: Verify Kafka consumer group behavior.

The changes to the Kafka consumer configuration with auto_commit=False might affect message processing guarantees. We should verify that messages are properly processed and not reprocessed unnecessarily.

✅ Verification successful

Let me gather more information about the Kafka consumer configuration and message processing patterns.

This will help us understand the broader context of Kafka consumer configurations and error handling patterns in the codebase.


Kafka consumer configuration is properly implemented with explicit message handling

The implementation shows a well-structured approach to message processing:

  • The auto_commit=False setting is intentional and safe, as messages are processed within a try-catch block
  • Proper error handling is in place for both JSON decoding and Kafka exceptions
  • Messages with missing required fields are logged and skipped gracefully
  • The consumer configuration is consistently implemented across the codebase

The code maintains message processing guarantees through:

  • Explicit error handling for each message
  • Clear logging of skipped messages and processing errors
  • Proper duplicate handling via drop_duplicates on device identifiers
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential message reprocessing issues in the consumer group

# Test: Look for duplicate message processing patterns in logs
rg -A 5 "Skipping message with key:"

# Test: Check for any error patterns in message processing
rg -A 5 "Error decoding JSON"

Length of output: 1117


Script:

#!/bin/bash
# Check for Kafka consumer configuration patterns and message processing logic
# Look for auto_commit usage and message processing patterns
ast-grep --pattern 'consume_from_topic($$$)'

# Check for other instances of Kafka consumer configuration
rg -A 5 "auto_commit"

# Look for message processing and commit patterns
rg -A 5 "KafkaException"

Length of output: 3095

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