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.

counts: Add new Add new mobile_pushes_sent::day LoggingCountStat.

Mateusz Mandera8a6d5b49973a
diff --git a/analytics/lib/counts.py b/analytics/lib/counts.py
index fcf39137f17..b2cb5d08095 100644
--- a/analytics/lib/counts.py
+++ b/analytics/lib/counts.py
@@ -829,6 +829,12 @@ def get_count_stats(realm: Optional[Realm] = None) -> Dict[str, CountStat]:
CountStat(
"minutes_active::day", DataCollector(UserCount, do_pull_minutes_active), CountStat.DAY
),
+ # Tracks the number of push notifications requested by the server.
+ LoggingCountStat(
+ "mobile_pushes_sent::day",
+ RealmCount,
+ CountStat.DAY,
+ ),
# Rate limiting stats
# Used to limit the number of invitation emails sent by a realm
LoggingCountStat("invites_sent::day", RealmCount, CountStat.DAY),
diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py
index 2443b60fd78..aaa40020b02 100644
--- a/zerver/lib/push_notifications.py
+++ b/zerver/lib/push_notifications.py
@@ -32,6 +32,7 @@ from django.utils.translation import gettext as _
from django.utils.translation import override as override_language
from typing_extensions import TypeAlias, override
+from analytics.lib.counts import COUNT_STATS, do_increment_logging_stat
from zerver.lib.avatar import absolute_avatar_url
from zerver.lib.emoji_utils import hex_codepoint_to_emoji
from zerver.lib.exceptions import ErrorCode, JsonableError
@@ -550,16 +551,16 @@ def uses_notification_bouncer() -> bool:
def send_notifications_to_bouncer(
- user_profile_id: int,
+ user_profile: UserProfile,
apns_payload: Dict[str, Any],
gcm_payload: Dict[str, Any],
gcm_options: Dict[str, Any],
) -> Tuple[int, int]:
post_data = {
- "user_uuid": str(get_user_profile_by_id(user_profile_id).uuid),
+ "user_uuid": str(user_profile.uuid),
# user_uuid is the intended future format, but we also need to send user_id
# to avoid breaking old mobile registrations, which were made with user_id.
- "user_id": user_profile_id,
+ "user_id": user_profile.id,
"apns_payload": apns_payload,
"gcm_payload": gcm_payload,
"gcm_options": gcm_options,
@@ -569,7 +570,19 @@ def send_notifications_to_bouncer(
assert isinstance(response_data["total_android_devices"], int)
assert isinstance(response_data["total_apple_devices"], int)
- return response_data["total_android_devices"], response_data["total_apple_devices"]
+ total_android_devices, total_apple_devices = (
+ response_data["total_android_devices"],
+ response_data["total_apple_devices"],
+ )
+ do_increment_logging_stat(
+ user_profile.realm,
+ COUNT_STATS["mobile_pushes_sent::day"],
+ None,
+ timezone_now(),
+ increment=total_android_devices + total_apple_devices,
+ )
+
+ return total_android_devices, total_apple_devices
#
@@ -1045,7 +1058,7 @@ def handle_remove_push_notification(user_profile_id: int, message_ids: List[int]
apns_payload = get_remove_payload_apns(user_profile, truncated_message_ids)
if uses_notification_bouncer():
- send_notifications_to_bouncer(user_profile_id, apns_payload, gcm_payload, gcm_options)
+ send_notifications_to_bouncer(user_profile, apns_payload, gcm_payload, gcm_options)
else:
user_identity = UserPushIdentityCompat(user_id=user_profile_id)
android_devices = list(
@@ -1054,10 +1067,21 @@ def handle_remove_push_notification(user_profile_id: int, message_ids: List[int]
apple_devices = list(
PushDeviceToken.objects.filter(user=user_profile, kind=PushDeviceToken.APNS)
)
- if android_devices:
- send_android_push_notification(user_identity, android_devices, gcm_payload, gcm_options)
- if apple_devices:
- send_apple_push_notification(user_identity, apple_devices, apns_payload)
+
+ android_successfully_sent_count = send_android_push_notification(
+ user_identity, android_devices, gcm_payload, gcm_options
+ )
+ apple_successfully_sent_count = send_apple_push_notification(
+ user_identity, apple_devices, apns_payload
+ )
+
+ do_increment_logging_stat(
+ user_profile.realm,
+ COUNT_STATS["mobile_pushes_sent::day"],
+ None,
+ timezone_now(),
+ increment=android_successfully_sent_count + apple_successfully_sent_count,
+ )
# We intentionally use the non-truncated message_ids here. We are
# assuming in this very rare case that the user has manually
@@ -1180,7 +1204,7 @@ def handle_push_notification(user_profile_id: int, missed_message: Dict[str, Any
if uses_notification_bouncer():
total_android_devices, total_apple_devices = send_notifications_to_bouncer(
- user_profile_id, apns_payload, gcm_payload, gcm_options
+ user_profile, apns_payload, gcm_payload, gcm_options
)
logger.info(
"Sent mobile push notifications for user %s through bouncer: %s via FCM devices, %s via APNs devices",
@@ -1205,8 +1229,21 @@ def handle_push_notification(user_profile_id: int, missed_message: Dict[str, Any
len(apple_devices),
)
user_identity = UserPushIdentityCompat(user_id=user_profile.id)
- send_apple_push_notification(user_identity, apple_devices, apns_payload)
- send_android_push_notification(user_identity, android_devices, gcm_payload, gcm_options)
+
+ apple_successfully_sent_count = send_apple_push_notification(
+ user_identity, apple_devices, apns_payload
+ )
+ android_successfully_sent_count = send_android_push_notification(
+ user_identity, android_devices, gcm_payload, gcm_options
+ )
+
+ do_increment_logging_stat(
+ user_profile.realm,
+ COUNT_STATS["mobile_pushes_sent::day"],
+ None,
+ timezone_now(),
+ increment=apple_successfully_sent_count + android_successfully_sent_count,
+ )
def send_test_push_notification_directly_to_devices(
diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py
index 3af9789142b..fcc2bb5e561 100644
--- a/zerver/tests/test_push_notifications.py
+++ b/zerver/tests/test_push_notifications.py
@@ -81,7 +81,6 @@ from zerver.models import (
get_client,
get_realm,
get_stream,
- get_user_profile_by_id,
)
from zilencer.models import RemoteZulipServerAuditLog
@@ -1631,6 +1630,16 @@ class HandlePushNotificationTest(PushNotificationTest):
pn_logger.output,
)
+ remote_realm_count = RealmCount.objects.values("property", "subgroup", "value").last()
+ self.assertEqual(
+ remote_realm_count,
+ dict(
+ property="mobile_pushes_sent::day",
+ subgroup=None,
+ value=len(gcm_devices) + len(apns_devices),
+ ),
+ )
+
@override_settings(PUSH_NOTIFICATION_BOUNCER_URL="https://push.zulip.org.example.com")
@responses.activate
def test_unregistered_client(self) -> None:
@@ -1749,9 +1758,9 @@ class HandlePushNotificationTest(PushNotificationTest):
# If the message is unread, we should send push notifications.
with mock.patch(
- "zerver.lib.push_notifications.send_apple_push_notification"
+ "zerver.lib.push_notifications.send_apple_push_notification", return_value=1
) as mock_send_apple, mock.patch(
- "zerver.lib.push_notifications.send_android_push_notification"
+ "zerver.lib.push_notifications.send_android_push_notification", return_value=1
) as mock_send_android:
handle_push_notification(user_profile.id, missed_message)
mock_send_apple.assert_called_once()
@@ -1761,9 +1770,9 @@ class HandlePushNotificationTest(PushNotificationTest):
usermessage.flags.read = True
usermessage.save()
with mock.patch(
- "zerver.lib.push_notifications.send_apple_push_notification"
+ "zerver.lib.push_notifications.send_apple_push_notification", return_value=1
) as mock_send_apple, mock.patch(
- "zerver.lib.push_notifications.send_android_push_notification"
+ "zerver.lib.push_notifications.send_android_push_notification", return_value=1
) as mock_send_android:
handle_push_notification(user_profile.id, missed_message)
mock_send_apple.assert_not_called()
@@ -1867,7 +1876,7 @@ class HandlePushNotificationTest(PushNotificationTest):
) as mock_logging_info:
handle_push_notification(user_profile.id, missed_message)
mock_send.assert_called_with(
- user_profile.id,
+ user_profile,
{"apns": True},
{"gcm": True},
{},
@@ -1911,9 +1920,13 @@ class HandlePushNotificationTest(PushNotificationTest):
"zerver.lib.push_notifications.get_message_payload_gcm",
return_value=({"gcm": True}, {}),
), mock.patch(
- "zerver.lib.push_notifications.send_apple_push_notification"
+ # Simulate the send...push_notification functions returning a number of successes
+ # lesser than the number of devices, so that we can verify correct CountStat counting.
+ "zerver.lib.push_notifications.send_apple_push_notification",
+ return_value=len(apple_devices) - 1,
) as mock_send_apple, mock.patch(
- "zerver.lib.push_notifications.send_android_push_notification"
+ "zerver.lib.push_notifications.send_android_push_notification",
+ return_value=len(android_devices) - 1,
) as mock_send_android, mock.patch(
"zerver.lib.push_notifications.push_notifications_enabled", return_value=True
) as mock_push_notifications:
@@ -1923,6 +1936,16 @@ class HandlePushNotificationTest(PushNotificationTest):
mock_send_android.assert_called_with(user_identity, android_devices, {"gcm": True}, {})
mock_push_notifications.assert_called_once()
+ remote_realm_count = RealmCount.objects.values("property", "subgroup", "value").last()
+ self.assertEqual(
+ remote_realm_count,
+ dict(
+ property="mobile_pushes_sent::day",
+ subgroup=None,
+ value=len(android_devices) + len(apple_devices) - 2,
+ ),
+ )
+
def test_send_remove_notifications_to_bouncer(self) -> None:
user_profile = self.example_user("hamlet")
message = self.get_message(
@@ -1941,7 +1964,7 @@ class HandlePushNotificationTest(PushNotificationTest):
) as mock_send:
handle_remove_push_notification(user_profile.id, [message.id])
mock_send.assert_called_with(
- user_profile.id,
+ user_profile,
{
"badge": 0,
"custom": {
@@ -1994,9 +2017,13 @@ class HandlePushNotificationTest(PushNotificationTest):
with mock.patch(
"zerver.lib.push_notifications.push_notifications_enabled", return_value=True
) as mock_push_notifications, mock.patch(
- "zerver.lib.push_notifications.send_android_push_notification"
+ # Simulate the send...push_notification functions returning a number of successes
+ # lesser than the number of devices, so that we can verify correct CountStat counting.
+ "zerver.lib.push_notifications.send_android_push_notification",
+ return_value=len(apple_devices) - 1,
) as mock_send_android, mock.patch(
- "zerver.lib.push_notifications.send_apple_push_notification"
+ "zerver.lib.push_notifications.send_apple_push_notification",
+ return_value=len(apple_devices) - 1,
) as mock_send_apple:
handle_remove_push_notification(self.user_profile.id, [message.id])
mock_push_notifications.assert_called_once()
@@ -2035,6 +2062,16 @@ class HandlePushNotificationTest(PushNotificationTest):
user_message = UserMessage.objects.get(user_profile=self.user_profile, message=message)
self.assertEqual(user_message.flags.active_mobile_push_notification, False)
+ remote_realm_count = RealmCount.objects.values("property", "subgroup", "value").last()
+ self.assertEqual(
+ remote_realm_count,
+ dict(
+ property="mobile_pushes_sent::day",
+ subgroup=None,
+ value=len(android_devices) + len(apple_devices) - 2,
+ ),
+ )
+
def test_user_message_does_not_exist(self) -> None:
"""This simulates a condition that should only be an error if the user is
not long-term idle; we fake it, though, in the sense that the user should
@@ -2069,9 +2106,9 @@ class HandlePushNotificationTest(PushNotificationTest):
with mock.patch(
"zerver.lib.push_notifications.push_notifications_enabled", return_value=True
) as mock_push_notifications, mock.patch(
- "zerver.lib.push_notifications.send_android_push_notification"
+ "zerver.lib.push_notifications.send_android_push_notification", return_value=1
) as mock_send_android, mock.patch(
- "zerver.lib.push_notifications.send_apple_push_notification"
+ "zerver.lib.push_notifications.send_apple_push_notification", return_value=1
) as mock_send_apple:
handle_remove_push_notification(self.user_profile.id, [message_id])
mock_push_notifications.assert_called_once()
@@ -2119,9 +2156,9 @@ class HandlePushNotificationTest(PushNotificationTest):
"zerver.lib.push_notifications.get_message_payload_gcm",
return_value=({"gcm": True}, {}),
), mock.patch(
- "zerver.lib.push_notifications.send_apple_push_notification"
+ "zerver.lib.push_notifications.send_apple_push_notification", return_value=1
) as mock_send_apple, mock.patch(
- "zerver.lib.push_notifications.send_android_push_notification"
+ "zerver.lib.push_notifications.send_android_push_notification", return_value=1
) as mock_send_android, mock.patch(
"zerver.lib.push_notifications.logger.error"
) as mock_logger, mock.patch(
@@ -2892,13 +2929,15 @@ class TestGetGCMPayload(PushNotificationTest):
class TestSendNotificationsToBouncer(ZulipTestCase):
@mock.patch("zerver.lib.remote_server.send_to_push_bouncer")
def test_send_notifications_to_bouncer(self, mock_send: mock.MagicMock) -> None:
+ user = self.example_user("hamlet")
+
mock_send.return_value = {"total_android_devices": 1, "total_apple_devices": 3}
total_android_devices, total_apple_devices = send_notifications_to_bouncer(
- 1, {"apns": True}, {"gcm": True}, {}
+ user, {"apns": True}, {"gcm": True}, {}
)
post_data = {
- "user_uuid": get_user_profile_by_id(1).uuid,
- "user_id": 1,
+ "user_uuid": user.uuid,
+ "user_id": user.id,
"apns_payload": {"apns": True},
"gcm_payload": {"gcm": True},
"gcm_options": {},
@@ -2912,6 +2951,16 @@ class TestSendNotificationsToBouncer(ZulipTestCase):
self.assertEqual(total_android_devices, 1)
self.assertEqual(total_apple_devices, 3)
+ remote_realm_count = RealmCount.objects.values("property", "subgroup", "value").last()
+ self.assertEqual(
+ remote_realm_count,
+ dict(
+ property="mobile_pushes_sent::day",
+ subgroup=None,
+ value=total_android_devices + total_apple_devices,
+ ),
+ )
+
@override_settings(PUSH_NOTIFICATION_BOUNCER_URL="https://push.zulip.org.example.com")
class TestSendToPushBouncer(ZulipTestCase):