Skip to content

Commit 03ebdb3

Browse files
committed
🎨 Refactor: Introduce Final app keys for various components in the web server
1 parent fbd326a commit 03ebdb3

File tree

26 files changed

+130
-37
lines changed

26 files changed

+130
-37
lines changed

packages/service-library/src/servicelib/aiohttp/aiopg_utils.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
1-
""" Holderplace for random helpers using aiopg
1+
"""Holderplace for random helpers using aiopg
22
3-
- Drop here functions/constants that at that time does
4-
not fit in any of the setups. Then, they can be moved and
5-
refactor when new abstractions are used in place.
3+
- Drop here functions/constants that at that time does
4+
not fit in any of the setups. Then, they can be moved and
5+
refactor when new abstractions are used in place.
66
7-
- aiopg is used as a client sdk to interact asynchronously with postgres service
7+
- aiopg is used as a client sdk to interact asynchronously with postgres service
88
9-
SEE for aiopg: https://aiopg.readthedocs.io/en/stable/sa.html
10-
SEE for underlying psycopg: http://initd.org/psycopg/docs/module.html
11-
SEE for extra keywords: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
9+
SEE for aiopg: https://aiopg.readthedocs.io/en/stable/sa.html
10+
SEE for underlying psycopg: http://initd.org/psycopg/docs/module.html
11+
SEE for extra keywords: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
1212
"""
1313

1414
# TODO: Towards implementing https://github.com/ITISFoundation/osparc-simcore/issues/1195
1515
# TODO: deprecate this module. Move utils into retry_policies, simcore_postgres_database.utils_aiopg
1616

1717
import logging
18+
from typing import Final
1819

1920
import sqlalchemy as sa
2021
from aiohttp import web
@@ -31,6 +32,8 @@
3132

3233
log = logging.getLogger(__name__)
3334

35+
APP_AIOPG_ENGINE_KEY: Final = web.AppKey("APP_AIOPG_ENGINE_KEY", Engine)
36+
3437

3538
async def raise_if_not_responsive(engine: Engine):
3639
async with engine.acquire() as conn:

packages/service-library/src/servicelib/aiohttp/application_keys.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
""" Namespace to keep all application storage keys
1+
"""Namespace to keep all application storage keys
22
33
Unique keys to identify stored data
44
Naming convention accounts for the storage scope: application, request, response, configuration and/or resources
@@ -8,18 +8,21 @@
88
99
See https://aiohttp.readthedocs.io/en/stable/web_advanced.html#data-sharing-aka-no-singletons-please
1010
"""
11+
1112
from typing import Final
1213

13-
# REQUIREMENTS:
14-
# - guarantees all keys are unique
15-
# - one place for all common keys
16-
# - hierarchical classification
14+
from aiohttp import web
15+
16+
# APPLICATION's CONTEXT KEYS
17+
18+
# NOTE: use these keys to store/retrieve data from aiohttp.web.Application
19+
# SEE https://docs.aiohttp.org/en/stable/web_quickstart.html#aiohttp-web-app-key
1720

1821
#
1922
# web.Application keys, i.e. app[APP_*_KEY]
2023
#
21-
APP_CONFIG_KEY: Final[str] = f"{__name__ }.config"
22-
APP_SETTINGS_KEY: Final[str] = f"{__name__ }.settings"
24+
APP_CONFIG_KEY = web.AppKey("APP_CONFIG_KEY", dict[str, object])
25+
APP_SETTINGS_KEY = web.AppKey("APP_SETTINGS_KEY", object)
2326

2427
APP_AIOPG_ENGINE_KEY: Final[str] = f"{__name__ }.aiopg_engine"
2528

packages/service-library/src/servicelib/aiohttp/client_session.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
get_http_client_request_aiohttp_sock_connect_timeout,
1010
get_http_client_request_total_timeout,
1111
)
12-
from .application_keys import APP_CLIENT_SESSION_KEY
12+
13+
APP_CLIENT_SESSION_KEY: web.AppKey[ClientSession] = web.AppKey("APP_CLIENT_SESSION_KEY")
1314

1415

1516
async def persistent_client_session(app: web.Application) -> AsyncGenerator[None, None]:

packages/service-library/src/servicelib/aiohttp/docker_utils.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import logging
2+
from typing import Final
23

4+
import aiodocker
35
import aiohttp
6+
from aiohttp import web
47
from models_library.docker import DockerGenericTag
58
from pydantic import TypeAdapter, ValidationError
69
from settings_library.docker_registry import RegistrySettings
@@ -18,6 +21,8 @@
1821

