From d730f6b2bf655329df8f1cc3e318479c31baae43 Mon Sep 17 00:00:00 2001 From: Matias Bordese Date: Fri, 24 Nov 2023 09:02:32 -0300 Subject: [PATCH] Trigger distribute task after alert is committed (#3420) Fix issue triggering task retries because alert is not yet committed to the DB. Similar to https://github.com/grafana/oncall/pull/3001. --- engine/apps/alerts/models/alert.py | 4 +++- engine/apps/alerts/tests/test_alert.py | 30 +++++++++++++++++--------- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/engine/apps/alerts/models/alert.py b/engine/apps/alerts/models/alert.py index afb4a9e449..79f458dbaf 100644 --- a/engine/apps/alerts/models/alert.py +++ b/engine/apps/alerts/models/alert.py @@ -144,7 +144,9 @@ def create( if settings.DEBUG: tasks.distribute_alert(alert.pk) else: - tasks.distribute_alert.apply_async((alert.pk,), countdown=TASK_DELAY_SECONDS) + transaction.on_commit( + partial(tasks.distribute_alert.apply_async, (alert.pk,), countdown=TASK_DELAY_SECONDS) + ) if group_created: # all code below related to maintenance mode diff --git a/engine/apps/alerts/tests/test_alert.py b/engine/apps/alerts/tests/test_alert.py index 77926a4461..1e33abe4cf 100644 --- a/engine/apps/alerts/tests/test_alert.py +++ b/engine/apps/alerts/tests/test_alert.py @@ -7,22 +7,32 @@ @pytest.mark.django_db -def test_alert_create_default_channel_filter(make_organization, make_alert_receive_channel, make_channel_filter): +@patch("apps.alerts.tasks.distribute_alert.distribute_alert.apply_async", return_value=None) +def test_alert_create_default_channel_filter( + mocked_distribute_alert_task, + make_organization, + make_alert_receive_channel, + make_channel_filter, + django_capture_on_commit_callbacks, +): organization = make_organization() alert_receive_channel = make_alert_receive_channel(organization) channel_filter = make_channel_filter(alert_receive_channel, is_default=True) - alert = Alert.create( - title="the title", - message="the message", - alert_receive_channel=alert_receive_channel, - raw_request_data={}, - integration_unique_data={}, - image_url=None, - link_to_upstream_details=None, - ) + with django_capture_on_commit_callbacks(execute=True) as callbacks: + alert = Alert.create( + title="the title", + message="the message", + alert_receive_channel=alert_receive_channel, + raw_request_data={}, + integration_unique_data={}, + image_url=None, + link_to_upstream_details=None, + ) assert alert.group.channel_filter == channel_filter + assert len(callbacks) == 1 + mocked_distribute_alert_task.assert_called_once_with((alert.pk,), countdown=1) @pytest.mark.django_db