Skip to content
Prev Previous commit
Next Next commit
close thread via exception
  • Loading branch information
Archmonger committed Oct 30, 2021
commit 13989c60663e3ee032b37b1b8b6e9b4846063063
25 changes: 16 additions & 9 deletions src/django_idom/websocket_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import asyncio
import json
import logging
from threading import Thread
import threading
from typing import Any
from urllib.parse import parse_qsl

Expand All @@ -25,18 +25,25 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:

async def connect(self) -> None:
await super().connect()
self._idom_dispatcher_thread = Thread(
# Thread-safe queue
self._recv_queue = janus.Queue().async_q

# Run render as thread
self._disconnected = threading.Event()
self._dispatcher_thread = threading.Thread(
target=asyncio.run,
args=(self._run_dispatch_loop(),),
daemon=True,
)
self._idom_dispatcher_thread.start()
self._dispatcher_thread.start()

async def disconnect(self, code: int) -> None:
self._idom_dispatcher_thread.join(timeout=0)
self._disconnected.set()
await self._recv_queue.put(None)
self._dispatcher_thread.join(timeout=0)

async def receive_json(self, content: Any, **kwargs: Any) -> None:
await self._idom_recv_queue.put(LayoutEvent(**content))
await self._recv_queue.put(LayoutEvent(**content))

async def _run_dispatch_loop(self):
view_id = self.scope["url_route"]["kwargs"]["view_id"]
Expand All @@ -59,14 +66,14 @@ async def _run_dispatch_loop(self):
)
return

# Thread-safe queue
self._idom_recv_queue = janus.Queue().async_q
try:
await dispatch_single_view(
Layout(component_instance),
self.send_json,
self._idom_recv_queue.get,
self._recv_queue.get,
)
except Exception:
await self.close()
raise
self._disconnected.wait()
if not self._disconnected.is_set():
raise