|
| 1 | +# This file is part of the QuestionPy SDK. (https://questionpy.org) |
| 2 | +# The QuestionPy SDK is free software released under terms of the MIT license. See LICENSE.md. |
| 3 | +# (c) Technische Universität Berlin, innoCampus <[email protected]> |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import logging |
| 7 | +from collections.abc import Awaitable, Callable |
| 8 | +from contextlib import AbstractAsyncContextManager |
| 9 | +from pathlib import Path |
| 10 | +from types import TracebackType |
| 11 | +from typing import TYPE_CHECKING, Self |
| 12 | + |
| 13 | +from watchdog.events import ( |
| 14 | + FileClosedEvent, |
| 15 | + FileOpenedEvent, |
| 16 | + FileSystemEvent, |
| 17 | + FileSystemEventHandler, |
| 18 | + FileSystemMovedEvent, |
| 19 | +) |
| 20 | +from watchdog.observers import Observer |
| 21 | +from watchdog.utils.event_debouncer import EventDebouncer |
| 22 | + |
| 23 | +from questionpy_common.constants import DIST_DIR |
| 24 | +from questionpy_sdk.package.builder import DirPackageBuilder |
| 25 | +from questionpy_sdk.package.errors import PackageBuildError, PackageSourceValidationError |
| 26 | +from questionpy_sdk.package.source import PackageSource |
| 27 | +from questionpy_sdk.webserver.app import WebServer |
| 28 | +from questionpy_server.worker.runtime.package_location import DirPackageLocation |
| 29 | + |
| 30 | +if TYPE_CHECKING: |
| 31 | + from watchdog.observers.api import ObservedWatch |
| 32 | + |
| 33 | +log = logging.getLogger("questionpy-sdk:watcher") |
| 34 | + |
| 35 | +_DEBOUNCE_INTERVAL = 0.5 # seconds |
| 36 | + |
| 37 | + |
| 38 | +class _EventHandler(FileSystemEventHandler): |
| 39 | + """Debounces events for watchdog file monitoring, ignoring events in the `dist` directory.""" |
| 40 | + |
| 41 | + def __init__( |
| 42 | + self, loop: asyncio.AbstractEventLoop, notify_callback: Callable[[], Awaitable[None]], watch_path: Path |
| 43 | + ) -> None: |
| 44 | + self._loop = loop |
| 45 | + self._notify_callback = notify_callback |
| 46 | + self._watch_path = watch_path |
| 47 | + |
| 48 | + self._event_debouncer = EventDebouncer(_DEBOUNCE_INTERVAL, self._on_file_changes) |
| 49 | + |
| 50 | + def start(self) -> None: |
| 51 | + self._event_debouncer.start() |
| 52 | + |
| 53 | + def stop(self) -> None: |
| 54 | + if self._event_debouncer.is_alive(): |
| 55 | + self._event_debouncer.stop() |
| 56 | + self._event_debouncer.join() |
| 57 | + |
| 58 | + def dispatch(self, event: FileSystemEvent) -> None: |
| 59 | + # filter events and debounce |
| 60 | + if not self._ignore_event(event): |
| 61 | + self._event_debouncer.handle_event(event) |
| 62 | + |
| 63 | + def _on_file_changes(self, events: list[FileSystemEvent]) -> None: |
| 64 | + # skip synchronization hassle by delegating this to the event loop in the main thread |
| 65 | + asyncio.run_coroutine_threadsafe(self._notify_callback(), self._loop) |
| 66 | + |
| 67 | + def _ignore_event(self, event: FileSystemEvent) -> bool: |
| 68 | + """Ignores events that should not trigger a rebuild. |
| 69 | +
|
| 70 | + Args: |
| 71 | + event: The event to check. |
| 72 | +
|
| 73 | + Returns: |
| 74 | + `True` if event should be ignored, otherwise `False`. |
| 75 | + """ |
| 76 | + if isinstance(event, FileOpenedEvent | FileClosedEvent): |
| 77 | + return True |
| 78 | + |
| 79 | + # ignore events events in `dist` dir |
| 80 | + relevant_path = event.dest_path if isinstance(event, FileSystemMovedEvent) else event.src_path |
| 81 | + try: |
| 82 | + return Path(relevant_path).relative_to(self._watch_path).parts[0] == DIST_DIR |
| 83 | + except IndexError: |
| 84 | + return False |
| 85 | + |
| 86 | + |
| 87 | +class Watcher(AbstractAsyncContextManager): |
| 88 | + """Watch a package source path and rebuild package/restart server on file changes.""" |
| 89 | + |
| 90 | + def __init__( |
| 91 | + self, source_path: Path, pkg_location: DirPackageLocation, state_storage_path: Path, host: str, port: int |
| 92 | + ) -> None: |
| 93 | + self._source_path = source_path |
| 94 | + self._pkg_location = pkg_location |
| 95 | + self._host = host |
| 96 | + self._port = port |
| 97 | + |
| 98 | + self._event_handler = _EventHandler(asyncio.get_running_loop(), self._notify, self._source_path) |
| 99 | + self._observer = Observer() |
| 100 | + self._webserver = WebServer(self._pkg_location, state_storage_path, self._host, self._port) |
| 101 | + self._on_change_event = asyncio.Event() |
| 102 | + self._watch: ObservedWatch | None = None |
| 103 | + |
| 104 | + async def __aenter__(self) -> Self: |
| 105 | + self._event_handler.start() |
| 106 | + self._observer.start() |
| 107 | + log.info("Watching '%s' for changes...", self._source_path) |
| 108 | + |
| 109 | + return self |
| 110 | + |
| 111 | + async def __aexit__( |
| 112 | + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None |
| 113 | + ) -> None: |
| 114 | + if self._observer.is_alive(): |
| 115 | + self._observer.stop() |
| 116 | + self._event_handler.stop() |
| 117 | + await self._webserver.stop_server() |
| 118 | + |
| 119 | + def _schedule(self) -> None: |
| 120 | + if self._watch is None: |
| 121 | + log.debug("Starting file watching...") |
| 122 | + self._watch = self._observer.schedule(self._event_handler, self._source_path, recursive=True) |
| 123 | + |
| 124 | + def _unschedule(self) -> None: |
| 125 | + if self._watch: |
| 126 | + log.debug("Stopping file watching...") |
| 127 | + self._observer.unschedule(self._watch) |
| 128 | + self._watch = None |
| 129 | + |
| 130 | + async def _notify(self) -> None: |
| 131 | + self._on_change_event.set() |
| 132 | + |
| 133 | + async def run_forever(self) -> None: |
| 134 | + try: |
| 135 | + await self._webserver.start_server() |
| 136 | + except Exception: |
| 137 | + log.exception("Failed to start webserver. The exception was:") |
| 138 | + # When user messed up the their package on initial run, we just bail out. |
| 139 | + return |
| 140 | + |
| 141 | + self._schedule() |
| 142 | + |
| 143 | + while True: |
| 144 | + await self._on_change_event.wait() |
| 145 | + |
| 146 | + # Try to rebuild package and restart web server which might fail. |
| 147 | + self._unschedule() |
| 148 | + await self._rebuild_and_restart() |
| 149 | + self._schedule() |
| 150 | + |
| 151 | + self._on_change_event.clear() |
| 152 | + |
| 153 | + async def _rebuild_and_restart(self) -> None: |
| 154 | + log.info("File changes detected. Rebuilding package...") |
| 155 | + |
| 156 | + # Stop webserver. |
| 157 | + try: |
| 158 | + await self._webserver.stop_server() |
| 159 | + except Exception: |
| 160 | + log.exception("Failed to stop web server. The exception was:") |
| 161 | + raise # Should not happen, thus we're propagating. |
| 162 | + |
| 163 | + # Build package. |
| 164 | + try: |
| 165 | + package_source = PackageSource(self._source_path) |
| 166 | + with DirPackageBuilder(package_source) as builder: |
| 167 | + builder.write_package() |
| 168 | + except (PackageBuildError, PackageSourceValidationError): |
| 169 | + log.exception("Failed to build package. The exception was:") |
| 170 | + return |
| 171 | + |
| 172 | + # Start server. |
| 173 | + try: |
| 174 | + await self._webserver.start_server() |
| 175 | + except Exception: |
| 176 | + log.exception("Failed to start web server. The exception was:") |
0 commit comments