diff --git a/wrolpi/api_utils.py b/wrolpi/api_utils.py index 00147edd..c2c0efd5 100644 --- a/wrolpi/api_utils.py +++ b/wrolpi/api_utils.py @@ -10,6 +10,7 @@ from http import HTTPStatus from pathlib import Path from sanic import response, HTTPResponse, Request, Sanic, SanicException +from sanic_ext.config import PRIORITY as SANIC_EXT_PRIORITY from wrolpi.common import Base, get_media_directory, logger, LOGGING_CONFIG from wrolpi.db import RequestDB, no_db_access @@ -40,6 +41,19 @@ os.register_at_fork(after_in_child=_reset_inherited_signal_handlers) # The only Sanic App, this is imported all over. api_app = Sanic(name='api_app', log_config=LOGGING_CONFIG) +# sanic-ext adds the automatic HEAD and OPTIONS routes one at a time in a `before_server_start` listener at +# SANIC_EXT_PRIORITY. Each route re-finalizes the finalized signal router (`Sanic.amend`), so a worker rebuilt it once +# per route (~20s on a Pi 4). Leave it unfinalized while those routes are added, then finalize it once. +@api_app.before_server_start(priority=SANIC_EXT_PRIORITY + 1) +async def unfinalize_signals_for_auto_routes(app: Sanic): + app.signal_router.reset() + + +@api_app.before_server_start(priority=SANIC_EXT_PRIORITY - 1) +async def finalize_signals_after_auto_routes(app: Sanic): + if not app.signal_router.finalized: + app.signalize(app.config.TOUCHUP) + @wraps(response.json) def json_response(*a, **kwargs) -> HTTPResponse: diff --git a/wrolpi/test/test_api_utils.py b/wrolpi/test/test_api_utils.py index ac093a86..4ef71c8e 100644 --- a/wrolpi/test/test_api_utils.py +++ b/wrolpi/test/test_api_utils.py @@ -77,3 +77,23 @@ async def test_stop_per_worker_tasks_without_start(): app = mock.Mock() app.ctx = mock.Mock(spec=[]) # no per_worker_* attributes await stop_per_worker_tasks(app) + + +@pytest.mark.asyncio +async def test_server_start_finalizes_signals_once(test_session, async_client): + """sanic-ext's automatic HEAD and OPTIONS routes must not re-finalize the signal router once per route; each + finalize also left one more `sanic.__signal__` route behind.""" + def finalizes(): + return len([i for i in api_app.signal_router.routes if str(i.path).startswith('sanic.__signal__.')]) + + # Other tests started the shared app before. + before = finalizes() + await async_client.get('/api/echo') + assert finalizes() - before < 10, f'{finalizes() - before} signal router finalizes' + + # The automatic routes still work. + request, response = await async_client.options('/api/status') + assert response.status_code == 204 + assert set(response.headers['allow'].split(',')) == {'GET', 'HEAD', 'OPTIONS'} + request, response = await async_client.head('/api/status') + assert response.status_code == 200