1922
_logger = logging.getLogger(__name__)
2023

24+
APP_DOCKER_ENGINE_KEY: Final = web.AppKey("APP_DOCKER_ENGINE_KEY", aiodocker.Docker)
25+
2126

2227
async def retrieve_image_layer_information(
2328
image: DockerGenericTag, registry_settings: RegistrySettings

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,17 @@
66
running task.
77
"""
88

9+
from typing import Final
10+
11+
from aiohttp import web
12+
913
from ._manager import get_long_running_manager
1014
from ._server import setup, start_long_running_task
1115

16+
APP_LONG_RUNNING_TASKS_KEY: Final = web.AppKey(
17+
"APP_LONG_RUNNING_TASKS_KEY", dict[str, object]
18+
)
19+
1220
__all__: tuple[str, ...] = (
1321
"get_long_running_manager",
1422
"setup",

packages/service-library/src/servicelib/aiohttp/monitor_slow_callbacks.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
import asyncio.events
22
import sys
33
import time
4+
from typing import Final
45

6+
from aiohttp import web
57
from pyinstrument import Profiler
68

79
from .incidents import LimitedOrderedStack, SlowCallback
810

11+
APP_SLOW_CALLBACKS_MONITOR_KEY: Final = web.AppKey(
12+
"APP_SLOW_CALLBACKS_MONITOR_KEY", LimitedOrderedStack[SlowCallback]
13+
)
14+
915

1016
def enable(
1117
slow_duration_secs: float, incidents: LimitedOrderedStack[SlowCallback]

packages/service-library/src/servicelib/aiohttp/monitoring.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
_logger = logging.getLogger(__name__)
2929

3030
_PROMETHEUS_METRICS: Final[str] = f"{__name__}.prometheus_metrics" # noqa: N816
31+
APP_MONITORING_NAMESPACE_KEY: Final = web.AppKey("APP_MONITORING_NAMESPACE_KEY", str)
3132

3233

3334
def get_collector_registry(app: web.Application) -> CollectorRegistry:

packages/service-library/src/servicelib/aiohttp/observer.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import logging
77
from collections import defaultdict
88
from collections.abc import Callable
9+
from typing import Final
910

1011
from aiohttp import web
1112

@@ -16,6 +17,9 @@
1617

1718

1819
_APP_OBSERVER_EVENTS_REGISTRY_KEY = "{__name__}.event_registry"
20+
APP_FIRE_AND_FORGET_TASKS_KEY: Final = web.AppKey(
21+
"APP_FIRE_AND_FORGET_TASKS_KEY", set[object]
22+
)
1923

2024

2125
class ObserverRegistryNotFoundError(RuntimeError): ...

packages/service-library/src/servicelib/aiohttp/requests_validation.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import json.decoder
1111
from collections.abc import Iterator
1212
from contextlib import contextmanager
13-
from typing import TypeVar
13+
from typing import Final, TypeVar
1414

1515
from aiohttp import web
1616
from common_library.user_messages import user_message
@@ -23,6 +23,10 @@
2323
ModelClass = TypeVar("ModelClass", bound=BaseModel)
2424
ModelOrListOrDictType = TypeVar("ModelOrListOrDictType", bound=BaseModel | list | dict)
2525

26+
APP_JSON_SCHEMA_SPECS_KEY: Final = web.AppKey(
27+
"APP_JSON_SCHEMA_SPECS_KEY", dict[str, object]
28+
)
29+
2630

2731
@contextmanager
2832
def handle_validation_as_http_error(

packages/service-library/src/servicelib/aiohttp/rest_middlewares.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import logging
77
from collections.abc import Awaitable, Callable
8-
from typing import Any
8+
from typing import Any, Final
99

1010
from aiohttp import web
1111
from aiohttp.web_exceptions import HTTPError
@@ -298,3 +298,8 @@ def append_rest_middlewares(
298298
"""Helper that appends rest-middlewares in the correct order"""
299299
app.middlewares.append(error_middleware_factory(api_version))
300300
app.middlewares.append(envelope_middleware_factory(api_version))
301+
302+
303+
APP_JSONSCHEMA_SPECS_KEY: Final = web.AppKey(
304+
"APP_JSONSCHEMA_SPECS_KEY", dict[str, object]
305+
)

0 commit comments

Comments
 (0)