From 742b05ed666022b016429c0e279ed7dd008b2e88 Mon Sep 17 00:00:00 2001 From: Leo Vasanko Date: Wed, 1 Nov 2023 14:40:08 +0000 Subject: [PATCH] Faster wwwroot serving, uses RAM cache of brotli compressed data for all assets. --- cista/app.py | 32 ++++++++++++++++++-------------- pyproject.toml | 1 + 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/cista/app.py b/cista/app.py index 0dbe4d8..c99919c 100755 --- a/cista/app.py +++ b/cista/app.py @@ -63,12 +63,14 @@ www = {} @app.before_server_start -def load_wwwroot(app, _): +def load_wwwroot(app): www.clear() - base = files("cista") - paths = ["wwwroot"] - while path := paths.pop(0): - current = files("cista") / path + base = files("cista") / "wwwroot" + paths = ["."] + while paths: + path = paths.pop(0) + current = base / path + print(">>>", current) for p in current.iterdir(): if p.is_dir(): print(p) @@ -80,18 +82,20 @@ def load_wwwroot(app, _): br = brotli.compress(data) if len(br) >= len(data): br = False + print(name, len(data), len(br) if br else br, mime) www[name] = data, br, mime @app.get("/", static=True) async def wwwroot(req, path=""): """Frontend files only""" - name = filename.sanitize(unquote(path)) if path else "index.html" - try: - index = files("cista").joinpath("wwwroot", name).read_bytes() - except OSError as e: - raise NotFound( - f"File not found: /{path}", extra={"name": name, "exception": repr(e)} - ) - mime = mimetypes.guess_type(name)[0] or "application/octet-stream" - return raw(index, content_type=mime) + name = unquote(path) or "index.html" + if name not in www: + raise NotFound(f"File not found: /{path}", extra={"name": name}) + data, br, mime = www[name] + headers = {} + # Brotli compressed? + if br and "br" in req.headers.accept_encoding.split(", "): + headers["content-encoding"] = "br" + data = br + return raw(data, content_type=mime, headers=headers) diff --git a/pyproject.toml b/pyproject.toml index bcfd2e9..78b7351 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,6 +15,7 @@ classifiers = [ ] dependencies = [ "argon2-cffi", + "brotli", "docopt", "inotify", "msgspec",