Skip to content

Commit 16c19cb

Browse files
committed
updating db in api module
1 parent 6ef1990 commit 16c19cb

File tree

7 files changed

+37
-40
lines changed

7 files changed

+37
-40
lines changed

services/web/server/src/simcore_service_webserver/garbage_collector/_core_guests.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ async def remove_guest_user_with_all_its_resources(
145145
"""Removes a GUEST user with all its associated projects and S3/MinIO files"""
146146

147147
try:
148-
user_role: UserRole = await get_user_role(app, user_id)
148+
user_role: UserRole = await get_user_role(app, user_id=user_id)
149149
if user_role > UserRole.GUEST:
150150
# NOTE: This acts as a protection barrier to avoid removing resources to more
151151
# priviledge users

services/web/server/src/simcore_service_webserver/garbage_collector/_core_orphans.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ async def _remove_service(
3737
save_service_state = False
3838
else:
3939
try:
40-
if await get_user_role(app, service.user_id) <= UserRole.GUEST:
40+
if await get_user_role(app, user_id=service.user_id) <= UserRole.GUEST:
4141
save_service_state = False
4242
else:
4343
save_service_state = await has_user_project_access_rights(

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ async def stop_node(request: web.Request) -> web.Response:
377377
permission="write",
378378
)
379379

380-
user_role = await get_user_role(request.app, req_ctx.user_id)
380+
user_role = await get_user_role(request.app, user_id=req_ctx.user_id)
381381
if user_role is None or user_role <= UserRole.GUEST:
382382
save_state = False
383383

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,9 @@ async def open_project(request: web.Request) -> web.Response:
109109
project_type: ProjectType = await projects_api.get_project_type(
110110
request.app, path_params.project_id
111111
)
112-
user_role: UserRole = await api.get_user_role(request.app, req_ctx.user_id)
112+
user_role: UserRole = await api.get_user_role(
113+
request.app, user_id=req_ctx.user_id
114+
)
113115
if project_type is ProjectType.TEMPLATE and user_role < UserRole.USER:
114116
# only USERS/TESTERS can do that
115117
raise web.HTTPForbidden(reason="Wrong user role to open/edit a template")

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -592,7 +592,7 @@ async def _start_dynamic_service(
592592
raise
593593

594594
save_state = False
595-
user_role: UserRole = await get_user_role(request.app, user_id)
595+
user_role: UserRole = await get_user_role(request.app, user_id=user_id)
596596
if user_role > UserRole.GUEST:
597597
save_state = await has_user_project_access_rights(
598598
request.app, project_id=project_uuid, user_id=user_id, permission="write"
@@ -1715,7 +1715,7 @@ async def remove_project_dynamic_services(
17151715

17161716
user_role: UserRole | None = None
17171717
try:
1718-
user_role = await get_user_role(app, user_id)
1718+
user_role = await get_user_role(app, user_id=user_id)
17191719
except UserNotFoundError:
17201720
user_role = None
17211721

services/web/server/src/simcore_service_webserver/users/api.py

Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
"""
77

88
import logging
9-
from collections import deque
109
from typing import Any, NamedTuple, TypedDict
1110

1211
import simcore_postgres_database.errors as db_errors
@@ -27,10 +26,13 @@
2726
from simcore_postgres_database.utils_groups_extra_properties import (
2827
GroupExtraPropertiesNotFoundError,
2928
)
29+
from simcore_postgres_database.utils_repos import (
30+
pass_or_acquire_connection,
31+
transaction_context,
32+
)
3033
from simcore_postgres_database.utils_users import generate_alternative_username
3134

32-
from ..db.plugin import get_database_engine
33-
from ..db.plugin import get_asyncpg_engine, get_database_engine
35+
from ..db.plugin import get_asyncpg_engine
3436
from ..login.storage import AsyncpgStorage, get_plugin_storage
3537
from ..security.api import clean_auth_policy_cache
3638
from . import _users_repository
@@ -81,23 +83,19 @@ def _parse_as_user(user_id: Any) -> UserID:
8183

8284

8385
async def get_user_profile(
84-
app: web.Application, user_id: UserID, product_name: ProductName
86+
app: web.Application, *, user_id: UserID, product_name: ProductName
8587
) -> MyProfileGet:
8688
"""
8789
:raises UserNotFoundError:
8890
:raises MissingGroupExtraPropertiesForProductError: when product is not properly configured
8991
"""
90-
91-
engine = get_database_engine(app)
9292
user_profile: dict[str, Any] = {}
9393
user_primary_group = everyone_group = {}
9494
user_standard_groups = []
9595
user_id = _parse_as_user(user_id)
9696

97-
async with engine.acquire() as conn:
98-
row: RowProxy
99-
100-
async for row in conn.execute(
97+
async with pass_or_acquire_connection(engine=get_asyncpg_engine(app)) as conn:
98+
result = await conn.stream(
10199
sa.select(users, groups, user_to_groups.c.access_rights)
102100
.select_from(
103101
users.join(user_to_groups, users.c.id == user_to_groups.c.uid).join(
@@ -107,7 +105,9 @@ async def get_user_profile(
107105
.where(users.c.id == user_id)
108106
.order_by(sa.asc(groups.c.name))
109107
.set_label_style(sa.LABEL_STYLE_TABLENAME_PLUS_COL)
110-
):
108+
)
109+
110+
async for row in result:
111111
if not user_profile:
112112
user_profile = {
113113
"id": row.users_id,
@@ -198,13 +198,12 @@ async def update_user_profile(
198198
user_id = _parse_as_user(user_id)
199199

200200
if updated_values := ToUserUpdateDB.from_api(update).to_db():
201-
async with get_database_engine(app).acquire() as conn:
201+
202+
async with transaction_context(engine=get_asyncpg_engine(app)) as conn:
202203
query = users.update().where(users.c.id == user_id).values(**updated_values)
203204

204205
try:
205-
206-
resp = await conn.execute(query)
207-
assert resp.rowcount == 1 # nosec
206+
await conn.execute(query)
208207

209208
except db_errors.UniqueViolation as err:
210209
user_name = updated_values.get("name")
@@ -217,15 +216,14 @@ async def update_user_profile(
217216
) from err
218217

219218

220-
async def get_user_role(app: web.Application, user_id: UserID) -> UserRole:
219+
async def get_user_role(app: web.Application, *, user_id: UserID) -> UserRole:
221220
"""
222221
:raises UserNotFoundError:
223222
"""
224223
user_id = _parse_as_user(user_id)
225224

226-
engine = get_database_engine(app)
227-
async with engine.acquire() as conn:
228-
user_role: RowProxy | None = await conn.scalar(
225+
async with pass_or_acquire_connection(engine=get_asyncpg_engine(app)) as conn:
226+
user_role = await conn.scalar(
229227
sa.select(users.c.role).where(users.c.id == user_id)
230228
)
231229
if user_role is None:
@@ -288,14 +286,11 @@ async def get_user_display_and_id_names(
288286

289287

290288
async def get_guest_user_ids_and_names(app: web.Application) -> list[tuple[int, str]]:
291-
engine = get_database_engine(app)
292-
result: deque = deque()
293-
async with engine.acquire() as conn:
294-
async for row in conn.execute(
289+
async with pass_or_acquire_connection(engine=get_asyncpg_engine(app)) as conn:
290+
result = await conn.stream(
295291
sa.select(users.c.id, users.c.name).where(users.c.role == UserRole.GUEST)
296-
):
297-
result.append(row.as_tuple())
298-
return list(result)
292+
)
293+
return [(row.id, row.name) async for row in result]
299294

300295

301296
async def delete_user_without_projects(app: web.Application, user_id: UserID) -> None:
@@ -304,6 +299,7 @@ async def delete_user_without_projects(app: web.Application, user_id: UserID) ->
304299
# otherwise this function will raise asyncpg.exceptions.ForeignKeyViolationError
305300
# Consider "marking" users as deleted and havning a background job that
306301
# cleans it up
302+
# TODO: upgrade!!!
307303
db: AsyncpgStorage = get_plugin_storage(app)
308304
user = await db.get_user({"id": user_id})
309305
if not user:
@@ -330,8 +326,8 @@ async def get_user_fullname(app: web.Application, user_id: UserID) -> FullNameDi
330326
"""
331327
user_id = _parse_as_user(user_id)
332328

333-
async with get_database_engine(app).acquire() as conn:
334-
result = await conn.execute(
329+
async with pass_or_acquire_connection(engine=get_asyncpg_engine(app)) as conn:
330+
result = await conn.stream(
335331
sa.select(users.c.first_name, users.c.last_name).where(
336332
users.c.id == user_id
337333
)
@@ -353,12 +349,11 @@ async def get_user(app: web.Application, user_id: UserID) -> dict[str, Any]:
353349
row = await _users_repository.get_user_or_raise(
354350
engine=get_asyncpg_engine(app), user_id=user_id
355351
)
356-
return dict(row)
352+
return row._asdict()
357353

358354

359355
async def get_user_id_from_gid(app: web.Application, primary_gid: int) -> UserID:
360-
engine = get_database_engine(app)
361-
async with engine.acquire() as conn:
356+
async with pass_or_acquire_connection(engine=get_asyncpg_engine(app)) as conn:
362357
user_id: UserID = await conn.scalar(
363358
sa.select(users.c.id).where(users.c.primary_gid == primary_gid)
364359
)

services/web/server/tests/unit/with_dbs/04/studies_dispatcher/test_studies_dispatcher_studies_access.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -365,15 +365,15 @@ async def test_access_cookie_of_expired_user(
365365
resp = await client.get(f"{me_url}")
366366

367367
data, _ = await assert_status(resp, status.HTTP_200_OK)
368-
assert await get_user_role(app, data["id"]) == UserRole.GUEST
368+
assert await get_user_role(app, user_id=data["id"]) == UserRole.GUEST
369369

370370
async def enforce_garbage_collect_guest(uid):
371371
# TODO: can be replaced now by actual GC
372372
# Emulates garbage collector:
373373
# - GUEST user expired, cleaning it up
374374
# - client still holds cookie with its identifier nonetheless
375375
#
376-
assert await get_user_role(app, uid) == UserRole.GUEST
376+
assert await get_user_role(app, user_id=uid) == UserRole.GUEST
377377
projects = await _get_user_projects(client)
378378
assert len(projects) == 1
379379

@@ -401,7 +401,7 @@ async def enforce_garbage_collect_guest(uid):
401401
# as a guest user
402402
resp = await client.get(f"{me_url}")
403403
data, _ = await assert_status(resp, status.HTTP_200_OK)
404-
assert await get_user_role(app, data["id"]) == UserRole.GUEST
404+
assert await get_user_role(app, user_id=data["id"]) == UserRole.GUEST
405405

406406
# But I am another user
407407
assert data["id"] != user_id

0 commit comments

Comments
 (0)