-
Notifications
You must be signed in to change notification settings - Fork 26
Adding retry process for dead letter queue #924
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
Merged
Merged
Changes from all commits
Commits
Show all changes
42 commits
Select commit
Hold shift + click to select a range
91cfb29
Add pytest-asyncio
grahamalama d330898
Add dead letter queue
grahamalama b0c8d48
Update secrets.baseline
grahamalama a7dd23d
Add heartbeat check for queue availability
grahamalama 02f5d03
Fix invalid_dl_queue_dsn_raises
grahamalama df1bd04
Ensure module and methods are properly documented
grahamalama fa05508
Log size of queue after insertion at debug level
grahamalama 4350974
Add test for failing file backend ping
grahamalama 40c2040
Add some logging to the queue and backends
grahamalama 9bd9c96
Fix logging for bugs with no entries in memory get_all
grahamalama 6a01d5a
Fix typo in `get_all` docstring
grahamalama 4b89323
Add debug messages for writing bug to file queue
grahamalama f1eb44c
Remove memory backend
grahamalama 75048e5
Preserve queue directory in clear()
grahamalama f6b8bd9
Refactor size
grahamalama 4467db8
Use size for `is_blocked`
grahamalama 635f42f
Refactor get(), get_all(), retrieve()
grahamalama 6d14b9c
Add some missing typing
grahamalama b2bba8e
Merge remote-tracking branch 'origin/main' into dlq-class
grahamalama d39c7b6
payload.event.time isn't a callable
grahamalama 6236719
Remote retries property from QueueItemFactory
grahamalama 576f9fe
Adding retry process
alexcottner 7312dde
ran lint
alexcottner 158cecf
removed unused var
alexcottner 11fc655
adding some metrics and error handling for async iteration errors
alexcottner 2f814d4
a little cleanup
alexcottner d6610f3
Add tests for errors for invalid json and a webhook payload that does…
grahamalama c62e86c
Make a queue item timestamp an alias of the event timestamp
grahamalama 63057fc
Add methods for listing items in the queue
grahamalama 43a7a15
Catch and reraise custom exception for failing to read item into memory
grahamalama 96222d1
Colocate custom exceptions
grahamalama 9bac2d5
Merge branch 'dlq-class' of github.com:mozilla/jira-bugzilla-integrat…
alexcottner 33397cd
Cleaning up a lot of loose ends. Changes for PR feedback.
alexcottner 99111e9
Fixed env var names
alexcottner 1ee3ab7
Add methods to access list and list_all from queue class
grahamalama 70a4909
fix comment in jbi/retry
alexcottner 8843d34
Merge branch 'dlq-class' of github.com:mozilla/jira-bugzilla-integrat…
alexcottner 5b76cc8
Some light refactoring and cleanup, responding to all PR feedback so …
alexcottner 536f6b6
merging main
alexcottner 4a365bc
updating .secrets.baseline again
alexcottner 23500d1
fixing one test to use the fixture
alexcottner e5f8e32
fixing lint
alexcottner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import asyncio | ||
| import logging | ||
| from datetime import UTC, datetime, timedelta | ||
| from os import getenv | ||
| from time import sleep | ||
|
|
||
| import jbi.runner as runner | ||
| from jbi.configuration import ACTIONS | ||
| from jbi.queue import get_dl_queue | ||
|
|
||
| CONSTANT_RETRY = getenv("DL_QUEUE_CONSTANT_RETRY", "false") == "true" | ||
| RETRY_TIMEOUT_DAYS = getenv("DL_QUEUE_RETRY_TIMEOUT_DAYS", 7) | ||
| CONSTANT_RETRY_SLEEP = getenv("DL_QUEUE_CONSTANT_RETRY_SLEEP", 5) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| async def retry_failed(item_executor=runner.execute_action, queue=get_dl_queue()): | ||
| min_event_timestamp = datetime.now(UTC) - timedelta(days=int(RETRY_TIMEOUT_DAYS)) | ||
|
|
||
| # load all bugs from DLQ | ||
| bugs = await queue.retrieve() | ||
|
|
||
| # metrics to track | ||
| metrics = { | ||
| "bug_count": len(bugs), | ||
| "events_processed": 0, | ||
| "events_skipped": 0, | ||
| "events_failed": 0, | ||
| "bugs_failed": 0, | ||
| } | ||
|
|
||
| for bug_id, items in bugs.items(): | ||
| try: | ||
| async for item in items: | ||
| # skip and delete item if we have exceeded RETRY_TIMEOUT_DAYS | ||
| if item.timestamp < min_event_timestamp: | ||
| logger.warning("removing expired event %s", item.identifier) | ||
| await queue.done(item) | ||
| metrics["events_skipped"] += 1 | ||
| continue | ||
|
|
||
| try: | ||
| item_executor(item.payload, ACTIONS) | ||
| await queue.done(item) | ||
| metrics["events_processed"] += 1 | ||
| except Exception: | ||
| logger.exception("failed to reprocess event %s.", item.identifier) | ||
| metrics["events_failed"] += 1 | ||
|
|
||
| # check for other events that will be skipped | ||
| pending_events = await queue.size(bug_id) | ||
| if pending_events > 1: # if this isn't the only event for the bug | ||
| logger.info( | ||
| "skipping %d event(s) for bug %d, previous event %s failed", | ||
| pending_events - 1, | ||
| bug_id, | ||
| item.identifier, | ||
| ) | ||
| metrics["events_skipped"] += pending_events - 1 | ||
| break | ||
| except Exception: | ||
| logger.exception("failed to parse events for bug %d.", bug_id) | ||
| metrics["bugs_failed"] += 1 | ||
|
|
||
| return metrics | ||
|
|
||
|
|
||
| async def main(): | ||
| while True: | ||
| metrics = await retry_failed() | ||
| logger.info("event queue processing complete", extra=metrics) | ||
| if not CONSTANT_RETRY: | ||
| return | ||
| sleep(int(CONSTANT_RETRY_SLEEP)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| from datetime import UTC, datetime, timedelta | ||
| from unittest.mock import MagicMock | ||
|
|
||
| import pytest | ||
|
|
||
| from jbi.queue import DeadLetterQueue | ||
| from jbi.retry import RETRY_TIMEOUT_DAYS, retry_failed | ||
| from jbi.runner import execute_action | ||
|
|
||
|
|
||
| def iter_error(): | ||
| mock = MagicMock() | ||
| mock.__aiter__.return_value = None | ||
| mock.__aiter__.side_effect = Exception("Throwing an exception") | ||
| return mock | ||
|
|
||
|
|
||
| async def aiter_sync(iterable): | ||
| for i in iterable: | ||
| yield i | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_queue(): | ||
| return MagicMock(spec=DeadLetterQueue) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_executor(): | ||
| return MagicMock(spec=execute_action) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_retry_empty_list(caplog, mock_queue): | ||
| mock_queue.retrieve.return_value = {} | ||
|
|
||
| metrics = await retry_failed(queue=mock_queue) | ||
| mock_queue.retrieve.assert_called_once() | ||
| assert len(caplog.messages) == 0 | ||
| assert metrics == { | ||
| "bug_count": 0, | ||
| "events_processed": 0, | ||
| "events_skipped": 0, | ||
| "events_failed": 0, | ||
| "bugs_failed": 0, | ||
| } | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_retry_success(caplog, mock_queue, mock_executor, queue_item_factory): | ||
| mock_queue.retrieve.return_value = { | ||
| 1: aiter_sync([queue_item_factory(payload__bug__id=1)]) | ||
| } | ||
|
|
||
| metrics = await retry_failed(item_executor=mock_executor, queue=mock_queue) | ||
| assert len(caplog.messages) == 0 # no logs should have been generated | ||
| mock_queue.retrieve.assert_called_once() | ||
| mock_queue.done.assert_called_once() # item should be marked as complete | ||
| mock_executor.assert_called_once() # item should have been processed | ||
| assert metrics == { | ||
| "bug_count": 1, | ||
| "events_processed": 1, | ||
| "events_skipped": 0, | ||
| "events_failed": 0, | ||
| "bugs_failed": 0, | ||
| } | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_retry_fail_and_skip( | ||
| caplog, mock_queue, mock_executor, queue_item_factory | ||
| ): | ||
| mock_queue.retrieve.return_value = { | ||
| 1: aiter_sync( | ||
| [ | ||
| queue_item_factory(payload__bug__id=1), | ||
| queue_item_factory(payload__bug__id=1), | ||
| ] | ||
| ) | ||
| } | ||
|
|
||
| mock_executor.side_effect = Exception("Throwing an exception") | ||
| mock_queue.size.return_value = 3 | ||
|
|
||
| metrics = await retry_failed(item_executor=mock_executor, queue=mock_queue) | ||
| mock_queue.retrieve.assert_called_once() | ||
| mock_queue.done.assert_not_called() # no items should have been marked as done | ||
| assert caplog.text.count("failed to reprocess event") == 1 | ||
| assert caplog.text.count("skipping 2 event(s)") == 1 | ||
| assert caplog.text.count("removing expired event") == 0 | ||
| mock_executor.assert_called_once() # only one item should have been attempted to be processed | ||
| assert metrics == { | ||
| "bug_count": 1, | ||
| "events_processed": 0, | ||
| "events_skipped": 2, | ||
| "events_failed": 1, | ||
| "bugs_failed": 0, | ||
| } | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_retry_remove_expired( | ||
| caplog, mock_queue, mock_executor, queue_item_factory | ||
| ): | ||
| mock_queue.retrieve.return_value = { | ||
| 1: aiter_sync( | ||
| [ | ||
| queue_item_factory( | ||
| payload__bug__id=1, | ||
| payload__event__time=datetime.now(UTC) | ||
| - timedelta(days=int(RETRY_TIMEOUT_DAYS), seconds=1), | ||
| ), | ||
| queue_item_factory(payload__bug__id=1), | ||
| ] | ||
| ) | ||
| } | ||
|
|
||
| metrics = await retry_failed(item_executor=mock_executor, queue=mock_queue) | ||
| mock_queue.retrieve.assert_called_once() | ||
| assert ( | ||
| len(mock_queue.done.call_args_list) == 2 | ||
| ), "both items should have been marked as done" | ||
| assert caplog.text.count("failed to reprocess event") == 0 | ||
| assert caplog.text.count("skipping events") == 0 | ||
| assert caplog.text.count("removing expired event") == 1 | ||
| mock_executor.assert_called_once() # only one item should have been attempted to be processed | ||
| assert metrics == { | ||
| "bug_count": 1, | ||
| "events_processed": 1, | ||
| "events_skipped": 1, | ||
| "events_failed": 0, | ||
| "bugs_failed": 0, | ||
| } | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_retry_bug_failed(caplog, mock_queue, mock_executor, queue_item_factory): | ||
| mock_queue.retrieve.return_value = { | ||
| 1: aiter_sync([queue_item_factory(payload__bug__id=1)]), | ||
| 2: iter_error(), | ||
| } | ||
|
|
||
| metrics = await retry_failed(item_executor=mock_executor, queue=mock_queue) | ||
| mock_queue.retrieve.assert_called_once() | ||
| mock_queue.done.assert_called_once() # one item should have been marked as done | ||
| assert caplog.text.count("failed to reprocess event") == 0 | ||
| assert caplog.text.count("skipping events") == 0 | ||
| assert caplog.text.count("removing expired event") == 0 | ||
| assert caplog.text.count("failed to parse events for bug") == 1 | ||
| mock_executor.assert_called_once() # only one item should have been attempted to be processed | ||
| assert metrics == { | ||
| "bug_count": 2, | ||
| "events_processed": 1, | ||
| "events_skipped": 0, | ||
| "events_failed": 0, | ||
| "bugs_failed": 1, | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we need another method for this?
discard()or something with better semantics thandone()? Especially if in the queue we log stuff likeitem X is doneThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The queue should be just an IO operator and not have any real logic in it. It feels a little weird to have two different functions that do the same functional operation but with potentially different debug logs. Am I thinking about it wrong?
Looking at the logs the queue emits, we don't currently have a conflict problem. The debug level logs say things like "Removed {event} from queue for bug {bug_id}." and "Removed directory for bug {bug_id}". And our log levels will be above debug in prod and we won't alert on those.