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

Max retry exports #391

Merged
merged 7 commits into from
Sep 3, 2024
Merged

Max retry exports #391

merged 7 commits into from
Sep 3, 2024

Conversation

Ashutosh619-sudo
Copy link
Contributor

No description provided.

Copy link

coderabbitai bot commented Aug 26, 2024

Walkthrough

The changes introduce enhancements to the export functionality and error handling within a financial application. The export_to_xero function now accepts an interval_hours parameter for refined export scheduling based on workspace settings. Additionally, a new error validation function has been added in the queue.py file, along with updates to the scheduling functions. The test suite has been expanded to cover these modifications, ensuring robust error management.

Changes

Files Change Summary
apps/workspaces/actions.py Modified export_to_xero to include interval_hours parameter for improved export control.
apps/xero/queue.py Introduced validate_failing_export function; updated schedule_bills_creation and schedule_bank_transaction_creation to include interval_hours. Enhanced error handling and logging.
tests/test_xero/test_tasks.py Added tests for skipping scheduling on errors; updated existing tests to include interval_hours handling.

Sequence Diagram(s)

sequenceDiagram
    participant Workspace
    participant Export
    participant Queue
    participant ErrorHandler

    Workspace->>Export: Request Export with interval_hours
    Export->>Queue: Schedule Bills Creation
    Queue->>Queue: Validate Failing Export
    Queue-->>ErrorHandler: Check for Errors
    alt No Errors
        Queue-->>Export: Complete Export
    else Errors Detected
        Queue-->>ErrorHandler: Log Error and Skip Export
    end
Loading

🐰 In the land of code where the rabbits hop,
New changes emerged, making exports pop!
With hours defined, the schedule's so neat,
Errors now managed, no more defeat.
Hooray for the updates, let’s dance and play,
For a smoother workflow, hip-hip-hooray! 🎉


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 178d999 and 8d72a07.

Files selected for processing (3)
  • apps/workspaces/actions.py (2 hunks)
  • apps/xero/queue.py (6 hunks)
  • tests/test_xero/test_tasks.py (4 hunks)
Additional comments not posted (11)
apps/workspaces/actions.py (2)

208-209: LGTM!

The changes enhance the function by allowing more granular control over the export process.

The code changes are approved.


225-226: LGTM!

The changes enhance the function by allowing more granular control over the export process.

The code changes are approved.

apps/xero/queue.py (5)

20-28: LGTM!

The function enhances the control flow by allowing the system to conditionally skip exporting expense groups that have encountered too many errors within a specified timeframe.

The code changes are approved.


123-123: LGTM!

The changes enhance the error handling and export scheduling logic, making the system more robust in managing failed exports.

The code changes are approved.


140-150: LGTM!

The changes enhance the error handling and export scheduling logic, making the system more robust in managing failed exports.

The code changes are approved.


199-199: LGTM!

The changes enhance the error handling and export scheduling logic, making the system more robust in managing failed exports.

The code changes are approved.


217-229: LGTM!

The changes enhance the error handling and export scheduling logic, making the system more robust in managing failed exports.

The code changes are approved.

tests/test_xero/test_tasks.py (4)

419-419: LGTM!

The changes ensure that the test covers the new parameter interval_hours.

The code changes are approved.


517-517: LGTM!

The changes ensure that the test covers the new parameter interval_hours.

The code changes are approved.


1024-1064: LGTM!

The new test enhances the testing coverage by ensuring that the scheduling function behaves as expected in scenarios where errors are encountered.

The code changes are approved.


1067-1107: LGTM!

The new test enhances the testing coverage by ensuring that the scheduling function behaves as expected in scenarios where errors are encountered.

The code changes are approved.

Copy link

Tests Skipped Failures Errors Time
162 0 💤 0 ❌ 0 🔥 1m 10s ⏱️

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, codebase verification and nitpick comments (10)
apps/xero/queue.py (6)

21-29: Improve docstring clarity and simplify condition.

The docstring can be improved for clarity. Additionally, the condition can be simplified for readability.

Apply this diff to improve the docstring and simplify the condition:

 def validate_failing_export(is_auto_export: bool, interval_hours: int, error: Error):
     """
     Validate if an export should be skipped based on conditions.
     :param is_auto_export: Indicates if auto export is enabled.
     :param interval_hours: The interval in hours for export scheduling.
     :param error: The error object containing error details.
     :return: True if the export should be skipped, False otherwise.
     """
-    return is_auto_export and interval_hours and error and error.repetition_count > 100 and datetime.now().replace(tzinfo=timezone.utc) - error.updated_at <= timedelta(hours=24)
+    return (
+        is_auto_export
+        and interval_hours
+        and error
+        and error.repetition_count > 100
+        and datetime.now(timezone.utc) - error.updated_at <= timedelta(hours=24)
+    )

Line range hint 124-128: Update docstring to include new parameter.

The docstring is missing the new interval_hours parameter.

