Debian Codegraph @

mkdocs/livereload/__init__.py

raw
1 from __future__ import annotations
2
3 import functools
4 import io
5 import ipaddress
6 import logging
7 import mimetypes
8 import os
9 import os.path
10 import pathlib
11 import posixpath
12 import re
13 import socket
14 import socketserver
15 import string
16 import sys
17 import threading
18 import time
19 import traceback
20 import urllib.parse
21 import webbrowser
22 import wsgiref.simple_server
23 import wsgiref.util
24 from typing import Any, BinaryIO, Callable, Iterable
25
26 import watchdog.events
27 import watchdog.observers.polling
28
29 _SCRIPT_TEMPLATE_STR = """
30 var livereload = function(epoch, requestId) {
31 var req, timeout;
32
33 var poll = function() {
34 req = new XMLHttpRequest();
35 req.onloadend = function() {
36 if (parseFloat(this.responseText) > epoch) {
37 location.reload();
38 } else {
39 timeout = setTimeout(poll, this.status === 200 ? 0 : 3000);
40 }
41 };
42 req.open("GET", "/livereload/" + epoch + "/" + requestId);
43 req.send();
44 }
45
46 var stop = function() {
47 if (req) {
48 req.abort();
49 }
50 if (timeout) {
51 clearTimeout(timeout);
52 }
53 req = timeout = undefined;
54 };
55
56 window.addEventListener("load", function() {
57 if (document.visibilityState === "visible") {
58 poll();
59 }
60 });
61 window.addEventListener("visibilitychange", function() {
62 if (document.visibilityState === "visible") {
63 poll();
64 } else {
65 stop();
66 }
67 });
68 window.addEventListener("beforeunload", stop);
69
70 console.log('Enabled live reload');
71 }
72 livereload(${epoch}, ${request_id});
73 """
74 _SCRIPT_TEMPLATE = string.Template(_SCRIPT_TEMPLATE_STR)
75
76
77 class _LoggerAdapter(logging.LoggerAdapter):
78 def process(self, msg: str, kwargs: dict) -> tuple[str, dict]: # type: ignore[override]
79 return time.strftime("[%H:%M:%S] ") + msg, kwargs
80
81
82 log = _LoggerAdapter(logging.getLogger(__name__), {})
83
84
85 def _normalize_mount_path(mount_path: str) -> str:
86 """Ensure the mount path starts and ends with a slash."""
87 return ("/" + mount_path.lstrip("/")).rstrip("/") + "/"
88
89
90 def _serve_url(host: str, port: int, path: str) -> str:
91 return f"http://{host}:{port}{_normalize_mount_path(path)}"
92
93
94 class LiveReloadServer(socketserver.ThreadingMixIn, wsgiref.simple_server.WSGIServer):
95 daemon_threads = True
96 poll_response_timeout = 60
97
98 def __init__(
99 self,
100 builder: Callable[[], None],
101 host: str,
102 port: int,
103 root: str,
104 mount_path: str = "/",
105 polling_interval: float = 0.5,
106 shutdown_delay: float = 0.25,
107 ) -> None:
108 self.builder = builder
109 try:
110 if isinstance(ipaddress.ip_address(host), ipaddress.IPv6Address):
111 self.address_family = socket.AF_INET6
112 except Exception:
113 pass
114 self.root = os.path.abspath(root)
115 self.mount_path = _normalize_mount_path(mount_path)
116 self.url = _serve_url(host, port, mount_path)
117 self.build_delay = 0.1
118 self.shutdown_delay = shutdown_delay
119 # To allow custom error pages.
120 self.error_handler: Callable[[int], bytes | None] = lambda code: None
121
122 super().__init__((host, port), _Handler, bind_and_activate=False)
123 self.set_app(self.serve_request)
124
125 self._wanted_epoch = _timestamp() # The version of the site that started building.
126 self._visible_epoch = self._wanted_epoch # Latest fully built version of the site.
127 self._epoch_cond = threading.Condition() # Must be held when accessing _visible_epoch.
128
129 self._want_rebuild: bool = False
130 self._rebuild_cond = threading.Condition() # Must be held when accessing _want_rebuild.
131
132 self._shutdown = False
133 self.serve_thread = threading.Thread(target=lambda: self.serve_forever(shutdown_delay))
134 self.observer = watchdog.observers.polling.PollingObserver(timeout=polling_interval)
135
136 self._watched_paths: dict[str, int] = {}
137 self._watch_refs: dict[str, Any] = {}
138
139 def watch(self, path: str, func: None = None, *, recursive: bool = True) -> None:
140 """Add the 'path' to watched paths, call the function and reload when any file changes under it."""
141 path = os.path.abspath(path)
142 if not (func is None or func is self.builder): # type: ignore[unreachable]
143 raise TypeError("Plugins can no longer pass a 'func' parameter to watch().")
144
145 if path in self._watched_paths:
146 self._watched_paths[path] += 1
147 return
148 self._watched_paths[path] = 1
149
150 def callback(event):
151 if event.is_directory:
152 return
153 log.debug(str(event))
154 with self._rebuild_cond:
155 self._want_rebuild = True
156 self._rebuild_cond.notify_all()
157
158 handler = watchdog.events.FileSystemEventHandler()
159 handler.on_any_event = callback # type: ignore[method-assign]
160 log.debug(f"Watching '{path}'")
161 self._watch_refs[path] = self.observer.schedule(handler, path, recursive=recursive)
162
163 def unwatch(self, path: str) -> None:
164 """Stop watching file changes for path. Raises if there was no corresponding `watch` call."""
165 path = os.path.abspath(path)
166
167 self._watched_paths[path] -= 1
168 if self._watched_paths[path] <= 0:
169 self._watched_paths.pop(path)
170 self.observer.unschedule(self._watch_refs.pop(path))
171
172 def serve(self, *, open_in_browser=False):
173 self.server_bind()
174 self.server_activate()
175
176 if self._watched_paths:
177 self.observer.start()
178
179 paths_str = ", ".join(f"'{_try_relativize_path(path)}'" for path in self._watched_paths)
180 log.info(f"Watching paths for changes: {paths_str}")
181
182 if open_in_browser:
183 log.info(f"Serving on {self.url} and opening it in a browser")
184 else:
185 log.info(f"Serving on {self.url}")
186 self.serve_thread.start()
187 if open_in_browser:
188 webbrowser.open(self.url)
189
190 self._build_loop()
191
192 def _build_loop(self):
193 while True:
194 with self._rebuild_cond:
195 while not self._rebuild_cond.wait_for(
196 lambda: self._want_rebuild or self._shutdown, timeout=self.shutdown_delay
197 ):
198 # We could have used just one wait instead of a loop + timeout, but we need
199 # occasional breaks, otherwise on Windows we can't receive KeyboardInterrupt.
200 pass
201 if self._shutdown:
202 break
203 log.info("Detected file changes")
204 while self._rebuild_cond.wait(timeout=self.build_delay):
205 log.debug("Waiting for file changes to stop happening")
206
207 self._wanted_epoch = _timestamp()
208 self._want_rebuild = False
209
210 try:
211 self.builder()
212 except Exception as e:
213 if isinstance(e, SystemExit):
214 print(e, file=sys.stderr) # noqa: T201
215 else:
216 traceback.print_exc()
217 log.error(
218 "An error happened during the rebuild. The server will appear stuck until build errors are resolved."
219 )
220 continue
221
222 with self._epoch_cond:
223 log.info("Reloading browsers")
224 self._visible_epoch = self._wanted_epoch
225 self._epoch_cond.notify_all()
226
227 def shutdown(self, wait=False) -> None:
228 self.observer.stop()
229 with self._rebuild_cond:
230 self._shutdown = True
231 self._rebuild_cond.notify_all()
232
233 if self.serve_thread.is_alive():
234 super().shutdown()
235 self.server_close()
236 if wait:
237 self.serve_thread.join()
238 self.observer.join()
239
240 def serve_request(self, environ, start_response) -> Iterable[bytes]:
241 try:
242 result = self._serve_request(environ, start_response)
243 except Exception:
244 code = 500
245 msg = "500 Internal Server Error"
246 log.exception(msg)
247 else:
248 if result is not None:
249 return result
250 code = 404
251 msg = "404 Not Found"
252
253 error_content = None
254 try:
255 error_content = self.error_handler(code)
256 except Exception:
257 log.exception("Failed to render an error message!")
258 if error_content is None:
259 error_content = msg.encode()
260
261 start_response(msg, [("Content-Type", "text/html")])
262 return [error_content]
263
264 def _serve_request(self, environ, start_response) -> Iterable[bytes] | None:
265 # https://bugs.python.org/issue16679
266 # https://github.com/bottlepy/bottle/blob/f9b1849db4/bottle.py#L984
267 path = environ["PATH_INFO"].encode("latin-1").decode("utf-8", "ignore")
268
269 if path.startswith("/livereload/"):
270 if m := re.fullmatch(r"/livereload/([0-9]+)/[0-9]+", path):
271 epoch = int(m[1])
272 start_response("200 OK", [("Content-Type", "text/plain")])
273
274 def condition():
275 return self._visible_epoch > epoch
276
277 with self._epoch_cond:
278 if not condition():
279 # Stall the browser, respond as soon as there's something new.
280 # If there's not, respond anyway after a minute.
281 self._log_poll_request(environ.get("HTTP_REFERER"), request_id=path)
282 self._epoch_cond.wait_for(condition, timeout=self.poll_response_timeout)
283 return [b"%d" % self._visible_epoch]
284
285 if (path + "/").startswith(self.mount_path):
286 rel_file_path = path[len(self.mount_path) :]
287
288 if path.endswith("/"):
289 rel_file_path += "index.html"
290 # Prevent directory traversal - normalize the path.
291 rel_file_path = posixpath.normpath("/" + rel_file_path).lstrip("/")
292 file_path = os.path.join(self.root, rel_file_path)
293 elif path == "/":
294 start_response("302 Found", [("Location", urllib.parse.quote(self.mount_path))])
295 return []
296 else:
297 return None # Not found
298
299 # Wait until the ongoing rebuild (if any) finishes, so we're not serving a half-built site.
300 with self._epoch_cond:
301 self._epoch_cond.wait_for(lambda: self._visible_epoch == self._wanted_epoch)
302 epoch = self._visible_epoch
303
304 try:
305 file: BinaryIO = open(file_path, "rb")
306 except OSError:
307 if not path.endswith("/") and os.path.isfile(os.path.join(file_path, "index.html")):
308 start_response("302 Found", [("Location", urllib.parse.quote(path) + "/")])
309 return []
310 return None # Not found
311
312 if self._watched_paths and file_path.endswith(".html"):
313 with file:
314 content = file.read()
315 content = self._inject_js_into_html(content, epoch)
316 file = io.BytesIO(content)
317 content_length = len(content)
318 else:
319 content_length = os.path.getsize(file_path)
320
321 content_type = self._guess_type(file_path)
322 start_response(
323 "200 OK", [("Content-Type", content_type), ("Content-Length", str(content_length))]
324 )
325 return wsgiref.util.FileWrapper(file)
326
327 def _inject_js_into_html(self, content, epoch):
328 try:
329 body_end = content.rindex(b"</body>")
330 except ValueError:
331 body_end = len(content)
332 # The page will reload if the livereload poller returns a newer epoch than what it knows.
333 # The other timestamp becomes just a unique identifier for the initiating page.
334 script = _SCRIPT_TEMPLATE.substitute(epoch=epoch, request_id=_timestamp())
335 return b"%b<script>%b</script>%b" % (
336 content[:body_end],
337 script.encode(),
338 content[body_end:],
339 )
340
341 @classmethod
342 @functools.lru_cache # "Cache" to not repeat the same message for the same browser tab.
343 def _log_poll_request(cls, url, request_id):
344 log.info(f"Browser connected: {url}")
345
346 @classmethod
347 def _guess_type(cls, path):
348 # MkDocs only ensures a few common types (as seen in livereload_tests.py::test_mime_types).
349 # Other uncommon types will not be accepted.
350 if path.endswith((".js", ".JS", ".mjs")):
351 return "application/javascript"
352 if path.endswith(".gz"):
353 return "application/gzip"
354
355 guess, _ = mimetypes.guess_type(path)
356 if guess:
357 return guess
358 return "application/octet-stream"
359
360
361 class _Handler(wsgiref.simple_server.WSGIRequestHandler):
362 def log_request(self, code="-", size="-"):
363 level = logging.DEBUG if str(code) == "200" else logging.WARNING
364 log.log(level, f'"{self.requestline}" code {code}')
365
366 def log_message(self, format, *args):
367 log.debug(format, *args)
368
369
370 def _timestamp() -> int:
371 return round(time.monotonic() * 1000)
372
373
374 def _try_relativize_path(path: str) -> str:
375 """Make the path relative to current directory if it's under that directory."""
376 p = pathlib.Path(path)
377 try:
378 p = p.relative_to(os.getcwd())
379 except ValueError:
380 pass
381 return str(p)