Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- `WaitingRoom(fail_open=True)`: let visitors without a pass through when the waiting page doesn't answer within `fail_open_timeout` (default 1.5 s; a timeout, network error or 5xx) instead of sending them to a page that won't load. One check per room, kept 15 seconds (`WaitingRoom.reachable()`); `Decision.fail_open`, `request.state.hibira_fail_open` / `environ["hibira.fail_open"]` and `on_fail_open` report it. The ASGI middleware runs the check off the event loop.

## 0.2.0

- Chat API on `Client` and `AsyncClient`: `put_conversation`, `get_conversation`, `delete_conversation`, `add_members`, `remove_member`, `send_message`, `list_messages`, `mark_read`, `system_message`, `user_conversations`, and `chat_request` for any other call.
Expand Down
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,13 @@ The pass has `number`, `ticket_id` (record it to allow one checkout per number)
and `expires_at`. During a secret rotation give `secret=[new, old]`. For rooms
with one place per signed-in customer, pass `user=lambda req: sign_user(SECRET, "presale", customer_id(req))`
and compare `pass.user_id` at checkout. `verify_pass(token, secret, room=...)`
checks a pass anywhere else. Django has its own middleware in
checks a pass anywhere else.

Set `fail_open=True` to let visitors through when the waiting page can't be
reached (1.5 s timeout, one check per room every 15 seconds), so a network
problem between your visitors and Hibira never blocks your page.

Django has its own middleware in
[django-hibira](https://github.com/hibira-io/django).

## Live Chat verified visitors
Expand Down Expand Up @@ -323,7 +329,7 @@ client):發送事件、私人 / presence 頻道授權、驗證 webhook、推
Gemini 的串流格式,並附 FastAPI 授權路由與 webhook 驗證。

另有 Chat API(對話、訊息、已讀、離線推播)、等候室 middleware(`hibira.waiting_room`,
FastAPI / Starlette 等 ASGI 與 Flask 等 WSGI 皆可用),以及 Live Chat 已驗證訪客的
FastAPI / Starlette 等 ASGI 與 Flask 等 WSGI 皆可用;`fail_open=True` 可在等候頁連不上時直接放行),以及 Live Chat 已驗證訪客的
`user_hash()`。

## License
Expand Down
60 changes: 58 additions & 2 deletions src/hibira/waiting_room.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,16 @@ async def drop(request: Request):

from __future__ import annotations

import asyncio
import base64
import binascii
import hashlib
import hmac
import json
import threading
import time
import urllib.error
import urllib.request
from dataclasses import dataclass, field
from typing import Any, Awaitable, Callable, Iterable, Literal, MutableMapping, Optional, Sequence, Union
from urllib.parse import parse_qsl, quote, urlencode, urlsplit, urlunsplit
Expand Down Expand Up @@ -164,6 +168,21 @@ class Decision:
set_cookie: Optional[str] = None
"""A Set-Cookie header value to send with the redirect."""
pass_: Optional[Pass] = None
fail_open: bool = False
"""True when allowed only because the waiting page could not be reached."""


_probes: dict[str, tuple[bool, float]] = {}
_probes_lock = threading.Lock()


def _http_status(url: str, timeout: float) -> int:
req = urllib.request.Request(url, headers={"Accept": "application/json"})
try:
with urllib.request.urlopen(req, timeout=timeout) as res: # noqa: S310 - https URL built from the room host
return int(res.status)
except urllib.error.HTTPError as e:
return int(e.code)


def _read_cookie(header: Optional[str], name: str) -> Optional[str]:
Expand Down Expand Up @@ -192,6 +211,34 @@ class WaitingRoom:
cookie_name: str = ""
user: Optional[UserToken] = field(default=None, repr=False)
"""Optional: returns a sign_user() token for the request's signed-in customer."""
fail_open: bool = False
"""Let visitors without a pass through when the waiting page doesn't answer
(timeout, network error or 5xx) instead of sending them to a page that
won't load. One check per room, kept 15 seconds."""
fail_open_timeout: float = 1.5
on_fail_open: Optional[Callable[[str], None]] = field(default=None, repr=False)
"""Called with the request URL for each visitor let through by fail_open."""
probe: Optional[Callable[[str, float], int]] = field(default=None, repr=False)
"""For tests: returns the HTTP status of a GET, or raises."""

