Skip to content

Commit 2a33aa9

Browse files
committed
@GitHK review: rename
1 parent 85703c0 commit 2a33aa9

File tree

11 files changed

+86
-89
lines changed

11 files changed

+86
-89
lines changed

packages/service-library/src/servicelib/db_asyncpg_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ async def create_async_engine_and_database_ready(
3333
"application_name": settings.POSTGRES_CLIENT_NAME,
3434
}
3535

36-
engine: AsyncEngine = create_async_engine(
36+
engine = create_async_engine(
3737
settings.dsn_with_async_sqlalchemy,
3838
pool_size=settings.POSTGRES_MINSIZE,
3939
max_overflow=settings.POSTGRES_MAXSIZE - settings.POSTGRES_MINSIZE,
Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1+
import asyncio
12
import logging
23
from collections.abc import AsyncIterator
34
from enum import Enum
45

5-
from fastapi_lifespan_manager import LifespanManager, State
6+
from fastapi_lifespan_manager import State
67
from servicelib.logging_utils import log_catch, log_context
78
from settings_library.postgres import PostgresSettings
89
from sqlalchemy.ext.asyncio import AsyncEngine
@@ -13,41 +14,41 @@
1314
_logger = logging.getLogger(__name__)
1415

1516

16-
postgres_lifespan_manager = LifespanManager()
17-
18-
19-
class PostgresLifespanStateKeys(str, Enum):
17+
class PostgresLifespanState(str, Enum):
2018
POSTGRES_SETTINGS = "postgres_settings"
2119
POSTGRES_ASYNC_ENGINE = "postgres.async_engine"
2220

2321

2422
class PostgresConfigurationError(LifespanOnStartupError):
25-
msg_template = "Invalid postgres settings [={pg_settings}] on startup. Note that postgres cannot be disabled using settings"
23+
msg_template = "Invalid postgres settings [={settings}] on startup. Note that postgres cannot be disabled using settings"
24+
2625

26+
def create_input_state(settings: PostgresSettings) -> State:
27+
return {PostgresLifespanState.POSTGRES_SETTINGS: settings}
2728

28-
@postgres_lifespan_manager.add
29-
async def setup_postgres_database(_, state: State) -> AsyncIterator[State]:
29+
30+
async def postgres_database_lifespan(_, state: State) -> AsyncIterator[State]:
3031

3132
with log_context(_logger, logging.INFO, f"{__name__}"):
3233

33-
pg_settings: PostgresSettings | None = state[
34-
PostgresLifespanStateKeys.POSTGRES_SETTINGS
35-
]
34+
settings = state[PostgresLifespanState.POSTGRES_SETTINGS]
3635

37-
if pg_settings is None or not isinstance(pg_settings, PostgresSettings):
38-
raise PostgresConfigurationError(pg_settings=pg_settings, module="postgres")
36+
if settings is None or not isinstance(settings, PostgresSettings):
37+
raise PostgresConfigurationError(settings=settings)
3938

40-
assert isinstance(pg_settings, PostgresSettings) # nosec
39+
assert isinstance(settings, PostgresSettings) # nosec
4140

41+
# connect to database
4242
async_engine: AsyncEngine = await create_async_engine_and_database_ready(
43-
pg_settings
43+
settings
4444
)
4545

4646
try:
47+
4748
yield {
48-
PostgresLifespanStateKeys.POSTGRES_ASYNC_ENGINE: async_engine,
49+
PostgresLifespanState.POSTGRES_ASYNC_ENGINE: async_engine,
4950
}
5051

5152
finally:
5253
with log_catch(_logger, reraise=False):
53-
await async_engine.dispose()
54+
await asyncio.wait_for(async_engine.dispose(), timeout=10)

packages/service-library/tests/fastapi/test_lifespan_utils.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ async def cache_lifespan(app: FastAPI) -> AsyncIterator[State]:
5656

5757

5858
@pytest.fixture
59-
def postgres_lifespan_mng() -> LifespanManager:
59+
def postgres_lifespan() -> LifespanManager:
6060
lifespan_manager = LifespanManager()
6161

6262
@lifespan_manager.add
@@ -70,8 +70,8 @@ async def _setup_postgres_async_engine(_, state: State) -> AsyncIterator[State]:
7070
with log_context(logging.INFO, "postgres_async_engine"):
7171
# pass state to children
7272

73-
state["postgres"].update(aengine="Some Async Engine")
74-
yield state
73+
current = state["postgres"]
74+
yield {"postgres": {"aengine": "Some Async Engine", **current}}
7575

7676
return lifespan_manager
7777

@@ -94,13 +94,13 @@ async def _setup_rabbitmq(app: FastAPI) -> AsyncIterator[State]:
9494

9595

9696
async def test_app_lifespan_composition(
97-
postgres_lifespan_mng: LifespanManager, rabbitmq_lifespan: LifespanManager
97+
postgres_lifespan: LifespanManager, rabbitmq_lifespan: LifespanManager
9898
):
9999
# The app has its own database and rpc-server to initialize
100100
# this is how you connect the lifespans pre-defined in servicelib
101101

102-
@postgres_lifespan_mng.add
103-
async def setup_database(app: FastAPI, state: State) -> AsyncIterator[State]:
102+
@postgres_lifespan.add
103+
async def database_lifespan(app: FastAPI, state: State) -> AsyncIterator[State]:
104104

105105
with log_context(logging.INFO, "app database"):
106106
assert state["postgres"] == {
@@ -119,7 +119,7 @@ async def setup_database(app: FastAPI, state: State) -> AsyncIterator[State]:
119119
assert app.state.database_engine
120120

121121
@rabbitmq_lifespan.add
122-
async def setup_rpc_server(app: FastAPI, state: State) -> AsyncIterator[State]:
122+
async def rpc_service_lifespan(app: FastAPI, state: State) -> AsyncIterator[State]:
123123
with log_context(logging.INFO, "app rpc-server"):
124124
assert "rabbitmq_rpc_server" in state
125125

@@ -129,7 +129,7 @@ async def setup_rpc_server(app: FastAPI, state: State) -> AsyncIterator[State]:
129129

130130
# Composes lifepans
131131
app_lifespan = LifespanManager()
132-
app_lifespan.include(postgres_lifespan_mng)
132+
app_lifespan.include(postgres_lifespan)
133133
app_lifespan.include(rabbitmq_lifespan)
134134

135135
app = FastAPI(lifespan=app_lifespan)
@@ -165,7 +165,7 @@ async def setup_rpc_server(app: FastAPI, state: State) -> AsyncIterator[State]:
165165

166166

167167
@pytest.fixture
168-
def failing_lifespan_manager(mocker: MockerFixture):
168+
def failing_lifespan_manager(mocker: MockerFixture) -> dict[str, Any]:
169169
startup_step = mocker.MagicMock()
170170
shutdown_step = mocker.MagicMock()
171171
handle_error = mocker.MagicMock()
@@ -174,8 +174,8 @@ def raise_error():
174174
msg = "failing module"
175175
raise RuntimeError(msg)
176176

177-
async def setup_failing_on_startup(app: FastAPI) -> AsyncIterator[State]:
178-
_name = setup_failing_on_startup.__name__
177+
async def lifespan_failing_on_startup(app: FastAPI) -> AsyncIterator[State]:
178+
_name = lifespan_failing_on_startup.__name__
179179

180180
with log_context(logging.INFO, _name):
181181
try:
@@ -187,8 +187,8 @@ async def setup_failing_on_startup(app: FastAPI) -> AsyncIterator[State]:
187187
yield {}
188188
shutdown_step(_name)
189189

190-
async def setup_failing_on_shutdown(app: FastAPI) -> AsyncIterator[State]:
191-
_name = setup_failing_on_shutdown.__name__
190+
async def lifespan_failing_on_shutdown(app: FastAPI) -> AsyncIterator[State]:
191+
_name = lifespan_failing_on_shutdown.__name__
192192

193193
with log_context(logging.INFO, _name):
194194
startup_step(_name)
@@ -204,16 +204,16 @@ async def setup_failing_on_shutdown(app: FastAPI) -> AsyncIterator[State]:
204204
"startup_step": startup_step,
205205
"shutdown_step": shutdown_step,
206206
"handle_error": handle_error,
207-
"setup_failing_on_startup": setup_failing_on_startup,
208-
"setup_failing_on_shutdown": setup_failing_on_shutdown,
207+
"lifespan_failing_on_startup": lifespan_failing_on_startup,
208+
"lifespan_failing_on_shutdown": lifespan_failing_on_shutdown,
209209
}
210210

211211

212212
async def test_app_lifespan_with_error_on_startup(
213213
failing_lifespan_manager: dict[str, Any],
214214
):
215215
app_lifespan = LifespanManager()
216-
app_lifespan.add(failing_lifespan_manager["setup_failing_on_startup"])
216+
app_lifespan.add(failing_lifespan_manager["lifespan_failing_on_startup"])
217217
app = FastAPI(lifespan=app_lifespan)
218218

219219
with pytest.raises(LifespanOnStartupError) as err_info:
@@ -225,8 +225,8 @@ async def test_app_lifespan_with_error_on_startup(
225225
assert not failing_lifespan_manager["startup_step"].called
226226
assert not failing_lifespan_manager["shutdown_step"].called
227227
assert exception.error_context() == {
228-
"module": "setup_failing_on_startup",
229-
"message": "Failed during startup of setup_failing_on_startup",
228+
"module": "lifespan_failing_on_startup",
229+
"message": "Failed during startup of lifespan_failing_on_startup",
230230
"code": "RuntimeError.LifespanError.LifespanOnStartupError",
231231
}
232232

@@ -235,7 +235,7 @@ async def test_app_lifespan_with_error_on_shutdown(
235235
failing_lifespan_manager: dict[str, Any],
236236
):
237237
app_lifespan = LifespanManager()
238-
app_lifespan.add(failing_lifespan_manager["setup_failing_on_shutdown"])
238+
app_lifespan.add(failing_lifespan_manager["lifespan_failing_on_shutdown"])
239239
app = FastAPI(lifespan=app_lifespan)
240240

241241
with pytest.raises(LifespanOnShutdownError) as err_info:
@@ -247,7 +247,7 @@ async def test_app_lifespan_with_error_on_shutdown(
247247
assert failing_lifespan_manager["startup_step"].called
248248
assert not failing_lifespan_manager["shutdown_step"].called
249249
assert exception.error_context() == {
250-
"module": "setup_failing_on_shutdown",
251-
"message": "Failed during shutdown of setup_failing_on_shutdown",
250+
"module": "lifespan_failing_on_shutdown",
251+
"message": "Failed during shutdown of lifespan_failing_on_shutdown",
252252
"code": "RuntimeError.LifespanError.LifespanOnShutdownError",
253253
}

packages/service-library/tests/fastapi/test_postgres_lifespan.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818
from pytest_simcore.helpers.typing_env import EnvVarsDict
1919
from servicelib.fastapi.postgres_lifespan import (
2020
PostgresConfigurationError,
21-
PostgresLifespanStateKeys,
22-
postgres_lifespan_manager,
21+
PostgresLifespanState,
22+
postgres_database_lifespan,
2323
)
2424
from settings_library.application import BaseApplicationSettings
2525
from settings_library.postgres import PostgresSettings
@@ -58,25 +58,26 @@ async def my_app_settings(app: FastAPI) -> AsyncIterator[State]:
5858
app.state.settings = AppSettings.create_from_envs()
5959

6060
yield {
61-
PostgresLifespanStateKeys.POSTGRES_SETTINGS: app.state.settings.CATALOG_POSTGRES
61+
PostgresLifespanState.POSTGRES_SETTINGS: app.state.settings.CATALOG_POSTGRES
6262
}
6363

6464
async def my_database_setup(app: FastAPI, state: State) -> AsyncIterator[State]:
65-
app.state.my_db_engine = state[PostgresLifespanStateKeys.POSTGRES_ASYNC_ENGINE]
65+
app.state.my_db_engine = state[PostgresLifespanState.POSTGRES_ASYNC_ENGINE]
6666

6767
yield {}
6868

6969
# compose lifespans
7070
app_lifespan = LifespanManager()
7171
app_lifespan.add(my_app_settings)
7272

73-
postgres_lifespan_manager.add(my_database_setup)
74-
app_lifespan.include(postgres_lifespan_manager)
73+
# potsgres
74+
app_lifespan.add(postgres_database_lifespan)
75+
app_lifespan.add(my_database_setup)
7576

7677
return app_lifespan
7778

7879

79-
async def test_setup_postgres_database_in_an_app(
80+
async def test_lifespan_postgres_database_in_an_app(
8081
is_pdb_enabled: bool,
8182
app_environment: EnvVarsDict,
8283
mock_create_async_engine_and_database_ready: MockType,
@@ -97,14 +98,14 @@ async def test_setup_postgres_database_in_an_app(
9798

9899
# Verify that the async engine is in the lifespan manager state
99100
assert (
100-
PostgresLifespanStateKeys.POSTGRES_ASYNC_ENGINE
101+
PostgresLifespanState.POSTGRES_ASYNC_ENGINE
101102
in asgi_manager._state # noqa: SLF001
102103
)
103104
assert app.state.my_db_engine
104105
assert (
105106
app.state.my_db_engine
106107
== asgi_manager._state[ # noqa: SLF001
107-
PostgresLifespanStateKeys.POSTGRES_ASYNC_ENGINE
108+
PostgresLifespanState.POSTGRES_ASYNC_ENGINE
108109
]
109110
)
110111

@@ -118,20 +119,20 @@ async def test_setup_postgres_database_in_an_app(
118119
async_engine.dispose.assert_called_once()
119120

120121

121-
async def test_setup_postgres_database_dispose_engine_on_failure(
122+
async def test_lifespan_postgres_database_dispose_engine_on_failure(
122123
is_pdb_enabled: bool,
123124
app_environment: EnvVarsDict,
124125
mock_create_async_engine_and_database_ready: MockType,
125126
app_lifespan: LifespanManager,
126127
):
127-
expected_msg = "my_faulty_setup error"
128+
expected_msg = "my_faulty_lifespan error"
128129

129130
def raise_error():
130131
raise RuntimeError(expected_msg)
131132

132133
@app_lifespan.add
133-
async def my_faulty_setup(app: FastAPI, state: State) -> AsyncIterator[State]:
134-
assert PostgresLifespanStateKeys.POSTGRES_ASYNC_ENGINE in state
134+
async def my_faulty_lifespan(app: FastAPI, state: State) -> AsyncIterator[State]:
135+
assert PostgresLifespanState.POSTGRES_ASYNC_ENGINE in state
135136
raise_error()
136137
yield {}
137138

@@ -154,14 +155,13 @@ async def test_setup_postgres_database_with_empty_pg_settings(
154155
is_pdb_enabled: bool,
155156
):
156157
async def my_app_settings(app: FastAPI) -> AsyncIterator[State]:
157-
yield {PostgresLifespanStateKeys.POSTGRES_SETTINGS: None}
158+
yield {PostgresLifespanState.POSTGRES_SETTINGS: None}
158159

159-
app_lifespan_manager = LifespanManager()
160-
app_lifespan_manager.add(my_app_settings)
161-
162-
app_lifespan_manager.include(postgres_lifespan_manager)
160+
app_lifespan = LifespanManager()
161+
app_lifespan.add(my_app_settings)
162+
app_lifespan.add(postgres_database_lifespan)
163163

164-
app = FastAPI(lifespan=app_lifespan_manager)
164+
app = FastAPI(lifespan=app_lifespan)
165165

166166
with pytest.raises(PostgresConfigurationError, match="postgres cannot be disabled"):
167167
async with ASGILifespanManager(

services/catalog/src/simcore_service_catalog/api/rpc/routes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
_logger = logging.getLogger(__name__)
1212

1313

14-
async def setup_rpc_api_routes(app: FastAPI) -> AsyncIterator[State]:
14+
async def rpc_api_lifespan(app: FastAPI) -> AsyncIterator[State]:
1515
rpc_server = get_rabbitmq_rpc_server(app)
1616
await rpc_server.register_router(_services.router, CATALOG_RPC_NAMESPACE, app)
1717
try:

services/catalog/src/simcore_service_catalog/core/background_tasks.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ async def stop_registry_sync_task(app: FastAPI) -> None:
236236
_logger.info("registry syncing task stopped")
237237

238238

239-
async def setup_background_task(app: FastAPI) -> AsyncIterator[State]:
239+
async def background_task_lifespan(app: FastAPI) -> AsyncIterator[State]:
240240
await start_registry_sync_task(app)
241241
try:
242242
yield {}

0 commit comments

Comments
 (0)