Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

remote_server: Handle JsonableErrors and connection failures better.

Tim Abbott53f40133eb60
diff --git a/zerver/lib/remote_server.py b/zerver/lib/remote_server.py
index 4b82fa9a1be..1dc0fc6c3ca 100644
--- a/zerver/lib/remote_server.py
+++ b/zerver/lib/remote_server.py
@@ -168,11 +168,11 @@ def send_to_push_bouncer(
)
if res.status_code >= 500:
- # 500s should be resolved by the people who run the push
+ # 5xx's should be resolved by the people who run the push
# notification bouncer service, and they'll get an appropriate
# error notification from the server. We raise an exception to signal
# to the callers that the attempt failed and they can retry.
- error_msg = "Received 500 from push notification bouncer"
+ error_msg = f"Received {res.status_code} from push notification bouncer"
logging.warning(error_msg)
raise PushNotificationBouncerServerError(error_msg)
elif res.status_code >= 400:
@@ -239,6 +239,30 @@ def send_json_to_push_bouncer(
)
+def maybe_mark_pushes_disabled(
+ e: Union[JsonableError, orjson.JSONDecodeError], logger: logging.Logger
+) -> None:
+ if isinstance(e, PushNotificationBouncerServerError):
+ # We don't fall through and deactivate the flag, since this is
+ # not under the control of the caller.
+ return
+
+ if isinstance(e, JsonableError):
+ logger.warning(e.msg)
+ else:
+ logger.exception("Exception communicating with %s", settings.PUSH_NOTIFICATION_BOUNCER_URL)
+
+ # An exception was thrown talking to the push bouncer. There may
+ # be certain transient failures that we could ignore here, but the
+ # default explanation is that there is something wrong either with
+ # our credentials being corrupted or our ability to reach the
+ # bouncer service over the network, so we immediately move to
+ # reporting push notifications as likely not working.
+ for realm in Realm.objects.filter(push_notifications_enabled=True):
+ do_set_realm_property(realm, "push_notifications_enabled", False, acting_user=None)
+ do_set_push_notifications_enabled_end_timestamp(realm, None, acting_user=None)
+
+
def build_analytics_data(
realm_count_query: QuerySet[RealmCount],
installation_count_query: QuerySet[InstallationCount],
@@ -319,8 +343,8 @@ def send_server_data_to_push_bouncer(consider_usage_statistics: bool = True) ->
# first, check what's latest
try:
result = send_to_push_bouncer("GET", "server/analytics/status", {})
- except PushNotificationBouncerRetryLaterError as e:
- logger.warning(e.msg, exc_info=True)
+ except (JsonableError, orjson.JSONDecodeError) as e:
+ maybe_mark_pushes_disabled(e, logger)
return
# Gather only entries with IDs greater than the last ID received by the push bouncer.
@@ -364,29 +388,8 @@ def send_server_data_to_push_bouncer(consider_usage_statistics: bool = True) ->
response = send_to_push_bouncer(
"POST", "server/analytics", request.model_dump(round_trip=True)
)
- except PushNotificationBouncerServerError: # nocoverage
- # 50x errors from the bouncer cannot be addressed by the
- # administrator of this server, and may be localized to
- # this endpoint; don't rashly mark push notifications as
- # disabled when they are likely working perfectly fine.
- return
- except Exception as e:
- if isinstance(e, JsonableError):
- # Log exceptions with server error messages to the analytics log.
- logger.warning(e.msg)
-
- # An exception was thrown trying to ask the bouncer service whether we can send
- # push notifications or not. There may be certain transient failures that we could
- # ignore here, but the default explanation is that there is something wrong either
- # with our credentials being corrupted or our ability to reach the bouncer service
- # over the network, so we immediately move to reporting push notifications as likely not working,
- # as whatever failed here is likely to also fail when trying to send a push notification.
- for realm in Realm.objects.filter(push_notifications_enabled=True):
- do_set_realm_property(realm, "push_notifications_enabled", False, acting_user=None)
- do_set_push_notifications_enabled_end_timestamp(realm, None, acting_user=None)
- if not isinstance(e, JsonableError):
- # Log this generic error only if we haven't already logged specific error above.
- logger.exception("Exception asking push bouncer if notifications will work.")
+ except (JsonableError, orjson.JSONDecodeError) as e:
+ maybe_mark_pushes_disabled(e, logger)
return
assert isinstance(response["realms"], dict) # for mypy
diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py
index 55da83203fc..582d2891306 100644
--- a/zerver/tests/test_push_notifications.py
+++ b/zerver/tests/test_push_notifications.py
@@ -1026,28 +1026,115 @@ class PushBouncerNotificationTest(BouncerTestCase):
class AnalyticsBouncerTest(BouncerTestCase):
TIME_ZERO = datetime(1988, 3, 14, tzinfo=timezone.utc)
+ def assertPushNotificationsAre(self, should_be: bool) -> None:
+ self.assertEqual(
+ {should_be},
+ set(
+ Realm.objects.all().distinct().values_list("push_notifications_enabled", flat=True)
+ ),
+ )
+
@override_settings(PUSH_NOTIFICATION_BOUNCER_URL="https://push.zulip.org.example.com")
@responses.activate
- def test_analytics_api(self) -> None:
- """This is a variant of the below test_push_api, but using the full
- push notification bouncer flow
- """
+ def test_analytics_failure_api(self) -> None:
assert settings.PUSH_NOTIFICATION_BOUNCER_URL is not None
ANALYTICS_URL = settings.PUSH_NOTIFICATION_BOUNCER_URL + "/api/v1/remotes/server/analytics"
ANALYTICS_STATUS_URL = ANALYTICS_URL + "/status"
- user = self.example_user("hamlet")
- end_time = self.TIME_ZERO
with responses.RequestsMock() as resp, self.assertLogs(
"zulip.analytics", level="WARNING"
) as mock_warning:
resp.add(responses.GET, ANALYTICS_STATUS_URL, body=ConnectionError())
+ Realm.objects.all().update(push_notifications_enabled=True)
+ send_server_data_to_push_bouncer()
+ self.assertEqual(
+ "WARNING:zulip.analytics:ConnectionError while trying to connect to push notification bouncer",
+ mock_warning.output[0],
+ )
+ self.assertTrue(resp.assert_call_count(ANALYTICS_STATUS_URL, 1))
+ self.assertPushNotificationsAre(False)
+
+ with responses.RequestsMock() as resp, self.assertLogs(
+ "zulip.analytics", level="WARNING"
+ ) as mock_warning:
+ resp.add(responses.GET, ANALYTICS_STATUS_URL, body="This is not JSON")
+ Realm.objects.all().update(push_notifications_enabled=True)
+ send_server_data_to_push_bouncer()
+ self.assertTrue(
+ mock_warning.output[0].startswith(
+ f"ERROR:zulip.analytics:Exception communicating with {settings.PUSH_NOTIFICATION_BOUNCER_URL}\nTraceback",
+ )
+ )
+ self.assertTrue(resp.assert_call_count(ANALYTICS_STATUS_URL, 1))
+ self.assertPushNotificationsAre(False)
+
+ with responses.RequestsMock() as resp, self.assertLogs("", level="WARNING") as mock_warning:
+ resp.add(responses.GET, ANALYTICS_STATUS_URL, body="Server error", status=502)
+ Realm.objects.all().update(push_notifications_enabled=True)
+ send_server_data_to_push_bouncer()
+ self.assertEqual(
+ "WARNING:root:Received 502 from push notification bouncer",
+ mock_warning.output[0],
+ )
+ self.assertTrue(resp.assert_call_count(ANALYTICS_STATUS_URL, 1))
+ self.assertPushNotificationsAre(True)
+
+ with responses.RequestsMock() as resp, self.assertLogs(
+ "zulip.analytics", level="WARNING"
+ ) as mock_warning:
+ Realm.objects.all().update(push_notifications_enabled=True)
+ resp.add(
+ responses.GET,
+ ANALYTICS_STATUS_URL,
+ status=401,
+ json={"CODE": "UNAUTHORIZED", "msg": "Some problem", "result": "error"},
+ )
send_server_data_to_push_bouncer()
self.assertIn(
- "WARNING:zulip.analytics:ConnectionError while trying to connect to push notification bouncer\nTraceback ",
+ "WARNING:zulip.analytics:Some problem",
mock_warning.output[0],
)
self.assertTrue(resp.assert_call_count(ANALYTICS_STATUS_URL, 1))
+ self.assertPushNotificationsAre(False)
+
+ with responses.RequestsMock() as resp, self.assertLogs(
+ "zulip.analytics", level="WARNING"
+ ) as mock_warning:
+ Realm.objects.all().update(push_notifications_enabled=True)
+ resp.add(
+ responses.GET,
+ ANALYTICS_STATUS_URL,
+ json={
+ "last_realm_count_id": 0,
+ "last_installation_count_id": 0,
+ "last_realmauditlog_id": 0,
+ },
+ )
+ resp.add(
+ responses.POST,
+ ANALYTICS_URL,
+ status=401,
+ json={"CODE": "UNAUTHORIZED", "msg": "Some problem", "result": "error"},
+ )
+ send_server_data_to_push_bouncer()
+ self.assertIn(
+ "WARNING:zulip.analytics:Some problem",
+ mock_warning.output[0],
+ )
+ self.assertTrue(resp.assert_call_count(ANALYTICS_URL, 1))
+ self.assertPushNotificationsAre(False)
+
+ @override_settings(PUSH_NOTIFICATION_BOUNCER_URL="https://push.zulip.org.example.com")
+ @responses.activate
+ def test_analytics_api(self) -> None:
+ """This is a variant of the below test_push_api, but using the full
+ push notification bouncer flow
+ """
+ assert settings.PUSH_NOTIFICATION_BOUNCER_URL is not None
+ ANALYTICS_URL = settings.PUSH_NOTIFICATION_BOUNCER_URL + "/api/v1/remotes/server/analytics"
+ ANALYTICS_STATUS_URL = ANALYTICS_URL + "/status"
+ user = self.example_user("hamlet")
+ end_time = self.TIME_ZERO
self.add_mock_response()
# Send any existing data over, so that we can start the test with a "clean" slate
@@ -1854,7 +1941,7 @@ class AnalyticsBouncerTest(BouncerTestCase):
)
with mock.patch("zerver.lib.remote_server.send_to_push_bouncer") as m, self.assertLogs(
- "zulip.analytics", level="ERROR"
+ "zulip.analytics", level="WARNING"
) as exception_log:
get_response = {
"last_realm_count_id": 0,
@@ -1864,7 +1951,7 @@ class AnalyticsBouncerTest(BouncerTestCase):
def mock_send_to_push_bouncer_response(method: str, *args: Any) -> Dict[str, int]:
if method == "POST":
- raise Exception
+ raise PushNotificationBouncerRetryLaterError("Some problem")
return get_response
m.side_effect = mock_send_to_push_bouncer_response
@@ -1874,10 +1961,10 @@ class AnalyticsBouncerTest(BouncerTestCase):
realms = Realm.objects.all()
for realm in realms:
self.assertFalse(realm.push_notifications_enabled)
- self.assertIn(
- "ERROR:zulip.analytics:Exception asking push bouncer if notifications will work.",
- exception_log.output[0],
- )
+ self.assertEqual(
+ exception_log.output,
+ ["WARNING:zulip.analytics:Some problem"],
+ )
send_server_data_to_push_bouncer(consider_usage_statistics=False)