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

Make ComparisonProxy sync #730

Merged
merged 1 commit into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions helpers/notifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from dataclasses import dataclass
from enum import Enum

from asgiref.sync import async_to_sync
from shared.torngit.base import TorngitBaseAdapter
from shared.torngit.exceptions import TorngitClientError

Expand Down Expand Up @@ -29,33 +30,33 @@ class BaseNotifier:
_pull: EnrichedPull | None = None
_repo_service: TorngitBaseAdapter | None = None

async def get_pull(self):
def get_pull(self):
repo_service = self.get_repo_service()

if self._pull is None:
self._pull = await fetch_and_update_pull_request_information_from_commit(
repo_service, self.commit, self.commit_yaml
)
self._pull = async_to_sync(
fetch_and_update_pull_request_information_from_commit
)(repo_service, self.commit, self.commit_yaml)

return self._pull

def get_repo_service(self):
def get_repo_service(self) -> TorngitBaseAdapter:
if self._repo_service is None:
self._repo_service = get_repo_provider_service(self.commit.repository)

return self._repo_service

async def send_to_provider(self, pull, message):
def send_to_provider(self, pull, message):
repo_service = self.get_repo_service()
assert repo_service

pullid = pull.database_pull.pullid
try:
comment_id = pull.database_pull.commentid
if comment_id:
await repo_service.edit_comment(pullid, comment_id, message)
async_to_sync(repo_service.edit_comment)(pullid, comment_id, message)
else:
res = await repo_service.post_comment(pullid, message)
res = async_to_sync(repo_service.post_comment)(pullid, message)
pull.database_pull.commentid = res["id"]
return True
except TorngitClientError:
Expand All @@ -71,10 +72,10 @@ async def send_to_provider(self, pull, message):
def build_message(self) -> str:
raise NotImplementedError

