zilencer: Add get_remote_realm_guest_and_non_guest_count.

We add a 'get_remote_realm_guest_and_non_guest_count'
function that queries 'RemoteRealmAuditLog' to get
the guest and non_guest count for that remote_realm.

This function is used in 'RemoteRealmBillingSession'
to calculate the current count of billed licenses.
This commit is contained in:
Prakhar Pratyush
2023-12-06 18:56:07 +05:30
committed by Tim Abbott
parent bd99e37910
commit 40621478cb
2 changed files with 38 additions and 2 deletions

View File

@@ -62,6 +62,7 @@ from zilencer.models import (
RemoteRealmBillingUser,
RemoteZulipServer,
RemoteZulipServerAuditLog,
get_remote_realm_guest_and_non_guest_count,
get_remote_server_guest_and_non_guest_count,
)
from zproject.config import get_secret
@@ -2801,8 +2802,8 @@ class RemoteRealmBillingSession(BillingSession): # nocoverage
@override
def current_count_for_billed_licenses(self) -> int:
# TODO: Do the proper calculation here.
return 10
remote_realm_counts = get_remote_realm_guest_and_non_guest_count(self.remote_realm)
return remote_realm_counts.non_guest_user_count + remote_realm_counts.guest_user_count
@override
def get_audit_log_event(self, event_type: AuditLogEventType) -> int:

View File

@@ -395,3 +395,38 @@ def get_remote_server_guest_and_non_guest_count(
return RemoteCustomerUserCount(
non_guest_user_count=non_guest_count, guest_user_count=guest_count
)
def get_remote_realm_guest_and_non_guest_count(
remote_realm: RemoteRealm, event_time: datetime = timezone_now()
) -> RemoteCustomerUserCount: # nocoverage
latest_audit_log = (
RemoteRealmAuditLog.objects.filter(
remote_realm=remote_realm,
event_type__in=RemoteRealmAuditLog.SYNCED_BILLING_EVENTS,
event_time__lte=event_time,
)
# Important: extra_data is empty for some pre-2020 audit logs
# prior to the introduction of realm_user_count_by_role
# logging. Meanwhile, modern Zulip servers using
# bulk_create_users to create the users in the system bot
# realm also generate such audit logs. Such audit logs should
# never be the latest in a normal realm.
.exclude(extra_data={}).last()
)
guest_count = 0
non_guest_count = 0
if latest_audit_log is not None:
humans_count_dict = latest_audit_log.extra_data[RemoteRealmAuditLog.ROLE_COUNT][
RemoteRealmAuditLog.ROLE_COUNT_HUMANS
]
for role_type in UserProfile.ROLE_TYPES:
if role_type == UserProfile.ROLE_GUEST:
guest_count += humans_count_dict.get(str(role_type), 0)
else:
non_guest_count += humans_count_dict.get(str(role_type), 0)
return RemoteCustomerUserCount(
non_guest_user_count=non_guest_count, guest_user_count=guest_count
)