From 2909d632954f226a04691c119f998591ff032420 Mon Sep 17 00:00:00 2001 From: Andrey Zelenchuk Date: Thu, 9 Nov 2023 02:43:52 +0200 Subject: [PATCH] Introduce initial payload. --- channels_graphql_ws/graphql_ws_consumer.py | 6 ++++++ channels_graphql_ws/subscription.py | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/channels_graphql_ws/graphql_ws_consumer.py b/channels_graphql_ws/graphql_ws_consumer.py index 9af6c83..2d7e32b 100644 --- a/channels_graphql_ws/graphql_ws_consumer.py +++ b/channels_graphql_ws/graphql_ws_consumer.py @@ -176,6 +176,8 @@ async def on_operation(self, op_id, payload): # ------------------------------------------------------------------- IMPLEMENTATION + SKIP = object() + # A prefix of Channel groups with subscription notifications. group_name_prefix: str = "GQLWS" @@ -914,6 +916,10 @@ async def _on_gql_start__initialize_subscription_stream( # `notification_queue_lock` as a guard while reading or writing # to the queue. notification_queue: asyncio.Queue = asyncio.Queue(maxsize=queue_size) + # Enqueue the initial payload. + initial_payload = subscription_class.initial_payload + if initial_payload is not self.SKIP: + notification_queue.put_nowait(Serializer.serialize(initial_payload)) # Lock to ensure that `notification_queue` operations are # thread safe. notification_queue_lock = threading.RLock() diff --git a/channels_graphql_ws/subscription.py b/channels_graphql_ws/subscription.py index 62f03d9..169a7d2 100644 --- a/channels_graphql_ws/subscription.py +++ b/channels_graphql_ws/subscription.py @@ -162,6 +162,11 @@ class Subscription(graphene.ObjectType): # Useful to skip intermediate notifications, e.g. progress reports. notification_queue_limit: Optional[int] = None + # Initial payload. Set it to send an "initial" response with this + # payload to a client as soon as it is subscribed (before any call + # to `Subscription.broadcast`). + initial_payload = GraphqlWsConsumer.SKIP + @classmethod def broadcast(cls, *, group=None, payload=None): """Call this method to notify all subscriptions in the group.