async def notify(
def notify(
self,
) -> NotifierResult:
pull = await self.get_pull()
pull = self.get_pull()
if pull is None:
log.info(
"Not notifying since there is no pull request associated with this commit",
Expand All @@ -86,7 +87,7 @@ async def notify(

message = self.build_message()

sent_to_provider = await self.send_to_provider(pull, message)
sent_to_provider = self.send_to_provider(pull, message)
if sent_to_provider == False:
return NotifierResult.TORNGIT_ERROR

Expand Down
14 changes: 3 additions & 11 deletions services/bundle_analysis/notify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from typing import NamedTuple

import sentry_sdk
from asgiref.sync import async_to_sync
from shared.yaml import UserYaml

from database.models.core import GITHUB_APP_INSTALLATION_DEFAULT_NAME, Commit, Owner
Expand All @@ -17,20 +16,15 @@
from services.bundle_analysis.notify.contexts.commit_status import (
CommitStatusNotificationContextBuilder,
)
from services.bundle_analysis.notify.helpers import (
get_notification_types_configured,
)
from services.bundle_analysis.notify.helpers import get_notification_types_configured
from services.bundle_analysis.notify.messages import MessageStrategyInterface
from services.bundle_analysis.notify.messages.comment import (
BundleAnalysisCommentMarkdownStrategy,
)
from services.bundle_analysis.notify.messages.commit_status import (
CommitStatusMessageStrategy,
)
from services.bundle_analysis.notify.types import (
NotificationSuccess,
NotificationType,
)
from services.bundle_analysis.notify.types import NotificationSuccess, NotificationType

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -190,9 +184,7 @@ def notify(self) -> BundleAnalysisNotifyReturn:
notifications_successful = []
for notification_context, message_strategy in notification_full_contexts:
message = message_strategy.build_message(notification_context)
result = async_to_sync(message_strategy.send_message)(
notification_context, message
)
result = message_strategy.send_message(notification_context, message)
if result.notification_attempted:
notifications_sent.append(notification_context.notification_type)
if result.notification_successful:
Expand Down
2 changes: 1 addition & 1 deletion services/bundle_analysis/notify/messages/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def build_message(
pass

@abstractmethod
async def send_message(
def send_message(
self, context: BaseBundleAnalysisNotificationContext, message: str | bytes
) -> NotificationResult:
pass
16 changes: 9 additions & 7 deletions services/bundle_analysis/notify/messages/comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@
from typing import Literal, TypedDict

import sentry_sdk
from asgiref.sync import async_to_sync
from django.template import loader
from shared.bundle_analysis import (
BundleAnalysisComparison,
BundleChange,
)
from shared.bundle_analysis import BundleAnalysisComparison, BundleChange
from shared.torngit.exceptions import TorngitClientError
from shared.validation.types import BundleThreshold

Expand Down Expand Up @@ -104,17 +102,21 @@ def build_upgrade_message(
return template.render(context)

@sentry_sdk.trace
async def send_message(
def send_message(
self, context: BundleAnalysisPRCommentNotificationContext, message: str
) -> NotificationResult:
pull = context.pull.database_pull
repository_service = context.repository_service
try:
comment_id = pull.bundle_analysis_commentid
if comment_id:
await repository_service.edit_comment(pull.pullid, comment_id, message)
async_to_sync(repository_service.edit_comment)(
pull.pullid, comment_id, message
)
else:
res = await repository_service.post_comment(pull.pullid, message)
res = async_to_sync(repository_service.post_comment)(
pull.pullid, message
)
pull.bundle_analysis_commentid = res["id"]
return NotificationResult(
notification_attempted=True,
Expand Down
20 changes: 9 additions & 11 deletions services/bundle_analysis/notify/messages/commit_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import TypedDict

import sentry_sdk
from asgiref.sync import async_to_sync
from django.template import loader
from shared.helpers.cache import make_hash_sha256
from shared.torngit.exceptions import TorngitClientError
Expand All @@ -11,10 +12,7 @@
CommitStatusLevel,
CommitStatusNotificationContext,
)
from services.bundle_analysis.notify.helpers import (
bytes_readable,
get_github_app_used,
)
from services.bundle_analysis.notify.helpers import bytes_readable, get_github_app_used
from services.bundle_analysis.notify.messages import MessageStrategyInterface
from services.notification.notifiers.base import NotificationResult

Expand Down Expand Up @@ -89,7 +87,7 @@ def _cache_key(self, context: CommitStatusNotificationContext) -> str:
)

@sentry_sdk.trace
async def send_message(
def send_message(
self, context: CommitStatusNotificationContext, message: str | bytes
) -> NotificationResult:
repository_service = context.repository_service
Expand All @@ -102,12 +100,12 @@ async def send_message(
explanation="payload_unchanged",
)
try:
await repository_service.set_commit_status(
commit=context.commit.commitid,
status=context.commit_status_level.to_str(),
context="codecov/bundles",
description=message,
url=context.commit_status_url,
async_to_sync(repository_service.set_commit_status)(
context.commit.commitid,
context.commit_status_level.to_str(),
"codecov/bundles",
message,
context.commit_status_url,
)
# Update the recently-sent messages cache
cache.get_backend().set(
Expand Down
24 changes: 11 additions & 13 deletions services/bundle_analysis/notify/messages/tests/test_comment.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from textwrap import dedent
from unittest.mock import AsyncMock, MagicMock
from unittest.mock import MagicMock

import pytest
from mock import AsyncMock
from shared.torngit.exceptions import TorngitClientError
from shared.typings.torngit import TorngitInstanceData
from shared.validation.types import BundleThreshold
Expand Down Expand Up @@ -76,9 +77,11 @@ def test_build_message_from_samples(self, dbsession, mocker, mock_storage):
def _setup_send_message_tests(
self, dbsession, mocker, torngit_ghapp_data, bundle_analysis_commentid
):
fake_repo_provider = AsyncMock(
fake_repo_provider = MagicMock(
name="fake_repo_provider",
data=TorngitInstanceData(installation=torngit_ghapp_data),
post_comment=AsyncMock(),
edit_comment=AsyncMock(),
)
fake_repo_provider.post_comment.return_value = {"id": 1000}
fake_repo_provider.edit_comment.return_value = {"id": 1000}
Expand Down Expand Up @@ -125,8 +128,7 @@ def _setup_send_message_tests(
),
],
)
@pytest.mark.asyncio
async def test_send_message_no_exising_comment(
def test_send_message_no_exising_comment(
self, dbsession, mocker, torngit_ghapp_data
):
fake_repo_provider, mock_pull, context, message = (
Expand All @@ -135,7 +137,7 @@ async def test_send_message_no_exising_comment(
)
)
strategy = BundleAnalysisCommentMarkdownStrategy()
result = await strategy.send_message(context, message)
result = strategy.send_message(context, message)
expected_app = torngit_ghapp_data.get("id") if torngit_ghapp_data else None
assert result == NotificationResult(
notification_attempted=True,
Expand All @@ -161,15 +163,12 @@ async def test_send_message_no_exising_comment(
),
],
)
@pytest.mark.asyncio
async def test_send_message_exising_comment(
self, dbsession, mocker, torngit_ghapp_data
):
def test_send_message_exising_comment(self, dbsession, mocker, torngit_ghapp_data):
fake_repo_provider, _, context, message = self._setup_send_message_tests(
dbsession, mocker, torngit_ghapp_data, bundle_analysis_commentid=1000
)
strategy = BundleAnalysisCommentMarkdownStrategy()
result = await strategy.send_message(context, message)
result = strategy.send_message(context, message)
expected_app = torngit_ghapp_data.get("id") if torngit_ghapp_data else None
assert result == NotificationResult(
notification_attempted=True,
Expand All @@ -179,8 +178,7 @@ async def test_send_message_exising_comment(
fake_repo_provider.edit_comment.assert_called_with(12, 1000, message)
fake_repo_provider.post_comment.assert_not_called()

@pytest.mark.asyncio
async def test_send_message_fail(self, dbsession, mocker):
def test_send_message_fail(self, dbsession, mocker):
fake_repo_provider, _, context, message = self._setup_send_message_tests(
dbsession, mocker, None, bundle_analysis_commentid=None
)
Expand All @@ -189,7 +187,7 @@ async def test_send_message_fail(self, dbsession, mocker):
name="fake_commit_report", external_id="some_UUID4"
)
strategy = BundleAnalysisCommentMarkdownStrategy()
result = await strategy.send_message(context, message)
result = strategy.send_message(context, message)
assert result == NotificationResult(
notification_attempted=True,
notification_successful=False,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from unittest.mock import AsyncMock, MagicMock
from unittest.mock import MagicMock

import pytest
from asgiref.sync import async_to_sync
from mock import AsyncMock
from shared.torngit.exceptions import TorngitClientError
from shared.typings.torngit import TorngitInstanceData
from shared.yaml import UserYaml
Expand Down Expand Up @@ -153,9 +153,10 @@ def test_build_message_from_samples(
def _setup_send_message_tests(
self, dbsession, mocker, torngit_ghapp_data, mock_storage
):
fake_repo_provider = AsyncMock(
fake_repo_provider = MagicMock(
name="fake_repo_provider",
data=TorngitInstanceData(installation=torngit_ghapp_data),
set_commit_status=AsyncMock(),
)
fake_repo_provider.set_commit_status.return_value = {"id": 1000}
mocker.patch(
Expand Down Expand Up @@ -222,13 +223,13 @@ def test_send_message_success(
dbsession, mocker, torngit_ghapp_data, mock_storage
)
strategy = CommitStatusMessageStrategy()
result = async_to_sync(strategy.send_message)(context, message)
result = strategy.send_message(context, message)
fake_repo_provider.set_commit_status.assert_called_with(
commit=context.commit.commitid,
status="success",
context="codecov/bundles",
description=message,
url=context.commit_status_url,
context.commit.commitid,
"success",
"codecov/bundles",
message,
context.commit_status_url,
)
expected_app = torngit_ghapp_data.get("id") if torngit_ghapp_data else None
assert result == NotificationResult(
Expand All @@ -245,7 +246,7 @@ def test_send_message_fail(self, dbsession, mocker, mock_storage):
)
fake_repo_provider.set_commit_status.side_effect = TorngitClientError()
strategy = CommitStatusMessageStrategy()
result = async_to_sync(strategy.send_message)(context, message)
result = strategy.send_message(context, message)
assert result == NotificationResult(
notification_attempted=True,
notification_successful=False,
Expand All @@ -258,17 +259,15 @@ def test_skip_payload_unchanged(self, dbsession, mocker, mock_storage, mock_cach
)
strategy = CommitStatusMessageStrategy()
mock_cache.get_backend().set(strategy._cache_key(context), 600, message)
result = async_to_sync(strategy.send_message)(context, message)
result = strategy.send_message(context, message)
fake_repo_provider.set_commit_status.assert_not_called()
assert result == NotificationResult(
notification_attempted=False,
notification_successful=False,
explanation="payload_unchanged",
)
# Side effect of sending message is updating the cache
assert async_to_sync(strategy.send_message)(
context, message
) == NotificationResult(
assert strategy.send_message(context, message) == NotificationResult(
notification_attempted=False,
notification_successful=False,
explanation="payload_unchanged",
Expand Down
6 changes: 3 additions & 3 deletions services/bundle_analysis/notify/tests/test_notify_service.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from unittest.mock import AsyncMock, MagicMock
from unittest.mock import MagicMock

import pytest
from shared.yaml import UserYaml
Expand Down Expand Up @@ -39,7 +39,7 @@ def override_comment_builder_and_message_strategy(mocker):
"services.bundle_analysis.notify.BundleAnalysisPRCommentContextBuilder",
return_value=mock_comment_builder,
)
mock_markdown_strategy = AsyncMock(name="fake_markdown_strategy")
mock_markdown_strategy = MagicMock(name="fake_markdown_strategy")
mock_markdown_strategy = mocker.patch(
"services.bundle_analysis.notify.BundleAnalysisCommentMarkdownStrategy",
return_value=mock_markdown_strategy,
Expand Down Expand Up @@ -67,7 +67,7 @@ def override_commit_status_builder_and_message_strategy(mocker):
"services.bundle_analysis.notify.CommitStatusNotificationContextBuilder",
return_value=mock_commit_status_builder,
)
commit_status_message_strategy = AsyncMock(name="fake_markdown_strategy")
commit_status_message_strategy = MagicMock(name="fake_markdown_strategy")
commit_status_message_strategy = mocker.patch(
"services.bundle_analysis.notify.CommitStatusMessageStrategy",
return_value=commit_status_message_strategy,
Expand Down
Loading
Loading