Skip to content

Commit 5199e38

Browse files
authored
♻️ Refactor: migrate more aiohttp app keys to type-safe web.AppKey (follow up) (#8452)
1 parent 6b176ba commit 5199e38

File tree

13 files changed

+77
-61
lines changed

13 files changed

+77
-61
lines changed
Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
11
from . import server
2+
from ._request import LONG_RUNNING_TASKS_CONTEXT_REQKEY
23

3-
__all__ = ("server",)
4+
__all__: tuple[str, ...] = (
5+
"server",
6+
"LONG_RUNNING_TASKS_CONTEXT_REQKEY",
7+
)

packages/service-library/src/servicelib/aiohttp/long_running_tasks/_constants.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,3 @@
33
from pydantic import PositiveFloat
44

55
MINUTE: Final[PositiveFloat] = 60
6-
APP_LONG_RUNNING_MANAGER_KEY: Final[str] = (
7-
f"{__name__ }.long_running_tasks.tasks_manager"
8-
)
9-
RQT_LONG_RUNNING_TASKS_CONTEXT_KEY: Final[str] = (
10-
f"{__name__}.long_running_tasks.context"
11-
)
Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1+
from typing import Final
2+
13
from aiohttp import web
24

35
from ...long_running_tasks.manager import LongRunningManager
46
from ...long_running_tasks.models import TaskContext
5-
from ._constants import APP_LONG_RUNNING_MANAGER_KEY
67
from ._request import get_task_context
78

89

@@ -13,6 +14,10 @@ def get_task_context(request: web.Request) -> TaskContext:
1314
return get_task_context(request)
1415

1516

17+
LONG_RUNNING_MANAGER_APPKEY: Final = web.AppKey(
18+
"LONG_RUNNING_MANAGER", AiohttpLongRunningManager
19+
)
20+
21+
1622
def get_long_running_manager(app: web.Application) -> AiohttpLongRunningManager:
17-
output: AiohttpLongRunningManager = app[APP_LONG_RUNNING_MANAGER_KEY]
18-
return output
23+
return app[LONG_RUNNING_MANAGER_APPKEY]
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
from typing import Any
1+
from typing import Any, Final
22

33
from aiohttp import web
44

5-
from ._constants import RQT_LONG_RUNNING_TASKS_CONTEXT_KEY
5+
LONG_RUNNING_TASKS_CONTEXT_REQKEY: Final = f"{__name__}.long_running_tasks.context"
66

77

88
def get_task_context(request: web.Request) -> dict[str, Any]:
9-
output: dict[str, Any] = request[RQT_LONG_RUNNING_TASKS_CONTEXT_KEY]
10-
return output
9+
ctx: dict[str, Any] = request[LONG_RUNNING_TASKS_CONTEXT_REQKEY]
10+
return ctx

packages/service-library/src/servicelib/aiohttp/long_running_tasks/_server.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,15 @@
2929
)
3030
from ..typing_extension import Handler
3131
from . import _routes
32-
from ._constants import (
33-
APP_LONG_RUNNING_MANAGER_KEY,
34-
RQT_LONG_RUNNING_TASKS_CONTEXT_KEY,
35-
)
3632
from ._error_handlers import base_long_running_error_handler
37-
from ._manager import AiohttpLongRunningManager, get_long_running_manager
33+
from ._manager import (
34+
LONG_RUNNING_MANAGER_APPKEY,
35+
AiohttpLongRunningManager,
36+
get_long_running_manager,
37+
)
38+
from ._request import (
39+
LONG_RUNNING_TASKS_CONTEXT_REQKEY,
40+
)
3841

3942

4043
def _no_ops_decorator(handler: Handler):
@@ -44,7 +47,7 @@ def _no_ops_decorator(handler: Handler):
4447
def _no_task_context_decorator(handler: Handler):
4548
@wraps(handler)
4649
async def _wrap(request: web.Request):
47-
request[RQT_LONG_RUNNING_TASKS_CONTEXT_KEY] = {}
50+
request[LONG_RUNNING_TASKS_CONTEXT_REQKEY] = {}
4851
return await handler(request)
4952

5053
return _wrap
@@ -178,7 +181,7 @@ async def on_cleanup_ctx(app: web.Application) -> AsyncGenerator[None, None]:
178181
app.middlewares.append(base_long_running_error_handler)
179182

