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.

push_notifs: Make push_notifications_enabled more resistant to flapping.

Mateusz Mandera962ab13203a7
diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py
index c65df45af01..738914e1c65 100644
--- a/zerver/lib/push_notifications.py
+++ b/zerver/lib/push_notifications.py
@@ -45,6 +45,7 @@ from zerver.lib.exceptions import ErrorCode, JsonableError
from zerver.lib.message import access_message_and_usermessage, huddle_users
from zerver.lib.outgoing_http import OutgoingSession
from zerver.lib.remote_server import (
+ record_push_notifications_recently_working,
send_json_to_push_bouncer,
send_server_data_to_push_bouncer,
send_to_push_bouncer,
@@ -662,15 +663,18 @@ def send_notifications_to_bouncer(
# The server may have updated our understanding of whether
# push notifications will work.
assert isinstance(remote_realm_dict, dict)
+ can_push = remote_realm_dict["can_push"]
do_set_realm_property(
user_profile.realm,
"push_notifications_enabled",
- remote_realm_dict["can_push"],
+ can_push,
acting_user=None,
)
do_set_push_notifications_enabled_end_timestamp(
user_profile.realm, remote_realm_dict["expected_end_timestamp"], acting_user=None
)
+ if can_push:
+ record_push_notifications_recently_working()
logger.info(
"Sent mobile push notifications for user %s through bouncer: %s via FCM devices, %s via APNs devices",
diff --git a/zerver/lib/remote_server.py b/zerver/lib/remote_server.py
index 27cb0d7f025..9fd10697c7e 100644
--- a/zerver/lib/remote_server.py
+++ b/zerver/lib/remote_server.py
@@ -6,6 +6,7 @@ import orjson
import requests
from django.conf import settings
from django.db.models import QuerySet
+from django.utils.timezone import now as timezone_now
from django.utils.translation import gettext as _
from pydantic import UUID4, BaseModel, ConfigDict, Field, Json, field_validator
@@ -16,6 +17,7 @@ from zerver.actions.realm_settings import (
do_set_push_notifications_enabled_end_timestamp,
do_set_realm_property,
)
+from zerver.lib import redis_utils
from zerver.lib.exceptions import (
JsonableError,
MissingRemoteRealmError,
@@ -23,9 +25,12 @@ from zerver.lib.exceptions import (
)
from zerver.lib.outgoing_http import OutgoingSession
from zerver.lib.queue import queue_event_on_commit
+from zerver.lib.redis_utils import get_redis_client
from zerver.models import Realm, RealmAuditLog
from zerver.models.realms import OrgTypeEnum
+redis_client = get_redis_client()
+
class PushBouncerSession(OutgoingSession):
def __init__(self, timeout: int = 15) -> None:
@@ -245,6 +250,29 @@ def send_json_to_push_bouncer(
)
+PUSH_NOTIFICATIONS_RECENTLY_WORKING_REDIS_KEY = "push_notifications_recently_working_ts"
+
+
+def record_push_notifications_recently_working() -> None:
+ # Record the timestamp in redis, marking that push notifications
+ # were working as of this moment.
+
+ redis_key = redis_utils.REDIS_KEY_PREFIX + PUSH_NOTIFICATIONS_RECENTLY_WORKING_REDIS_KEY
+ # Keep this record around for 24h in case it's useful for debugging.
+ redis_client.set(redis_key, str(timezone_now().timestamp()), ex=60 * 60 * 24)
+
+
+def check_push_notifications_recently_working() -> bool:
+ # Check in redis whether push notifications were working in the last hour.
+ redis_key = redis_utils.REDIS_KEY_PREFIX + PUSH_NOTIFICATIONS_RECENTLY_WORKING_REDIS_KEY
+ timestamp = redis_client.get(redis_key)
+ if timestamp is None:
+ return False
+
+ # If the timestamp is within the last hour, we consider push notifications to be working.
+ return timezone_now().timestamp() - float(timestamp) < 60 * 60
+
+
def maybe_mark_pushes_disabled(
e: Union[JsonableError, orjson.JSONDecodeError], logger: logging.Logger
) -> None:
@@ -259,11 +287,18 @@ def maybe_mark_pushes_disabled(
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
+ # be certain transient failures that we could ignore here -
+ # therefore we check whether push notifications were recently working
+ # and if so, the error can be treated as transient.
+ # Otherwise, the assumed 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 move to
# reporting push notifications as likely not working.
+ if check_push_notifications_recently_working():
+ # Push notifications were recently observed working, so we
+ # assume this is likely a transient failure.
+ return
+
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)
diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py
index 52d98a4735e..1d306677565 100644
--- a/zerver/tests/test_push_notifications.py
+++ b/zerver/tests/test_push_notifications.py
@@ -39,6 +39,7 @@ from zerver.actions.realm_settings import (
from zerver.actions.user_groups import check_add_user_group
from zerver.actions.user_settings import do_change_user_setting, do_regenerate_api_key
from zerver.actions.user_topics import do_set_user_topic_visibility_policy
+from zerver.lib import redis_utils
from zerver.lib.avatar import absolute_avatar_url, get_avatar_for_inaccessible_user
from zerver.lib.exceptions import JsonableError
from zerver.lib.push_notifications import (
@@ -64,12 +65,15 @@ from zerver.lib.push_notifications import (
send_notifications_to_bouncer,
)
from zerver.lib.remote_server import (
+ PUSH_NOTIFICATIONS_RECENTLY_WORKING_REDIS_KEY,
AnalyticsRequest,
PushNotificationBouncerError,
PushNotificationBouncerRetryLaterError,
PushNotificationBouncerServerError,
build_analytics_data,
get_realms_info_for_push_bouncer,
+ record_push_notifications_recently_working,
+ redis_client,
send_server_data_to_push_bouncer,
send_to_push_bouncer,
)
@@ -1334,6 +1338,12 @@ class AnalyticsBouncerTest(BouncerTestCase):
),
)
+ @override
+ def setUp(self) -> None:
+ redis_client.delete(PUSH_NOTIFICATIONS_RECENTLY_WORKING_REDIS_KEY)
+
+ return super().setUp()
+
@override_settings(PUSH_NOTIFICATION_BOUNCER_URL="https://push.zulip.org.example.com")
@responses.activate
def test_analytics_failure_api(self) -> None:
@@ -1354,6 +1364,40 @@ class AnalyticsBouncerTest(BouncerTestCase):
self.assertTrue(resp.assert_call_count(ANALYTICS_STATUS_URL, 1))
self.assertPushNotificationsAre(False)
+ # Simulate ConnectionError again, but this time with a redis record indicating
+ # that push notifications have recently worked fine.
+ 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)
+ record_push_notifications_recently_working()
+
+ 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))
+ # push_notifications_enabled shouldn't get set to False, because this is treated
+ # as a transient error.
+ self.assertPushNotificationsAre(True)
+
+ # However after an hour has passed without seeing push notifications
+ # working, we take the error seriously.
+ with time_machine.travel(now() + timedelta(minutes=61), tick=False):
+ send_server_data_to_push_bouncer()
+ self.assertEqual(
+ "WARNING:zulip.analytics:ConnectionError while trying to connect to push notification bouncer",
+ mock_warning.output[1],
+ )
+ self.assertTrue(resp.assert_call_count(ANALYTICS_STATUS_URL, 2))
+ self.assertPushNotificationsAre(False)
+
+ redis_client.delete(
+ redis_utils.REDIS_KEY_PREFIX + PUSH_NOTIFICATIONS_RECENTLY_WORKING_REDIS_KEY
+ )
+
with responses.RequestsMock() as resp, self.assertLogs(
"zulip.analytics", level="WARNING"
) as mock_warning: