Skip to content

Threaded dispatcher loop #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions requirements/pkg-deps.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
channels<4.0.0 # Django websocket features
idom >=0.33.0, <0.34.0
janus < 1.0.0
20 changes: 12 additions & 8 deletions src/django_idom/websocket_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
import asyncio
import json
import logging
from threading import Thread
from typing import Any
from urllib.parse import parse_qsl

import janus
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from idom.core.dispatcher import dispatch_single_view
from idom.core.layout import Layout, LayoutEvent
Expand All @@ -23,14 +25,15 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:

async def connect(self) -> None:
await super().connect()
self._idom_dispatcher_future = asyncio.ensure_future(self._run_dispatch_loop())
self._idom_dispatcher_thread = Thread(
target=asyncio.run,
args=(self._run_dispatch_loop(),),
)
self._idom_dispatcher_thread.daemon = True
self._idom_dispatcher_thread.start()

async def disconnect(self, code: int) -> None:
if self._idom_dispatcher_future.done():
await self._idom_dispatcher_future
else:
self._idom_dispatcher_future.cancel()
await super().disconnect(code)
self._idom_dispatcher_thread.join(timeout=0)

async def receive_json(self, content: Any, **kwargs: Any) -> None:
await self._idom_recv_queue.put(LayoutEvent(**content))
Expand All @@ -56,12 +59,13 @@ async def _run_dispatch_loop(self):
)
return

self._idom_recv_queue = recv_queue = asyncio.Queue()
# Thread-safe queue
self._idom_recv_queue = janus.Queue().async_q
try:
await dispatch_single_view(
Layout(component_instance),
self.send_json,
recv_queue.get,
self._idom_recv_queue.get,
)
except Exception:
await self.close()
Expand Down