180183
# add components to state
181-
app[APP_LONG_RUNNING_MANAGER_KEY] = long_running_manager = (
184+
app[LONG_RUNNING_MANAGER_APPKEY] = long_running_manager = (
182185
AiohttpLongRunningManager(
183186
stale_task_check_interval=stale_task_check_interval,
184187
stale_task_detect_timeout=stale_task_detect_timeout,

packages/service-library/tests/aiohttp/long_running_tasks/test_long_running_tasks_with_task_context.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
from pydantic import TypeAdapter, create_model
2020
from pytest_simcore.helpers.assert_checks import assert_status
2121
from servicelib.aiohttp import long_running_tasks, status
22-
from servicelib.aiohttp.long_running_tasks._server import (
23-
RQT_LONG_RUNNING_TASKS_CONTEXT_KEY,
22+
from servicelib.aiohttp.long_running_tasks._request import (
23+
LONG_RUNNING_TASKS_CONTEXT_REQKEY,
2424
)
2525
from servicelib.aiohttp.requests_validation import parse_request_query_parameters_as
2626
from servicelib.aiohttp.rest_middlewares import append_rest_middlewares
@@ -56,7 +56,7 @@ async def _test_task_context_decorator(
5656
) -> web.StreamResponse:
5757
"""this task context callback tries to get the user_id from the query if available"""
5858
query_param = parse_request_query_parameters_as(query_model, request)
59-
request[RQT_LONG_RUNNING_TASKS_CONTEXT_KEY] = query_param.model_dump()
59+
request[LONG_RUNNING_TASKS_CONTEXT_REQKEY] = query_param.model_dump()
6060
return await handler(request)
6161

6262
return _test_task_context_decorator

services/web/server/src/simcore_service_webserver/long_running_tasks/plugin.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,8 @@
22
from functools import wraps
33

44
from aiohttp import web
5-
from models_library.utils.fastapi_encoders import jsonable_encoder
6-
from servicelib.aiohttp.long_running_tasks._constants import (
7-
RQT_LONG_RUNNING_TASKS_CONTEXT_KEY,
5+
from servicelib.aiohttp.long_running_tasks import (
6+
LONG_RUNNING_TASKS_CONTEXT_REQKEY,
87
)
98
from servicelib.aiohttp.long_running_tasks.server import setup
109
from servicelib.aiohttp.typing_extension import Handler
@@ -31,7 +30,9 @@ async def _test_task_context_decorator(
3130
) -> web.StreamResponse:
3231
"""this task context callback tries to get the user_id from the query if available"""
3332
req_ctx = AuthenticatedRequestContext.model_validate(request)
34-
request[RQT_LONG_RUNNING_TASKS_CONTEXT_KEY] = jsonable_encoder(req_ctx)
33+
request[LONG_RUNNING_TASKS_CONTEXT_REQKEY] = req_ctx.model_dump(
34+
mode="json", by_alias=True
35+
)
3536
return await handler(request)
3637

3738
return _test_task_context_decorator

services/web/server/src/simcore_service_webserver/projects/_permalink_service.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import asyncio
22
import logging
3-
from typing import Protocol, cast
3+
from typing import Final, Protocol
44

55
from aiohttp import web
66
from models_library.api_schemas_webserver.permalinks import ProjectPermalink
@@ -10,7 +10,6 @@
1010
from .exceptions import PermalinkFactoryError, PermalinkNotAllowedError
1111
from .models import ProjectDict
1212

13-
_PROJECT_PERMALINK = f"{__name__}"
1413
_logger = logging.getLogger(__name__)
1514

1615

@@ -24,16 +23,21 @@ async def __call__(
2423
) -> ProjectPermalink: ...
2524

2625

26+
_PROJECT_PERMALINK_FACTORY_APPKEY: Final = web.AppKey(
27+
"PROJECT_PERMALINK_FACTORY", CreateLinkCoroutine
28+
)
29+
30+
2731
def register_factory(app: web.Application, factory_coro: CreateLinkCoroutine):
28-
if _create := app.get(_PROJECT_PERMALINK):
32+
if _create := app.get(_PROJECT_PERMALINK_FACTORY_APPKEY):
2933
msg = f"Permalink factory can only be set once: registered {_create}"
3034
raise PermalinkFactoryError(msg)
31-
app[_PROJECT_PERMALINK] = factory_coro
35+
app[_PROJECT_PERMALINK_FACTORY_APPKEY] = factory_coro
3236

3337

3438
def _get_factory(app: web.Application) -> CreateLinkCoroutine:
35-
if _create := app.get(_PROJECT_PERMALINK):
36-
return cast(CreateLinkCoroutine, _create)
39+
if _create := app.get(_PROJECT_PERMALINK_FACTORY_APPKEY):
40+
return _create
3741

3842
msg = "Undefined permalink factory. Check plugin initialization."
3943
raise PermalinkFactoryError(msg)

services/web/server/src/simcore_service_webserver/resource_manager/_constants.py

Lines changed: 0 additions & 2 deletions
This file was deleted.

services/web/server/src/simcore_service_webserver/resource_manager/plugin.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,15 @@
88
"""
99

1010
import logging
11-
from typing import Final
1211

1312
from aiohttp import web
1413

1514
from ..application_setup import ModuleCategory, app_setup_func
1615
from ..redis import setup_redis
17-
from ._constants import APP_CLIENT_SOCKET_REGISTRY_KEY, APP_RESOURCE_MANAGER_TASKS_KEY
18-
from .registry import RedisResourceRegistry
16+
from .registry import CLIENT_SOCKET_REGISTRY_APPKEY, RedisResourceRegistry
1917

2018
_logger = logging.getLogger(__name__)
2119

22-
APP_RESOURCE_MANAGER_CLIENT_KEY: Final = web.AppKey(
23-
"APP_RESOURCE_MANAGER_CLIENT_KEY", object
24-
)
25-
2620

2721
@app_setup_func(
2822
"simcore_service_webserver.resource_manager",
@@ -33,9 +27,7 @@
3327
def setup_resource_manager(app: web.Application) -> bool:
3428
"""Sets up resource manager subsystem in the application"""
3529

36-
app[APP_RESOURCE_MANAGER_TASKS_KEY] = []
37-
3830
setup_redis(app)
39-
app[APP_CLIENT_SOCKET_REGISTRY_KEY] = RedisResourceRegistry(app)
31+
app[CLIENT_SOCKET_REGISTRY_APPKEY] = RedisResourceRegistry(app)
4032

4133
return True

0 commit comments

Comments
 (0)