SurfSense/plugins/remote/host/tests/serving.py
Anish Sarkar 8d85b6f544 feat(plugins): serve SurfSense's plugins from one host, a paid one behind the license
plugins/remote/host mounts each plugin folder's MCP server at /<id>/mcp and
answers /health; without proprietary/ it serves only the Apache-2.0 plugins.
A plugin's access hook runs before its server sees a request, and
proprietary/license_check applies contract 2 with Keygen's validate-key: a
five-minute cache, a day's grace while Keygen is down, and 401, 403 or 503
otherwise. The check is license_check/, since license/ beside LICENSE is one
path on macOS and Windows. CI checks plugins/remote/ on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 22:40:00 +05:30

32 lines
966 B
Python

"""The host, or a stand-in for a service it calls, served on loopback for a test."""
import socket
import threading
import time
from collections.abc import Iterator
from contextlib import contextmanager
import uvicorn
from starlette.types import ASGIApp
@contextmanager
def serving(app: ASGIApp) -> Iterator[str]:
"""Serve `app` on a free loopback port and yield its base URL."""
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
# A client holding its stream open must not keep the server up.
config = uvicorn.Config(
app, log_level="warning", lifespan="on", timeout_graceful_shutdown=1
)
server = uvicorn.Server(config)
thread = threading.Thread(target=server.run, kwargs={"sockets": [sock]})
thread.start()
while not server.started:
time.sleep(0.01)
try:
yield f"http://127.0.0.1:{port}"
finally:
server.should_exit = True
thread.join()