django_api: Extract send_event_on_commit helper.

django-stubs 4.2.1 gives transaction.on_commit a more accurate type
annotation, but this exposed that mypy can’t handle the lambda default
parameters that we use to recapture loop variables such as

    for stream_id in public_stream_ids:
        peer_user_ids = …
        event = …

        transaction.on_commit(
            lambda event=event, peer_user_ids=peer_user_ids: send_event(
                realm, event, peer_user_ids
            )
        )

https://github.com/python/mypy/issues/15459

A workaround that mypy accepts is

        transaction.on_commit(
            (
                lambda event, peer_user_ids: lambda: send_event(
                    realm, event, peer_user_ids
                )
            )(event, peer_user_ids)
        )

But that’s kind of ugly and potentially error-prone, so let’s make a
helper function for this very common pattern.

        send_event_on_commit(realm, event, peer_user_ids)

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg
2023-06-17 11:53:07 -07:00
committed by Tim Abbott
parent 77c146b8b0
commit 7657cb4a0f
22 changed files with 114 additions and 180 deletions

View File

@@ -1,6 +1,5 @@
from typing import Any, Dict, Optional
from django.db import transaction
from django.utils.translation import gettext as _
from zerver.actions.create_user import create_historical_user_messages
@@ -9,7 +8,7 @@ from zerver.lib.exceptions import JsonableError
from zerver.lib.message import access_message, update_to_dict_cache
from zerver.lib.stream_subscription import subscriber_ids_with_stream_history_access
from zerver.models import Message, Reaction, Recipient, Stream, UserMessage, UserProfile
from zerver.tornado.django_api import send_event
from zerver.tornado.django_api import send_event_on_commit
def notify_reaction_update(
@@ -60,7 +59,7 @@ def notify_reaction_update(
stream = Stream.objects.get(id=stream_id)
user_ids |= subscriber_ids_with_stream_history_access(stream)
transaction.on_commit(lambda: send_event(user_profile.realm, event, list(user_ids)))
send_event_on_commit(user_profile.realm, event, list(user_ids))
def do_add_reaction(