forked from kenzuya/unshackle
132 lines
5.2 KiB
Python
132 lines
5.2 KiB
Python
"""The remote session protocol: what a remote client sends must be what the server serves."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ast
|
|
import functools
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from unshackle.core import remote_channel, remote_lifetime
|
|
from unshackle.core import remote_protocol as protocol
|
|
from unshackle.core import remote_service
|
|
from unshackle.core.api import routes
|
|
|
|
ROUTE_NAMES = {name for name in vars(protocol) if name.endswith("_ROUTE")}
|
|
CLIENT_METHODS = {
|
|
"get": "GET",
|
|
"probe": "GET",
|
|
"post": "POST",
|
|
"ws_connect": "GET",
|
|
}
|
|
SERVED = {(method, path): handler for method, path, handler, _ in routes.ROUTES}
|
|
ROOT = Path(__file__).parents[3]
|
|
|
|
|
|
@functools.cache
|
|
def client_tree() -> ast.Module:
|
|
"""The client modules as one tree: the remote service, the session channel adapters and the session lifetime."""
|
|
modules = [
|
|
ast.parse(Path(m.__file__).read_text(encoding="utf-8"))
|
|
for m in (remote_service, remote_channel, remote_lifetime)
|
|
]
|
|
return ast.Module(body=[node for module in modules for node in module.body], type_ignores=[])
|
|
|
|
|
|
def client_calls() -> tuple[set[tuple[str, str]], set[str]]:
|
|
"""The (method, route) pairs the client sends, and every route name the client module reads.
|
|
|
|
A URL a function keeps in a local variable counts at the call that sends it.
|
|
"""
|
|
tree = client_tree()
|
|
referenced = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and n.id in ROUTE_NAMES}
|
|
calls: set[tuple[str, str]] = set()
|
|
for function in ast.walk(tree):
|
|
if not isinstance(function, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
continue
|
|
local = {
|
|
target.id: node.value
|
|
for node in ast.walk(function)
|
|
if isinstance(node, ast.Assign)
|
|
for target in node.targets
|
|
if isinstance(target, ast.Name)
|
|
}
|
|
for call in ast.walk(function):
|
|
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute) and call.args):
|
|
continue
|
|
if call.func.attr in ("request", "send") and isinstance(call.args[0], ast.Constant) and len(call.args) > 1:
|
|
method, target = str(call.args[0].value).upper(), call.args[1]
|
|
elif call.func.attr in CLIENT_METHODS:
|
|
method, target = CLIENT_METHODS[call.func.attr], call.args[0]
|
|
else:
|
|
continue
|
|
if isinstance(target, ast.Name):
|
|
target = local.get(target.id, target)
|
|
calls |= {
|
|
(method, getattr(protocol, n.id))
|
|
for n in ast.walk(target)
|
|
if isinstance(n, ast.Name) and n.id in ROUTE_NAMES
|
|
}
|
|
return calls, referenced
|
|
|
|
|
|
def test_every_route_the_client_calls_is_served_with_that_method():
|
|
calls, referenced = client_calls()
|
|
assert calls, "the scan found no client calls"
|
|
assert {path for _, path in calls} >= {getattr(protocol, name) for name in referenced}
|
|
assert calls <= SERVED.keys()
|
|
|
|
|
|
def test_the_server_takes_its_remote_session_routes_from_the_protocol():
|
|
protocol_paths = {getattr(protocol, name) for name in ROUTE_NAMES}
|
|
served_paths = {path for _, path in SERVED}
|
|
assert protocol_paths <= served_paths
|
|
assert {path for path in served_paths if path.startswith("/api/session")} <= protocol_paths
|
|
|
|
|
|
def test_the_wire_values_stay_pinned():
|
|
"""Both halves read one record, so only this list catches a renamed value on the wire."""
|
|
assert {name: getattr(protocol, name) for name in ROUTE_NAMES} == {
|
|
"HEALTH_ROUTE": "/api/health",
|
|
"SERVICES_ROUTE": "/api/services",
|
|
"SEARCH_ROUTE": "/api/search",
|
|
"SESSION_CREATE_ROUTE": "/api/session/create",
|
|
"SESSION_ROUTE": "/api/session/{session_id}",
|
|
"TITLES_ROUTE": "/api/session/{session_id}/titles",
|
|
"TRACKS_ROUTE": "/api/session/{session_id}/tracks",
|
|
"SEGMENTS_ROUTE": "/api/session/{session_id}/segments",
|
|
"SEGMENT_FILTER_ROUTE": "/api/session/{session_id}/segment_filter",
|
|
"SAMPLES_ROUTE": "/api/session/{session_id}/samples",
|
|
"LICENSE_ROUTE": "/api/session/{session_id}/license",
|
|
"KEYS_ROUTE": "/api/session/{session_id}/keys",
|
|
"BAD_KEY_ROUTE": "/api/session/{session_id}/keys/bad",
|
|
"CHANNEL_ROUTE": "/api/session/{session_id}/channel",
|
|
}
|
|
assert [m.value for m in protocol.ChannelMessage] == ["prompt", "cdm_call", "log", "status", "drain", "answer"]
|
|
assert protocol.CHANNEL_SESSION_GONE == 4404
|
|
assert [s.value for s in protocol.AuthStatus] == ["authenticating", "authenticated", "failed"]
|
|
assert {c.name for c in protocol.APIErrorCode} >= {
|
|
"SESSION_NOT_FOUND",
|
|
"SERVER_CDM_CAPPED",
|
|
"SERVER_DRAINING",
|
|
"CLIENT_OUTDATED",
|
|
}
|
|
assert [k.value for k in protocol.ClientErrorKind] == [
|
|
"CONNECT",
|
|
"TIMEOUT",
|
|
"AUTH",
|
|
"TUNNEL_CLOSED",
|
|
"GRANTS_CHANGED",
|
|
"UNKNOWN",
|
|
]
|
|
|
|
|
|
def keys(shape: Any) -> set[str]:
|
|
return set(shape.__required_keys__ | shape.__optional_keys__)
|
|
|
|
|
|
def properties(schema: dict | None) -> set[str]:
|
|
return set(
|
|
((schema or {}).get("content", {}).get("application/json", {}).get("schema", {}) or {}).get("properties", {})
|
|
)
|