Apply this diff to update the docstring:

 def schedule_bills_creation(workspace_id: int, expense_group_ids: List[str], is_auto_export: bool, fund_source: str, interval_hours: int) -> list:
     """
     Schedule bills creation
     :param expense_group_ids: List of expense group ids
     :param workspace_id: workspace id
+    :param is_auto_export: Indicates if auto export is enabled.
+    :param fund_source: The source of funds.
+    :param interval_hours: The interval in hours for export scheduling.
     :return: List of chaining attributes
     """

150-150: Improve logging message for more details.

The logging message can include more details about the error.

Apply this diff to improve the logging message:

 logger.info('Skipping expense group %s as it has %s errors', expense_group.id, error.repetition_count)
+ logger.info('Skipping expense group %s due to error: %s (repetition count: %s)', expense_group.id, error.error_detail, error.repetition_count)

Line range hint 200-204: Update docstring to include new parameter.

The docstring is missing the new interval_hours parameter.

Apply this diff to update the docstring:

 def schedule_bank_transaction_creation(
     workspace_id: int, expense_group_ids: List[str], is_auto_export: bool, fund_source: str, interval_hours: int
 ) -> list:
     """
     Schedule bank transaction creation
     :param expense_group_ids: List of expense group ids
     :param workspace_id: workspace id
+    :param is_auto_export: Indicates if auto export is enabled.
+    :param fund_source: The source of funds.
+    :param interval_hours: The interval in hours for export scheduling.
     :return: List of chaining attributes
     """

229-229: Improve logging message for more details.

The logging message can include more details about the error.

Apply this diff to improve the logging message:

 logger.info('Skipping expense group %s as it has %s errors', expense_group.id, error.repetition_count)
+ logger.info('Skipping expense group %s due to error: %s (repetition count: %s)', expense_group.id, error.error_detail, error.repetition_count)

218-218: Replace print statements with proper logging.

The print statements should be replaced with proper logging for consistency and better debugging.

Apply this diff to replace print statements with proper logging:

- print(len(expense_groups))
+ logger.debug('Number of expense groups: %d', len(expense_groups))

- print('task_log', task_log.__dict__)
+ logger.debug('Task log details: %s', task_log.__dict__)

- print('task_log', task_log.__dict__)
+ logger.debug('Task log details: %s', task_log.__dict__)

Also applies to: 237-237, 243-243

tests/test_xero/test_tasks.py (4)

1024-1024: Add docstring to the test function.

The test function is missing a docstring.

Apply this diff to add a docstring:

 def test_skipping_schedule_bills_creation(db):
+    """
+    Test the behavior of schedule_bills_creation function when encountering errors.
+    :param db: Database fixture.
+    :return: None
+    """

1054-1055: Add more assertions to validate the behavior.

The test can include more assertions to validate the behavior.

Apply this diff to add more assertions:

 task_log = TaskLog.objects.filter(expense_group_id=expense_group.id).first()
 assert task_log.type == 'FETCHING_EXPENSES'
+ assert task_log.status == 'READY'

 task_log = TaskLog.objects.filter(expense_group_id=expense_group.id).first()
 assert task_log.type == 'CREATING_BILL'
+ assert task_log.status == 'ENQUEUED'

Also applies to: 1063-1064


1067-1067: Add docstring to the test function.

The test function is missing a docstring.

Apply this diff to add a docstring:

 def test_skipping_schedule_bank_transaction_creation(db):
+    """
+    Test the behavior of schedule_bank_transaction_creation function when encountering errors.
+    :param db: Database fixture.
+    :return: None
+    """

1097-1098: Add more assertions to validate the behavior.

The test can include more assertions to validate the behavior.

Apply this diff to add more assertions:

 task_log = TaskLog.objects.filter(expense_group_id=expense_group.id).first()
 assert task_log.type == 'FETCHING_EXPENSES'
+ assert task_log.status == 'READY'

 task_log = TaskLog.objects.filter(expense_group_id=expense_group.id).first()
 assert task_log.type == 'CREATING_BANK_TRANSACTION'
+ assert task_log.status == 'ENQUEUED'

Also applies to: 1106-1107

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8d72a07 and 2b1408f.

Files selected for processing (2)
  • apps/xero/queue.py (6 hunks)
  • tests/test_xero/test_tasks.py (4 hunks)

Comment on lines +226 to +228
error = errors.filter(workspace_id=workspace_id, expense_group=expense_group, is_resolved=False).first()
skip_export = validate_failing_export(is_auto_export, interval_hours, error)
if skip_export:
Copy link

Choose a reason for hiding this comment

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

Handle potential exceptions in validate_failing_export function call.

The validate_failing_export function call should handle potential exceptions to avoid breaking the loop.

Apply this diff to handle potential exceptions:

 error = errors.filter(workspace_id=workspace_id, expense_group=expense_group, is_resolved=False).first()
