-
Notifications
You must be signed in to change notification settings - Fork 3
feat: migrations #251
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
Open
janbritz
wants to merge
6
commits into
dev
Choose a base branch
from
feat/migrations
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat: migrations #251
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0d7d3b0
feat: migrations
janbritz 65ce22d
feat(migrations): downgrade
janbritz 0bdaf1c
fix: exceptions
janbritz d4776be
refactor: rename Exception
janbritz 6740b8b
refactor: make non-const variables lowercase
janbritz 6ffedef
feat(migrations): log exception when discovery fails
janbritz 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
Large diffs are not rendered by default.
Oops, something went wrong.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # This file is part of the QuestionPy SDK. (https://questionpy.org) | ||
| # The QuestionPy SDK is free software released under terms of the MIT license. See LICENSE.md. | ||
| # (c) Technische Universität Berlin, innoCampus <info@isis.tu-berlin.de> | ||
| import importlib | ||
| import pkgutil | ||
| from collections import defaultdict | ||
| from typing import NamedTuple | ||
|
|
||
| from ._base import MigrationQuestionStateWithVersion | ||
| from ._migration import MIGRATIONS_REGISTRY, Migration, MigrationsRegistry | ||
| from ._side_migration import SIDE_MIGRATIONS_REGISTRY, SideMigration, SideMigrationsRegistry | ||
| from .errors import MigrationDiscoveryError, MigrationNotPossibleError | ||
|
|
||
| __all__ = [ | ||
| "Migration", | ||
| "MigrationNotPossibleError", | ||
| "MigrationQuestionStateWithVersion", | ||
| "Migrations", | ||
| "SideMigration", | ||
| "get_migrations", | ||
| ] | ||
|
|
||
|
|
||
| class Migrations(NamedTuple): | ||
| package: MigrationsRegistry | ||
| """Migrations from and to this package.""" | ||
| side: SideMigrationsRegistry | ||
| """Migrations from other packages to this package.""" | ||
|
|
||
|
|
||
| def get_migrations(namespace: str, short_name: str) -> Migrations: | ||
| """The package and its dependencies must be importable.""" | ||
| module_name = f"{namespace}.{short_name}.migrations" | ||
|
|
||
| try: | ||
| module = importlib.import_module(module_name) | ||
| except ModuleNotFoundError: | ||
| return Migrations([], defaultdict(defaultdict)) | ||
|
|
||
| try: | ||
| for module_info in pkgutil.walk_packages(module.__path__, prefix=f"{module_name}."): | ||
| importlib.import_module(module_info.name) | ||
| except Exception as e: | ||
| raise MigrationDiscoveryError from e | ||
|
|
||
| return Migrations(MIGRATIONS_REGISTRY, SIDE_MIGRATIONS_REGISTRY) |
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,28 @@ | ||
| # This file is part of the QuestionPy SDK. (https://questionpy.org) | ||
| # The QuestionPy SDK is free software released under terms of the MIT license. See LICENSE.md. | ||
| # (c) Technische Universität Berlin, innoCampus <info@isis.tu-berlin.de> | ||
| from pydantic import BaseModel, JsonValue | ||
|
|
||
|
|
||
| class MigrationQuestionStateWithVersion(BaseModel): | ||
| package_namespace: str | ||
| package_short_name: str | ||
| package_version: str | ||
| options: dict[str, JsonValue] | ||
| state: dict[str, JsonValue] | ||
| state_version: int | ||
|
|
||
|
|
||
| class BaseMigration: | ||
| _state: MigrationQuestionStateWithVersion | ||
|
|
||
| def __init__(self, state: MigrationQuestionStateWithVersion): | ||
| self._state = state | ||
|
|
||
| @property | ||
| def state(self) -> dict[str, JsonValue]: | ||
| return self._state.state | ||
|
|
||
| @property | ||
| def options(self) -> dict[str, JsonValue]: | ||
| return self._state.options |
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,42 @@ | ||
| # This file is part of the QuestionPy SDK. (https://questionpy.org) | ||
| # The QuestionPy SDK is free software released under terms of the MIT license. See LICENSE.md. | ||
| # (c) Technische Universität Berlin, innoCampus <info@isis.tu-berlin.de> | ||
| from abc import ABC, abstractmethod | ||
| from bisect import insort | ||
|
|
||
| from ._base import BaseMigration | ||
| from .errors import MigrationNotPossibleError | ||
|
|
||
| type MigrationsRegistry = list[type[Migration]] | ||
|
|
||
|
|
||
| MIGRATIONS_REGISTRY: MigrationsRegistry = [] | ||
|
|
||
|
|
||
| def _migration_strategy(migration_cls: type["Migration"]) -> str: | ||
| """Migrations are sorted by their module and class name.""" | ||
| return migration_cls.__module__ + "." + migration_cls.__qualname__ | ||
|
|
||
|
|
||
| class Migration(BaseMigration, ABC): | ||
| """The base class for migrations from and to the current package.""" | ||
|
|
||
| def __init_subclass__(cls, **kwargs: object) -> None: | ||
| super().__init_subclass__(**kwargs) | ||
| insort(MIGRATIONS_REGISTRY, cls, key=_migration_strategy) | ||
|
|
||
| @abstractmethod | ||
| def upgrade(self) -> None: | ||
| """Upgrade the previous state to this version. | ||
|
|
||
| It is generally assumed, that upgrading is always possible, but if that is not the case the | ||
| `MigrationNotPossibleError` should be raised. | ||
| """ | ||
|
|
||
| def downgrade(self) -> None: | ||
| """Downgrade this state to the previous version. | ||
|
|
||
| The `MigrationNotPossibleError` should be raised if downgrading is not possible. This is also the default | ||
| behaviour. | ||
| """ | ||
| raise MigrationNotPossibleError | ||
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,29 @@ | ||
| # This file is part of the QuestionPy SDK. (https://questionpy.org) | ||
| # The QuestionPy SDK is free software released under terms of the MIT license. See LICENSE.md. | ||
| # (c) Technische Universität Berlin, innoCampus <info@isis.tu-berlin.de> | ||
| from abc import ABC, abstractmethod | ||
| from collections import defaultdict | ||
|
|
||
| from ._base import BaseMigration | ||
|
|
||
| type SideMigrationsRegistry = defaultdict[str, defaultdict[str, dict[int, type[SideMigration]]]] | ||
|
|
||
|
|
||
| SIDE_MIGRATIONS_REGISTRY: SideMigrationsRegistry = defaultdict(lambda: defaultdict(dict)) | ||
|
|
||
|
|
||
| class SideMigration(BaseMigration, ABC): | ||
| """The base class for migrations from other packages to the current package.""" | ||
|
|
||
| def __init_subclass__( | ||
| cls, /, for_namespace: str, for_short_name: str, for_state_version: int, **kwargs: object | ||
| ) -> None: | ||
| super().__init_subclass__(**kwargs) | ||
| SIDE_MIGRATIONS_REGISTRY[for_namespace][for_short_name][for_state_version] = cls | ||
|
|
||
| @abstractmethod | ||
| def sidegrade(self) -> None: | ||
| """Sidegrade the given state to this version. | ||
|
|
||
| If the migration is not possible, raise the `MigrationNotPossibleError`. | ||
| """ |
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,71 @@ | ||
| # This file is part of the QuestionPy SDK. (https://questionpy.org) | ||
| # The QuestionPy SDK is free software released under terms of the MIT license. See LICENSE.md. | ||
| # (c) Technische Universität Berlin, innoCampus <info@isis.tu-berlin.de> | ||
| from questionpy_common.api.qtype import MigrationError, MigrationErrorKind | ||
| from questionpy_common.environment import Package | ||
|
|
||
| from ._base import MigrationQuestionStateWithVersion | ||
|
|
||
|
|
||
| class MigrationNotImplementedError(MigrationError): | ||
| def __init__(self) -> None: | ||
| super().__init__(kind=MigrationErrorKind.NOT_IMPLEMENTED) | ||
|
|
||
|
|
||
| class MigrationNotPossibleError(MigrationError): | ||
| def __init__(self, *args: object, reason: str | None = None, temporary: bool = False) -> None: | ||
| super().__init__(*args, kind=MigrationErrorKind.NOT_POSSIBLE, reason=reason, temporary=temporary) | ||
|
|
||
|
|
||
| class SpecificMigrationFailedError(MigrationError): | ||
| def __init__(self, cause: Exception, from_version: int, to_version: int, step: int): | ||
| temporary = False | ||
| msg = f"The migration at step {step} from state version {from_version} to state version {to_version} " | ||
|
|
||
| if isinstance(cause, MigrationNotPossibleError): | ||
| kind = MigrationErrorKind.NOT_POSSIBLE | ||
|
|
||
| temporary = cause.temporary | ||
| reason = f": {cause}" if cause.reason else "." | ||
| msg += f"is not possible{reason}" | ||
| else: | ||
| kind = MigrationErrorKind.FAILED | ||
| msg += "failed." | ||
|
|
||
| super().__init__(kind=kind, reason=msg, temporary=temporary) | ||
|
|
||
|
|
||
| class MigrationPackageMissmatchError(MigrationError): | ||
| def __init__(self, package: Package, state: MigrationQuestionStateWithVersion): | ||
| msg = ( | ||
| f"The provided question state must origin from this package. " | ||
| f"Expected @{package.manifest.namespace}/{package.manifest.short_name}, " | ||
| f"got @{state.package_namespace}/{state.package_short_name}." | ||
| ) | ||
|
|
||
| super().__init__(kind=MigrationErrorKind.PACKAGE_MISSMATCH, reason=msg) | ||
|
|
||
|
|
||
| class MigrationPackageVersionMissmatchError(MigrationError): | ||
| def __init__(self, expected_state_version: int, actual_state_version: int): | ||
| msg = ( | ||
| f"The provided question state must have the same state version used by this package. Expected " | ||
| f"'{expected_state_version}', got '{actual_state_version}." | ||
| ) | ||
|
|
||
| super().__init__(kind=MigrationErrorKind.PACKAGE_MISSMATCH, reason=msg) | ||
|
|
||
|
|
||
| class MigrationQuestionStateInvalidError(MigrationError): | ||
| def __init__(self) -> None: | ||
| super().__init__(kind=MigrationErrorKind.QUESTION_STATE_INVALID) | ||
|
|
||
|
|
||
| class MigrationFailedError(MigrationError): | ||
| def __init__(self) -> None: | ||
| super().__init__(kind=MigrationErrorKind.FAILED) | ||
|
|
||
|
|
||
| class MigrationDiscoveryError(MigrationError): | ||
| def __init__(self) -> None: | ||
| super().__init__(kind=MigrationErrorKind.DISCOVERY_ERROR) |
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.
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.