-
Notifications
You must be signed in to change notification settings - Fork 32
🎨 EFS Guardian adding data removal background task #6562
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
matusdrobuliak66
merged 22 commits into
ITISFoundation:master
from
matusdrobuliak66:improve-efs-4
Oct 22, 2024
Merged
Changes from 17 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
eb665e1
daily work
matusdrobuliak66 278fd85
Merge branch 'master' into improve-efs-4
matusdrobuliak66 bd2e218
refactoring project lock
matusdrobuliak66 0a2b1ba
fix pylint
matusdrobuliak66 ea50b06
refactor project lock
matusdrobuliak66 bf3a36d
fix tests
matusdrobuliak66 5349e3f
fix fixture with same name
matusdrobuliak66 2656b3d
final cleanup
matusdrobuliak66 9de2c25
fix unit tests
matusdrobuliak66 50fe206
Merge branch 'master' into improve-efs-4
matusdrobuliak66 2ada7e6
review @sanderegg
matusdrobuliak66 5633f51
Merge branch 'master' into improve-efs-4
matusdrobuliak66 70020a4
note about test
matusdrobuliak66 10e9b7f
review @pcrespov
matusdrobuliak66 dea70a6
review @pcrespov
matusdrobuliak66 e8a5300
review @sanderegg
matusdrobuliak66 67eb5ad
Merge branch 'master' into improve-efs-4
matusdrobuliak66 0831675
review @pcrespov
matusdrobuliak66 7dd1a16
review @pcrespov
matusdrobuliak66 43e68fa
Merge branch 'master' into improve-efs-4
matusdrobuliak66 b92b845
fix
matusdrobuliak66 3b74cfb
fix
matusdrobuliak66 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
41 changes: 41 additions & 0 deletions
41
packages/postgres-database/src/simcore_postgres_database/utils_projects.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| from datetime import datetime, timezone | ||
|
|
||
| import sqlalchemy as sa | ||
| from models_library.errors_classes import OsparcErrorMixin | ||
| from models_library.projects import ProjectID | ||
| from pydantic import parse_obj_as | ||
| from sqlalchemy.ext.asyncio import AsyncConnection | ||
|
|
||
| from .models.projects import projects | ||
| from .utils_repos import transaction_context | ||
|
|
||
|
|
||
| class DBBaseProjectError(OsparcErrorMixin, Exception): | ||
| ... | ||
|
|
||
|
|
||
| class DBProjectNotFoundError(DBBaseProjectError): | ||
| project_uuid: ProjectID | ||
|
|
||
|
|
||
| class ProjectsRepo: | ||
| def __init__(self, engine): | ||
| self.engine = engine | ||
|
|
||
| async def get_project_last_change_date( | ||
| self, | ||
| project_uuid: ProjectID, | ||
| *, | ||
| connection: AsyncConnection | None = None, | ||
| ) -> datetime: | ||
| async with transaction_context(self.engine, connection) as conn: | ||
| get_stmt = sa.select(projects.c.last_change_date).where( | ||
| projects.c.uuid == f"{project_uuid}" | ||
| ) | ||
|
|
||
| result = await conn.execute(get_stmt) | ||
| row = result.first() | ||
| if row is None: | ||
| raise DBProjectNotFoundError(project_uuid=project_uuid) | ||
| date = parse_obj_as(datetime, row[0]) | ||
| return date.replace(tzinfo=timezone.utc) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| # pylint: disable=redefined-outer-name | ||
| # pylint: disable=unused-argument | ||
| # pylint: disable=unused-variable | ||
| # pylint: disable=too-many-arguments | ||
| import uuid | ||
| from collections.abc import Awaitable, Callable | ||
| from datetime import datetime | ||
| from typing import Any, AsyncIterator | ||
|
|
||
| import pytest | ||
| import sqlalchemy | ||
| from aiopg.sa.connection import SAConnection | ||
| from aiopg.sa.result import RowProxy | ||
| from faker import Faker | ||
| from simcore_postgres_database.models.projects import projects | ||
| from simcore_postgres_database.utils_projects import ( | ||
| DBProjectNotFoundError, | ||
| ProjectsRepo, | ||
| ) | ||
| from sqlalchemy.ext.asyncio import AsyncEngine | ||
|
|
||
|
|
||
| async def _delete_project(connection: SAConnection, project_uuid: uuid.UUID) -> None: | ||
| result = await connection.execute( | ||
| sqlalchemy.delete(projects).where(projects.c.uuid == f"{project_uuid}") | ||
| ) | ||
| assert result.rowcount == 1 | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| async def registered_user( | ||
| connection: SAConnection, | ||
| create_fake_user: Callable[..., Awaitable[RowProxy]], | ||
| ) -> RowProxy: | ||
| user = await create_fake_user(connection) | ||
| assert user | ||
| return user | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| async def registered_project( | ||
| connection: SAConnection, | ||
| registered_user: RowProxy, | ||
| create_fake_project: Callable[..., Awaitable[RowProxy]], | ||
| ) -> AsyncIterator[dict[str, Any]]: | ||
| project = await create_fake_project(connection, registered_user) | ||
| assert project | ||
|
|
||
| yield dict(project) | ||
|
|
||
| await _delete_project(connection, project["uuid"]) | ||
|
|
||
|
|
||
| async def test_get_project_last_change_date( | ||
| asyncpg_engine: AsyncEngine, registered_project: dict, faker: Faker | ||
| ): | ||
| projects_repo = ProjectsRepo(asyncpg_engine) | ||
|
|
||
| project_last_change_date = await projects_repo.get_project_last_change_date( | ||
| project_uuid=registered_project["uuid"] | ||
| ) | ||
| assert isinstance(project_last_change_date, datetime) | ||
|
|
||
| with pytest.raises(DBProjectNotFoundError): | ||
| await projects_repo.get_project_last_change_date( | ||
| project_uuid=faker.uuid4() # <-- Non existing uuid in DB | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import datetime | ||
| import logging | ||
| from asyncio.log import logger | ||
| from collections.abc import AsyncIterator | ||
| from contextlib import asynccontextmanager | ||
| from typing import Final | ||
|
|
||
| import redis | ||
| import redis.exceptions | ||
| from models_library.projects import ProjectID | ||
| from models_library.projects_access import Owner | ||
| from models_library.projects_state import ProjectLocked, ProjectStatus | ||
| from redis.asyncio.lock import Lock | ||
|
|
||
| from .background_task import periodic_task | ||
| from .logging_utils import log_context | ||
|
|
||
| _logger = logging.getLogger(__name__) | ||
|
|
||
| PROJECT_REDIS_LOCK_KEY: str = "project_lock:{}" | ||
| PROJECT_LOCK_TIMEOUT: Final[datetime.timedelta] = datetime.timedelta(seconds=10) | ||
| ProjectLock = Lock | ||
|
|
||
| ProjectLockError = redis.exceptions.LockError | ||
|
|
||
|
|
||
| async def _auto_extend_project_lock(project_lock: Lock) -> None: | ||
| # NOTE: the background task already catches anything that might raise here | ||
| await project_lock.reacquire() | ||
|
|
||
|
|
||
| @asynccontextmanager | ||
| async def lock_project( | ||
| redis_lock: Lock, | ||
| project_uuid: str | ProjectID, | ||
| status: ProjectStatus, | ||
| owner: Owner | None = None, | ||
| ) -> AsyncIterator[None]: | ||
| """Context manager to lock and unlock a project by user_id | ||
|
|
||
| Raises: | ||
| ProjectLockError: if project is already locked | ||
| """ | ||
|
|
||
| try: | ||
| if not await redis_lock.acquire( | ||
| blocking=False, | ||
| token=ProjectLocked( | ||
| value=True, | ||
| owner=owner, | ||
| status=status, | ||
| ).json(), | ||
| ): | ||
| msg = f"Lock for project {project_uuid!r} owner {owner!r} could not be acquired" | ||
| raise ProjectLockError(msg) | ||
|
|
||
| with log_context( | ||
| _logger, | ||
| logging.DEBUG, | ||
| msg=f"with lock for {owner=}:{project_uuid=}:{status=}", | ||
| ): | ||
| async with periodic_task( | ||
| _auto_extend_project_lock, | ||
| interval=0.6 * PROJECT_LOCK_TIMEOUT, | ||
| task_name=f"{PROJECT_REDIS_LOCK_KEY.format(project_uuid)}_lock_auto_extend", | ||
| project_lock=redis_lock, | ||
| ): | ||
| yield | ||
|
|
||
| finally: | ||
| # let's ensure we release that stuff | ||
| try: | ||
| if await redis_lock.owned(): | ||
| await redis_lock.release() | ||
| except (redis.exceptions.LockError, redis.exceptions.LockNotOwnedError) as exc: | ||
| logger.warning( | ||
| "releasing %s unexpectedly raised an exception: %s", | ||
| f"{redis_lock=!r}", | ||
| f"{exc}", | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| # NOTE: Tested in osparc-simcore/services/web/server/tests/unit/with_dbs/02/test_project_lock.py |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.