An internal plugin proxy can name a services-manager service to wake:
"proxy": {"internal": true, "wake": {"service": "music-dl", "holdMinutes": 15}}.
A stopped container has no Docker DNS entry, so a call on its name fails
with httpx.ConnectError before it reaches anything.
- manifest: proxy.wake = {service (^[a-z0-9][a-z0-9_.-]{0,62}$),
holdMinutes (int 1..240, default 15)}, refused without internal: true;
out["proxy"]["wake"] is None when absent. In the approval fingerprint only
when declared (all 42 hub plugins keep theirs); the capability line says
which service it wakes.
- proxy: forward() / open_stream() (and so run_inspect) first POST
$SERVICES_MANAGER_URL/api/services/<svc>/wake?hold=<min>&wait=60&trigger=cli
(default http://services-manager:8080, 70 s timeout); one wake per service
per 60 s, a 2xx answer cached, concurrent calls share one wake (an
asyncio.Lock per service and loop). A ConnectError forces a wake past the
cache and retries once (a streamed upload only if none of its body was
read). services-manager down or refusing is logged, never fails the call.
- tests: backend/test_plugin_proxy_wake.py (12 cases).
- docs/plugins.md: the proxy.wake section + the tool proxy line.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
278 lines
11 KiB
Python
278 lines
11 KiB
Python
"""``proxy.wake``: the plugin proxy wakes a Dynamic service of the homelab's
|
|
services-manager before an internal call, throttled to one wake per service
|
|
per minute, and once more (then retries) when the call can't connect."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
import httpx
|
|
|
|
import main
|
|
from plugins import proxy as proxy_mod
|
|
from plugins.manifest import ManifestError, capability_fingerprint, validate_manifest
|
|
from plugins.proxy import ProxyError, forward, open_stream
|
|
from plugins.store import OWNER_UID, PluginStore
|
|
|
|
BASE = {
|
|
"schema": 1,
|
|
"id": "music",
|
|
"name": "Music",
|
|
"proxy": {
|
|
"baseUrl": "http://music-dl:8080",
|
|
"internal": True,
|
|
"allow": [{"method": "GET", "path": "^api/.*$"}, {"method": "POST", "path": "^api/jobs$"}],
|
|
},
|
|
}
|
|
|
|
|
|
def _manifest(**proxy_extra) -> dict:
|
|
mf = json.loads(json.dumps(BASE))
|
|
mf["proxy"].update(proxy_extra)
|
|
return mf
|
|
|
|
|
|
def _write(root: pathlib.Path, mf: dict) -> pathlib.Path:
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
(root / "plugin.json").write_text(json.dumps(mf), encoding="utf-8")
|
|
return root
|
|
|
|
|
|
def _validate(mf: dict) -> dict:
|
|
with tempfile.TemporaryDirectory() as td:
|
|
return validate_manifest(_write(pathlib.Path(td) / mf["id"], mf))
|
|
|
|
|
|
class TestWakeManifest(unittest.TestCase):
|
|
def test_cleaned_shape_and_default_hold(self):
|
|
mf = _validate(_manifest(wake={"service": "music-dl"}))
|
|
self.assertEqual(mf["proxy"]["wake"], {"service": "music-dl", "holdMinutes": 15})
|
|
mf = _validate(_manifest(wake={"service": "music-dl", "holdMinutes": 240}))
|
|
self.assertEqual(mf["proxy"]["wake"]["holdMinutes"], 240)
|
|
self.assertIsNone(_validate(_manifest())["proxy"]["wake"])
|
|
|
|
def test_refuses_wake_without_internal(self):
|
|
with self.assertRaises(ManifestError) as ctx:
|
|
_validate(_manifest(baseUrl="https://api.example.test", internal=False,
|
|
wake={"service": "music-dl"}))
|
|
self.assertIn("proxy.wake needs internal: true", ctx.exception.errors)
|
|
|
|
def test_refuses_bad_service_and_hold(self):
|
|
for svc in ("", "Music", "-x", "a/b", "music-dl\n", "x" * 64):
|
|
with self.subTest(svc=svc), self.assertRaises(ManifestError):
|
|
_validate(_manifest(wake={"service": svc}))
|
|
for hold in (0, 241, "15", 1.5, True):
|
|
with self.subTest(hold=hold), self.assertRaises(ManifestError):
|
|
_validate(_manifest(wake={"service": "music-dl", "holdMinutes": hold}))
|
|
with self.assertRaises(ManifestError):
|
|
_validate(_manifest(wake="music-dl"))
|
|
|
|
def test_fingerprint_unchanged_without_wake(self):
|
|
# Pinned from main before proxy.wake existed: an installed plugin
|
|
# without it must keep its approval.
|
|
self.assertEqual(capability_fingerprint(_validate(_manifest())), "44dbcafb1695c7d7b7c3fbc4")
|
|
bare = _validate(_manifest())
|
|
woken = _validate(_manifest(wake={"service": "music-dl"}))
|
|
self.assertNotEqual(capability_fingerprint(bare), capability_fingerprint(woken))
|
|
longer = _validate(_manifest(wake={"service": "music-dl", "holdMinutes": 30}))
|
|
self.assertNotEqual(capability_fingerprint(woken), capability_fingerprint(longer))
|
|
|
|
|
|
class _Upstream:
|
|
"""A mock services-manager + music-dl behind one MockTransport."""
|
|
|
|
def __init__(self):
|
|
self.wakes: list[httpx.Request] = []
|
|
self.calls: list[httpx.Request] = []
|
|
self.wake_mode = "ok" # ok | down | 500
|
|
self.connect_fails = 0 # music-dl refuses this many connections first
|
|
self.wake_delay = 0.0
|
|
|
|
async def handler(self, req: httpx.Request) -> httpx.Response:
|
|
if req.url.host == "services-manager":
|
|
self.wakes.append(req)
|
|
if self.wake_delay:
|
|
await asyncio.sleep(self.wake_delay)
|
|
if self.wake_mode == "down":
|
|
raise httpx.ConnectError("Name or service not known", request=req)
|
|
if self.wake_mode == "500":
|
|
return httpx.Response(500, text="boom")
|
|
return httpx.Response(200, json={"name": "music-dl", "ready": True})
|
|
if req.url.host == "music-dl":
|
|
if self.connect_fails > 0:
|
|
self.connect_fails -= 1
|
|
raise httpx.ConnectError("[Errno -2] Name or service not known", request=req)
|
|
self.calls.append(req)
|
|
return httpx.Response(200, json={"ok": True, "path": req.url.path})
|
|
return httpx.Response(404)
|
|
|
|
|
|
class TestProxyWake(unittest.TestCase):
|
|
def setUp(self):
|
|
proxy_mod._wake_ok_at.clear()
|
|
self.td = tempfile.TemporaryDirectory()
|
|
root = pathlib.Path(self.td.name)
|
|
self.store = PluginStore(root / "data")
|
|
self.deps = main.app.state.ai
|
|
self.up = _Upstream()
|
|
|
|
def tearDown(self):
|
|
proxy_mod._wake_ok_at.clear()
|
|
self.td.cleanup()
|
|
|
|
def _rec(self, mf: dict) -> dict:
|
|
pdir = _write(pathlib.Path(self.td.name) / "src" / mf["id"], mf)
|
|
self.store.install(OWNER_UID, str(pdir), is_owner=True, approve=True)
|
|
return self.store.get_raw(OWNER_UID, mf["id"])
|
|
|
|
def _run(self, coro_fn):
|
|
async def go():
|
|
async with httpx.AsyncClient(transport=httpx.MockTransport(self.up.handler)) as client:
|
|
return await coro_fn(client)
|
|
return asyncio.run(go())
|
|
|
|
def _get(self, client, rec, path="api/status"):
|
|
return forward(client, self.deps, self.store, OWNER_UID, rec, method="GET", rel_path=path)
|
|
|
|
def test_wakes_once_then_throttles(self):
|
|
rec = self._rec(_manifest(wake={"service": "music-dl", "holdMinutes": 20}))
|
|
|
|
async def go(client):
|
|
for _ in range(3):
|
|
st, _, raw = await self._get(client, rec)
|
|
self.assertEqual(st, 200)
|
|
self._run(go)
|
|
self.assertEqual(len(self.up.wakes), 1)
|
|
w = self.up.wakes[0]
|
|
self.assertEqual(w.method, "POST")
|
|
self.assertEqual(str(w.url.copy_with(query=None)),
|
|
"http://services-manager:8080/api/services/music-dl/wake")
|
|
self.assertEqual(dict(w.url.params), {"hold": "20", "wait": "60", "trigger": "cli"})
|
|
self.assertEqual(len(self.up.calls), 3)
|
|
|
|
# A minute later the next call wakes (and extends the hold) again.
|
|
proxy_mod._wake_ok_at["music-dl"] -= 61
|
|
self._run(lambda c: self._get(c, rec))
|
|
self.assertEqual(len(self.up.wakes), 2)
|
|
|
|
def test_concurrent_calls_share_one_wake(self):
|
|
rec = self._rec(_manifest(wake={"service": "music-dl"}))
|
|
self.up.wake_delay = 0.05
|
|
|
|
async def go(client):
|
|
res = await asyncio.gather(*(self._get(client, rec) for _ in range(5)))
|
|
self.assertEqual([r[0] for r in res], [200] * 5)
|
|
self._run(go)
|
|
self.assertEqual(len(self.up.wakes), 1)
|
|
|
|
def test_connect_error_forces_a_wake_and_retries_once(self):
|
|
rec = self._rec(_manifest(wake={"service": "music-dl"}))
|
|
|
|
async def go(client):
|
|
await self._get(client, rec) # wakes, caches
|
|
self.up.connect_fails = 1 # went back to sleep meanwhile
|
|
st, _, raw = await self._get(client, rec, "api/library")
|
|
self.assertEqual(st, 200)
|
|
self.assertEqual(json.loads(raw)["path"], "/api/library")
|
|
self._run(go)
|
|
self.assertEqual(len(self.up.wakes), 2) # the throttle was bypassed
|
|
self.assertEqual(len(self.up.calls), 2)
|
|
|
|
def test_retries_only_once(self):
|
|
rec = self._rec(_manifest(wake={"service": "music-dl"}))
|
|
self.up.connect_fails = 5
|
|
|
|
async def go(client):
|
|
with self.assertRaises(ProxyError) as ctx:
|
|
await self._get(client, rec)
|
|
self.assertEqual(ctx.exception.status, 502)
|
|
self._run(go)
|
|
self.assertEqual(self.up.connect_fails, 3) # first try + one retry
|
|
self.assertEqual(len(self.up.wakes), 2)
|
|
|
|
def test_services_manager_down_does_not_fail_the_call(self):
|
|
rec = self._rec(_manifest(wake={"service": "music-dl"}))
|
|
for mode in ("down", "500"):
|
|
with self.subTest(mode=mode):
|
|
proxy_mod._wake_ok_at.clear()
|
|
self.up.wakes.clear()
|
|
self.up.wake_mode = mode
|
|
|
|
async def go(client):
|
|
for _ in range(2):
|
|
st, _, _ = await self._get(client, rec)
|
|
self.assertEqual(st, 200)
|
|
with self.assertLogs("plugins.proxy", level="WARNING"):
|
|
self._run(go)
|
|
# A failed wake isn't cached: each call asks again.
|
|
self.assertEqual(len(self.up.wakes), 2)
|
|
self.assertNotIn("music-dl", proxy_mod._wake_ok_at)
|
|
|
|
def test_no_wake_declared_never_calls_services_manager(self):
|
|
rec = self._rec(_manifest())
|
|
self._run(lambda c: self._get(c, rec))
|
|
self.up.connect_fails = 1
|
|
|
|
async def go(client):
|
|
with self.assertRaises(ProxyError) as ctx:
|
|
await self._get(client, rec)
|
|
self.assertEqual(ctx.exception.status, 502)
|
|
self._run(go)
|
|
self.assertEqual(self.up.wakes, [])
|
|
|
|
def test_services_manager_url_from_env(self):
|
|
rec = self._rec(_manifest(wake={"service": "music-dl"}))
|
|
seen = []
|
|
|
|
async def handler(req):
|
|
seen.append(str(req.url.copy_with(query=None)))
|
|
return httpx.Response(200, json={"ready": True})
|
|
|
|
async def go():
|
|
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
|
|
await self._get(client, rec)
|
|
with patch.dict(os.environ, {"SERVICES_MANAGER_URL": "http://sm.test:9000/"}):
|
|
asyncio.run(go())
|
|
self.assertEqual(seen[0], "http://sm.test:9000/api/services/music-dl/wake")
|
|
|
|
def test_open_stream_wakes_and_retries(self):
|
|
rec = self._rec(_manifest(stream=True, wake={"service": "music-dl"}))
|
|
|
|
def stream(client, **kw):
|
|
return open_stream(client, self.deps, self.store, OWNER_UID, rec, **kw)
|
|
|
|
async def go(client):
|
|
resp, _, _, _ = await stream(client, method="GET", rel_path="api/file.mp3")
|
|
self.assertEqual(resp.status_code, 200)
|
|
await resp.aclose()
|
|
self.assertEqual(len(self.up.wakes), 1)
|
|
|
|
self.up.connect_fails = 1
|
|
resp, _, _, _ = await stream(client, method="GET", rel_path="api/file.mp3")
|
|
self.assertEqual(resp.status_code, 200)
|
|
await resp.aclose()
|
|
self.assertEqual(len(self.up.wakes), 2)
|
|
|
|
# A body already read can't be sent again: no retry. (MockTransport
|
|
# reads the body before the handler; a real refused connection
|
|
# fails before the body, so a real upload does get its retry.)
|
|
async def body():
|
|
yield b"chunk"
|
|
self.up.connect_fails = 1
|
|
with self.assertRaises(ProxyError) as ctx:
|
|
await stream(client, method="POST", rel_path="api/jobs", body_iter=body())
|
|
self.assertEqual(ctx.exception.status, 502)
|
|
self._run(go)
|
|
self.assertEqual(len(self.up.wakes), 2)
|
|
self.assertEqual(len(self.up.calls), 2)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|