- skip_export = validate_failing_export(is_auto_export, interval_hours, error)
+ try:
+     skip_export = validate_failing_export(is_auto_export, interval_hours, error)
+ except Exception as e:
+     logger.error('Error validating export for expense group %s: %s', expense_group.id, str(e))
+     skip_export = False
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
error = errors.filter(workspace_id=workspace_id, expense_group=expense_group, is_resolved=False).first()
skip_export = validate_failing_export(is_auto_export, interval_hours, error)
if skip_export:
error = errors.filter(workspace_id=workspace_id, expense_group=expense_group, is_resolved=False).first()
try:
skip_export = validate_failing_export(is_auto_export, interval_hours, error)
except Exception as e:
logger.error('Error validating export for expense group %s: %s', expense_group.id, str(e))
skip_export = False
if skip_export:

Comment on lines +147 to +149
error = errors.filter(workspace_id=workspace_id, expense_group=expense_group, is_resolved=False).first()
skip_export = validate_failing_export(is_auto_export, interval_hours, error)
if skip_export:
Copy link

Choose a reason for hiding this comment

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

Handle potential exceptions in validate_failing_export function call.

The validate_failing_export function call should handle potential exceptions to avoid breaking the loop.

Apply this diff to handle potential exceptions:

 error = errors.filter(workspace_id=workspace_id, expense_group=expense_group, is_resolved=False).first()
- skip_export = validate_failing_export(is_auto_export, interval_hours, error)
+ try:
+     skip_export = validate_failing_export(is_auto_export, interval_hours, error)
+ except Exception as e:
+     logger.error('Error validating export for expense group %s: %s', expense_group.id, str(e))
+     skip_export = False
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
error = errors.filter(workspace_id=workspace_id, expense_group=expense_group, is_resolved=False).first()
skip_export = validate_failing_export(is_auto_export, interval_hours, error)
if skip_export:
error = errors.filter(workspace_id=workspace_id, expense_group=expense_group, is_resolved=False).first()
try:
skip_export = validate_failing_export(is_auto_export, interval_hours, error)
except Exception as e:
logger.error('Error validating export for expense group %s: %s', expense_group.id, str(e))
skip_export = False
if skip_export:

@Ashutosh619-sudo Ashutosh619-sudo added the deploy Triggers deployment of active branch to Staging label Aug 27, 2024
@Ashutosh619-sudo Ashutosh619-sudo added deploy Triggers deployment of active branch to Staging and removed deploy Triggers deployment of active branch to Staging labels Aug 28, 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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2b1408f and add2573.

Files selected for processing (1)
  • apps/xero/queue.py (6 hunks)
Files skipped from review as they are similar to previous changes (1)
  • apps/xero/queue.py

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between add2573 and 99ec268.

Files selected for processing (1)
  • apps/workspaces/actions.py (3 hunks)
Files skipped from review as they are similar to previous changes (1)
  • apps/workspaces/actions.py

@Ashutosh619-sudo Ashutosh619-sudo added deploy Triggers deployment of active branch to Staging and removed deploy Triggers deployment of active branch to Staging labels Aug 28, 2024
Copy link

Tests Skipped Failures Errors Time
162 0 💤 0 ❌ 0 🔥 1m 10s ⏱️

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 99ec268 and cc2493f.

Files selected for processing (1)
  • apps/xero/queue.py (6 hunks)
Files skipped from review as they are similar to previous changes (1)
  • apps/xero/queue.py

Copy link

Tests Skipped Failures Errors Time
162 0 💤 0 ❌ 0 🔥 1m 9s ⏱️

task_log, _ = TaskLog.objects.get_or_create(
workspace_id=expense_group.workspace_id,
expense_group=expense_group,
defaults={"status": TaskLogStatusEnum.ENQUEUED, "type": TaskLogTypeEnum.CREATING_BILL},
)
if task_log.status not in [TaskLogStatusEnum.IN_PROGRESS, TaskLogStatusEnum.ENQUEUED]:
task_log.type = TaskLogTypeEnum.CREATING_BILL
Copy link
Contributor

Choose a reason for hiding this comment

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

this is not needed no

task_log, _ = TaskLog.objects.get_or_create(
workspace_id=expense_group.workspace_id,
expense_group=expense_group,
defaults={"status": TaskLogStatusEnum.ENQUEUED, "type": TaskLogTypeEnum.CREATING_BANK_TRANSACTION},
)
if task_log.status not in [TaskLogStatusEnum.IN_PROGRESS, TaskLogStatusEnum.ENQUEUED]:
task_log.type = TaskLogTypeEnum.CREATING_BANK_TRANSACTION
Copy link
Contributor

Choose a reason for hiding this comment

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

same

@Ashutosh619-sudo Ashutosh619-sudo merged commit 2582aa0 into master Sep 3, 2024
1 check passed
Ashutosh619-sudo added a commit that referenced this pull request Sep 3, 2024
* Max retry export with test cases

* added interval hours

* fixed flake

* change log level

* cahnge log level

* flake resolved

* remove loggers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deploy Triggers deployment of active branch to Staging
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants