-
-
Notifications
You must be signed in to change notification settings - Fork 83
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement hot reloading with websockets
- Loading branch information
Showing
7 changed files
with
148 additions
and
47 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,3 @@ | ||
"""Rebuild Sphinx documentation on changes, with live-reload in the browser.""" | ||
"""Rebuild Sphinx documentation on changes, with hot reloading in the browser.""" | ||
|
||
__version__ = "2024.02.04" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
from __future__ import annotations | ||
|
||
from starlette.datastructures import MutableHeaders | ||
from starlette.types import ASGIApp, Message, Receive, Scope, Send | ||
|
||
|
||
def web_socket_script(ws_url: str) -> str: | ||
# language=HTML | ||
return f""" | ||
<script> | ||
const ws = new WebSocket("ws://{ws_url}/websocket-reload"); | ||
ws.onmessage = () => window.location.reload(); | ||
</script> | ||
""" | ||
|
||
|
||
class JavascriptInjectorMiddleware: | ||
def __init__(self, app: ASGIApp, ws_url: str) -> None: | ||
self.app = app | ||
self.script = web_socket_script(ws_url).encode("utf-8") | ||
|
||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | ||
add_script = False | ||
if scope["type"] != "http": | ||
await self.app(scope, receive, send) | ||
return | ||
|
||
async def send_wrapper(message: Message) -> None: | ||
nonlocal add_script | ||
if message["type"] == "http.response.start": | ||
headers = MutableHeaders(scope=message) | ||
if headers.get("Content-Type", "").startswith("text/html"): | ||
add_script = True | ||
if "Content-Length" in headers: | ||
length = int(headers["Content-Length"]) + len(self.script) | ||
headers["Content-Length"] = str(length) | ||
elif message["type"] == "http.response.body": | ||
request_complete = not message.get("more_body", False) | ||
if add_script and request_complete: | ||
message["body"] += self.script | ||
await send(message) | ||
|
||
await self.app(scope, receive, send_wrapper) | ||
return |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
from __future__ import annotations | ||
|
||
import asyncio | ||
import os | ||
from contextlib import AbstractAsyncContextManager, asynccontextmanager | ||
|
||
import watchfiles | ||
from starlette.types import Receive, Scope, Send | ||
from starlette.websockets import WebSocket | ||
|
||
TYPE_CHECKING = False | ||
if TYPE_CHECKING: | ||
from collections.abc import Callable | ||
|
||
from sphinx_autobuild.filter import IgnoreFilter | ||
|
||
|
||
class RebuildServer: | ||
def __init__( | ||
self, | ||
paths: list[os.PathLike[str]], | ||
ignore_filter: IgnoreFilter, | ||
change_callback: Callable[[], None], | ||
) -> None: | ||
self.paths = [os.path.realpath(path, strict=True) for path in paths] | ||
self.ignore = ignore_filter | ||
self.change_callback = change_callback | ||
self.flag = asyncio.Event() | ||
self.should_exit = asyncio.Event() | ||
|
||
@asynccontextmanager | ||
async def lifespan(self, _app) -> AbstractAsyncContextManager[None]: | ||
task = asyncio.create_task(self.main()) | ||
yield | ||
self.should_exit.set() | ||
await task | ||
return | ||
|
||
async def main(self) -> None: | ||
tasks = ( | ||
asyncio.create_task(self.watch()), | ||
asyncio.create_task(self.should_exit.wait()), | ||
) | ||
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) | ||
[task.cancel() for task in pending] | ||
[task.result() for task in done] | ||
|
||
async def watch(self) -> None: | ||
async for _changes in watchfiles.awatch( | ||
*self.paths, | ||
watch_filter=lambda _, path: not self.ignore(path), | ||
): | ||
self.change_callback() | ||
self.flag.set() | ||
|
||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | ||
assert scope["type"] == "websocket" | ||
ws = WebSocket(scope, receive, send) | ||
await ws.accept() | ||
|
||
tasks = ( | ||
asyncio.create_task(self.watch_reloads(ws)), | ||
asyncio.create_task(self.wait_client_disconnect(ws)), | ||
) | ||
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) | ||
[task.cancel() for task in pending] | ||
[task.result() for task in done] | ||
|
||
async def watch_reloads(self, ws: WebSocket) -> None: | ||
while True: | ||
await self.flag.wait() | ||
self.flag.clear() | ||
await ws.send_text("refresh") | ||
|
||
@staticmethod | ||
async def wait_client_disconnect(ws: WebSocket) -> None: | ||
async for _ in ws.iter_text(): | ||
pass |