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

feat: keep.join function for workflows #2547

Merged
merged 4 commits into from
Nov 20, 2024
Merged

Conversation

talboren
Copy link
Member

@talboren talboren commented Nov 20, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a join function for concatenating various data types into a single string.
    • Enhanced URL generation in the IOHandler class using the new join function.
    • Improved validation of AWS CloudWatch log queries in the CloudwatchProvider class.
    • Added functionality for merging incidents and enhanced incident filtering options in incident management.
  • Bug Fixes

    • Enhanced error handling for JSON parsing and URL shortening processes.
    • Improved error handling and logging in incident and alert management functions.
  • Chores

    • Cleaned up code by removing commented-out sections and TODOs.
    • Updated project version and added new dependency in pyproject.toml.

@talboren talboren linked an issue Nov 20, 2024 that may be closed by this pull request
Copy link

vercel bot commented Nov 20, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
keep ⬜️ Ignored (Inspect) Visit Preview Nov 20, 2024 9:50am

@dosubot dosubot bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Nov 20, 2024
Copy link

coderabbitai bot commented Nov 20, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce new functionality across multiple modules. A new join function is added to the keep/functions/__init__.py module, which concatenates elements from various iterables into a string. The IOHandler class in keep/iohandler/iohandler.py is updated to simplify URL rendering using the new join function and enhance error handling. The CloudwatchProvider class in keep/providers/cloudwatch_provider/cloudwatch_provider.py sees improvements in AWS permission validation and error logging, enhancing its robustness in handling CloudWatch logs. Additionally, the incident management functions in keep/api/core/db.py are refined for better performance and error handling, and the project version is updated in pyproject.toml.

Changes

