Workers finalize the signal router once at startup, not once per route (#945)

sanic-ext adds the automatic HEAD and OPTIONS routes one at a time in a
before_server_start listener.  Each route re-finalized the already-finalized
signal router (Sanic.amend), and each finalize registered one more
`sanic.__signal__` route, so a worker rebuilt an ever-growing router about 245
times.  The signal router is now left unfinalized while sanic-ext adds those
routes and finalized once afterwards.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-11-03 14:49:49 -07:00 • committed by Roland
parent 89b84c9765
commit cafa2a2279
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
2 changed files with 34 additions and 0 deletions

View file

@ -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:

View file

@ -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