def reachable(self, now: Optional[float] = None) -> bool:
"""Whether GET <host>/waitroom/<key>/<room> answers in time and not with a 5xx."""
url = f"{self.host.rstrip('/')}/waitroom/{quote(self.app_key, safe='')}/{quote(self.room, safe='')}"
t = time.time() if now is None else now
with _probes_lock:
hit = _probes.get(url)
if hit is not None and hit[1] > t:
return hit[0]
try:
status = (self.probe or _http_status)(url, self.fail_open_timeout)
ok = 0 < status < 500
except Exception: # noqa: BLE001 - any failure to reach the page counts as down
ok = False
with _probes_lock:
if len(_probes) > 256:
_probes.clear()
_probes[url] = (ok, t + 15)
return ok

def __post_init__(self) -> None:
if not self.cookie_name:
Expand Down Expand Up @@ -230,6 +277,10 @@ def decide(
p = self.verify(_read_cookie(cookie, self.cookie_name), now)
if p is not None:
return Decision("allow", pass_=p)
if self.fail_open and not self.reachable(now):
if self.on_fail_open is not None:
self.on_fail_open(url)
return Decision("allow", fail_open=True)
if method.upper() not in ("GET", "HEAD"):
return Decision("deny")
user = self.user(request) if self.user is not None and request is not None else None
Expand Down Expand Up @@ -277,9 +328,13 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
path = scope.get("root_path", "") + scope.get("path", "")
qs = scope.get("query_string", b"").decode("latin-1")
url = f"{scope.get('scheme', 'http')}://{host}{quote(path)}" + (f"?{qs}" if qs else "")
d = self.room.decide(url, scope.get("method", "GET"), headers.get("cookie"), request=scope)
args = (url, scope.get("method", "GET"), headers.get("cookie"), scope)
# The fail_open check is a blocking request: keep it off the event loop.
d = await asyncio.to_thread(self.room.decide, *args) if self.room.fail_open else self.room.decide(*args)
if d.action == "allow":
scope.setdefault("state", {})["hibira_pass"] = d.pass_
state = scope.setdefault("state", {})
state["hibira_pass"] = d.pass_
state["hibira_fail_open"] = d.fail_open
await self.app(scope, receive, send)
return
if d.action == "deny":
Expand Down Expand Up @@ -324,6 +379,7 @@ def __call__(self, environ: Environ, start_response: Callable[..., Any]) -> Iter
d = self.room.decide(url, environ.get("REQUEST_METHOD", "GET"), environ.get("HTTP_COOKIE"), request=environ)
if d.action == "allow":
environ["hibira.pass"] = d.pass_
environ["hibira.fail_open"] = d.fail_open
return self.app(environ, start_response)
if d.action == "deny":
length = str(len(_DENY_BODY))
Expand Down
46 changes: 46 additions & 0 deletions tests/test_waiting_room.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,49 @@ def app(environ, start_response):
wsgi_call(WSGIMiddleware(lambda e, s: (s("200 OK", []), [b"open"])[1], ROOM, ["/drop"]), path="/other")[2]
== b"open"
)


def test_fail_open_lets_visitors_through_when_the_waiting_page_is_down():
calls = []
seen = []

def down(url, timeout):
calls.append((url, timeout))
return 522

room = WaitingRoom(
app_key="key-fo", secret="s", room="presale", fail_open=True, probe=down, on_fail_open=seen.append
)
d = room.decide("https://shop.test/drop", now=NOW)
assert d.action == "allow" and d.fail_open and d.pass_ is None
assert room.decide("https://shop.test/drop", method="POST", now=NOW + 5).action == "allow"
assert calls == [("https://ws.hibira.io/waitroom/key-fo/presale", 1.5)]
assert seen == ["https://shop.test/drop", "https://shop.test/drop"]


def test_fail_open_treats_errors_as_down_and_keeps_the_queue_when_up():
def boom(url, timeout):
raise TimeoutError("timed out")

down = WaitingRoom(app_key="key-err", secret="s", room="presale", fail_open=True, probe=boom)
assert down.decide("https://shop.test/drop", now=NOW).action == "allow"
up = WaitingRoom(app_key="key-up", secret="s", room="presale", fail_open=True, probe=lambda u, t: 200)
assert up.decide("https://shop.test/drop", now=NOW).action == "redirect"

def never(url, timeout):
raise AssertionError("not called")

off = WaitingRoom(app_key="key-off", secret="s", room="presale", probe=never)
assert off.decide("https://shop.test/drop", now=NOW).action == "redirect"


def test_fail_open_in_asgi():
app = FastAPI()

@app.get("/drop")
def drop(request: Request):
return {"fail_open": request.state.hibira_fail_open}

room = WaitingRoom(app_key="key-asgi", secret="s", room="presale", fail_open=True, probe=lambda u, t: 503)
c = TestClient(ASGIMiddleware(app, room), base_url="https://shop.test")
assert c.get("/drop", follow_redirects=False).json() == {"fail_open": True}
Loading