Sending messages to groups using group_send()
suddenly stops working after some time. The handler method of the consumer is not called anymore.
Restarting daphne
is fixing the issue for some time.
Details
There is no error showing up anywhere in the logs, just the messages are not getting handled by the consumers anymore.
I'm, using the following libraries:
- aioredis==1.2.0
- asgiref==2.3.2
- channels-redis==2.3.2
- channels==2.1.6
- daphne==2.2.4
- django==2.1.5
- redis==3.0.1
Code
# settings.py
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {"hosts": [("localhost", "6379")]},
}
}
# views.py
class ReceiveEventView(APIView):
def post(self, request, *args, **kwargs):
# payload: {"type": "event_triggered", "group": "warning", "message": "Button pressed"}
# or
# payload: {"type": "event_triggered", "group": "danger", "message": "Red Button pressed"}
payload = json.loads(request.POST.get("payload", "{}"))
if (payload.get("type") == "event_triggered"):
async_to_sync(channel_layer.group_send)(payload.get("group"), payload)
return HttpResponse(status=204)
# consumers.py
class EventConsumer(WebsocketConsumer):
def connect(self):
if not self.scope["user"].is_authenticated:
return
self.accept()
for group in get_subscriptions(self.scope["user"]):
async_to_sync(self.channel_layer.group_add)(group, self.channel_name)
def disconnect(self, close_code):
if not self.scope["user"].is_authenticated:
return
for group in get_subscriptions(self.scope["user"]):
async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)
def event_triggered(self, event):
logger.debug("Consumer::event_triggered()")
self.send(text_data=json.dumps(event))
expected and actual results
For some time Consumer::event_triggered()
appears in the logging, but suddenly stops. Receiving messages from the browser via WebSocket still works. Just the transport from group_send()
to the consumers is broken.