File Path Change Summary
keep/functions/init.py Added `join(iterable: list
keep/iohandler/iohandler.py Updated IOHandler class: modified event_context structure, simplified render method for URL construction using keep.join, and enhanced error handling in __get_short_urls. Cleaned up commented-out sections.
keep/providers/cloudwatch_provider/cloudwatch_provider.py Updated CloudwatchProvider class: added query and query_id variables, enhanced validate_scopes method for AWS permissions validation with improved logging.
keep/api/core/db.py Enhanced incident and alert management functions: added merge_incidents_to_id, improved create_incident_from_dto, modified add_alerts_to_incident and get_last_incidents for better error handling and performance.
pyproject.toml Updated project version from 0.29.1 to 0.29.2 and added dependency json5 = "^0.9.28".

Possibly related PRs

Suggested reviewers

  • shahargl

Poem

🐰 In the code where rabbits play,
New functions hop and join the fray.
With URLs that dance and twirl,
And permissions that unfurl.
A cleaner path, a joyful cheer,
Hooray for changes, let’s all hear! 🎉


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.

@dosubot dosubot bot added the Feature A new feature label Nov 20, 2024
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: 2

🧹 Outside diff range and nitpick comments (8)
keep/functions/__init__.py (2)

178-187: Add docstring to document function behavior and parameters.

The new join function lacks documentation. Add a docstring to explain its purpose, parameters, return value, and examples.

 def join(iterable: list | dict | str, delimiter: str = ",") -> str:
+    """Join elements of an iterable into a delimited string.
+
+    Args:
+        iterable: Input collection to join. Can be:
+            - list: Elements are converted to strings
+            - dict: Formatted as "key=value" pairs
+            - str: Parsed as JSON first
+        delimiter: String to join elements with (default: ",")
+
+    Returns:
+        str: Joined string representation
+
+    Examples:
+        >>> join(['a', 'b', 'c'])
+        'a,b,c'
+        >>> join({'key': 'value'})
+        'key=value'
+    """

185-186: Consider enhancing type handling for nested structures.

The current implementation might not handle nested dictionaries or lists properly. Consider adding recursive handling for nested structures.

     if isinstance(iterable, dict):
-        return delimiter.join([f"{k}={v}" for k, v in iterable.items()])
+        def format_value(v):
+            if isinstance(v, (dict, list)):
+                return json.dumps(v)
+            return str(v)
+        return delimiter.join([f"{k}={format_value(v)}" for k, v in iterable.items()])
     return delimiter.join([str(item) for item in iterable])
keep/iohandler/iohandler.py (2)

523-523: Add descriptive comments for the test data structure

While the new tags-based structure is good, consider adding comments explaining the expected format and usage of the tags in the event context, especially since this is test code.


525-525: Enhance test case with assertions and documentation

The test case could be improved in several ways:

  1. Add expected output documentation
  2. Include assertions to validate the result
  3. Consider removing the unnecessary asteval evaluation for this simple string concatenation test

Example improvement:

# Test keep.join function for URL parameter construction
expected = "https://www.keephq.dev?k1&k2"
result = iohandler.render('https://www.keephq.dev?keep.join("{{alert.tags}}", "&")')
assert result == expected, f"Expected {expected}, but got {result}"
keep/providers/cloudwatch_provider/cloudwatch_provider.py (4)

260-260: Initialize query to None instead of False for clarity

It is more idiomatic in Python to initialize variables to None when they are expected to hold a value or object that is not yet assigned. This improves code readability and avoids potential confusion with boolean values.

Apply this diff to update the initialization:

- query = False
+ query = None

282-282: Initialize query_id to None instead of False for clarity

Similarly, initializing query_id to None makes it clear that it has not been assigned a meaningful value yet.

Apply this diff to update the initialization:

- query_id = False
+ query_id = None

Line range hint 284-287: Fix incorrect assignment to scopes dictionary

Currently, the code assigns to scopes using a tuple as a key:

scopes["logs:GetQueryResults", "logs:DescribeQueries"] = "..."

This creates a single key that is a tuple, which is likely unintended and may lead to logical errors when accessing the scopes. Instead, assign to each key separately to accurately reflect the validation results.

Apply this diff to fix the issue:

- scopes["logs:GetQueryResults", "logs:DescribeQueries"] = (
+ scopes["logs:GetQueryResults"] = (
    "Could not validate logs:GetQueryResults scope without logs:DescribeQueries, so assuming the scope is not granted."
+ )
+ scopes["logs:DescribeQueries"] = (
+    "Could not validate logs:GetQueryResults scope without logs:DescribeQueries, so assuming the scope is not granted."
+ )

Line range hint 260-273: Clarify scope validation logic in exception handling

In the except block while handling exceptions from logs_client.start_query, the logic assumes that a ResourceNotFoundException indicates that the logs:StartQuery scope is not required:

if "ResourceNotFoundException" in str(e):
    self.logger.info("AWS logs:StartQuery scope is not required")
    scopes["logs:StartQuery"] = True

However, a ResourceNotFoundException typically means that the log group does not exist, but the permission logs:StartQuery is granted. Therefore, the scope logs:StartQuery should be marked as granted (True) in this case. The log message should reflect that the scope is granted rather than not required.

Consider updating the logic to correctly reflect the scope validation:

if "ResourceNotFoundException" in str(e):
-   self.logger.info("AWS logs:StartQuery scope is not required")
+   self.logger.info("AWS logs:StartQuery scope is granted")
    scopes["logs:StartQuery"] = True
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 838d1d7 and a1c2157.

📒 Files selected for processing (3)
  • keep/functions/__init__.py (1 hunks)
  • keep/iohandler/iohandler.py (1 hunks)
  • keep/providers/cloudwatch_provider/cloudwatch_provider.py (2 hunks)

keep/functions/__init__.py Outdated Show resolved Hide resolved
keep/functions/__init__.py Outdated Show resolved Hide resolved
@dosubot dosubot bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Nov 20, 2024
@talboren talboren enabled auto-merge (squash) November 20, 2024 09:50
Copy link
Member

@shahargl shahargl left a comment

Choose a reason for hiding this comment

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

lgtm

@talboren talboren merged commit b96bd67 into main Nov 20, 2024
9 of 11 checks passed
@talboren talboren deleted the 2546-feature-keepjoin-function branch November 20, 2024 09:52
@dosubot dosubot bot added the lgtm This PR has been approved by a maintainer label Nov 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Feature A new feature lgtm This PR has been approved by a maintainer size:M This PR changes 30-99 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[➕ Feature]: keep.join function
2 participants