-
-
Notifications
You must be signed in to change notification settings - Fork 23
Streaming deserialize: add source stream and task #318
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
bjester
wants to merge
5
commits into
learningequality:release-v0.9.x
Choose a base branch
from
bjester:streaming-deserialize-part-1
base: release-v0.9.x
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
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
31af519
Create base source class to share between serializatin and deserializ…
bjester f4ca9bf
Refactor serialize source to use new base class
bjester 1323ee7
Add Store queryset method for filtering on deserialization errors
bjester 5ee2ac3
Add complementary method for querying store records during deserializ…
bjester 6af15df
Add new source for deserialization of store records
bjester 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
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,92 @@ | ||
| from typing import Dict | ||
| from typing import Generator | ||
| from typing import List | ||
| from typing import Optional | ||
| from typing import Type | ||
|
|
||
| from morango.models.certificates import Filter | ||
| from morango.models.core import Store | ||
| from morango.models.core import SyncableModel | ||
| from morango.registry import syncable_models | ||
| from morango.sync.stream.source import MorangoSource | ||
| from morango.sync.stream.source import SourceTask | ||
|
|
||
|
|
||
| class DeserializeTask(SourceTask): | ||
| """Carrier class for providing context through the deserialization pipeline.""" | ||
|
|
||
| __slots__ = ("store", "app_model", "fk_cache", "errors") | ||
|
|
||
| def __init__(self, store: Store, fk_cache: Dict): | ||
| self.store = store | ||
| self.fk_cache: Dict = fk_cache | ||
| self.app_model: Optional[SyncableModel] = None | ||
| self.errors: List[Exception] = [] | ||
|
|
||
| @property | ||
| def id(self) -> str: | ||
| return self.store.id | ||
|
|
||
| @property | ||
| def model(self) -> Type[SyncableModel]: | ||
| return syncable_models.get_model(self.store.profile, self.store.model_name) | ||
|
|
||
| @property | ||
| def has_errors(self) -> bool: | ||
| return len(self.errors) > 0 | ||
|
|
||
| def set_app_model(self, app_model: Optional[SyncableModel]) -> None: | ||
| self.app_model = app_model | ||
|
|
||
| def add_error(self, error: Exception) -> None: | ||
| self.errors.append(error) | ||
|
|
||
|
|
||
| class StoreModelSource(MorangoSource[DeserializeTask]): | ||
| """ | ||
| Yields ``DeserializeTask`` objects for dirty store models that match the optional | ||
| *sync_filter*. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| profile: str, | ||
| sync_filter: Optional[Filter] = None, | ||
| dirty_only: bool = True, | ||
| partition_order: str = "asc", | ||
| fk_cache: Optional[Dict] = None, | ||
| skip_errored: bool = False, | ||
| ): | ||
| """ | ||
| :param profile: The Morango model profile | ||
| :param sync_filter: The Filter object for this sync | ||
| :param dirty_only: Whether to filter on dirty records only | ||
| :param partition_order: Controls how the filter specificity is applied, "asc" or "desc" | ||
| :param fk_cache: Dictionary cache for FK references | ||
| :param skip_errored: Whether to skip Store records with deserialization errors | ||
| """ | ||
| super().__init__(profile, sync_filter, dirty_only, partition_order) | ||
| self.fk_cache = fk_cache if fk_cache is not None else {} | ||
| self.skip_errored = skip_errored | ||
|
|
||
| def begin(self) -> None: | ||
| """Reset fk_cache at the beginning of stream""" | ||
| super().begin() | ||
| self.fk_cache.clear() | ||
|
|
||
| def stream_for_filter( | ||
| self, partition_condition: Optional[str] | ||
| ) -> Generator[DeserializeTask, None, None]: | ||
| # the registry yields models in foreign key dependency order, so streaming model by model | ||
| # ensures a record's foreign key targets are deserialized before it is | ||
| for store_qs in syncable_models.get_store_querysets(self.profile): | ||
| qs = store_qs | ||
| if partition_condition is not None: | ||
| qs = qs.filter(partition__startswith=partition_condition) | ||
| if self.dirty_only: | ||
| qs = qs.filter(dirty_bit=True) | ||
| if self.skip_errored: | ||
| qs = qs.exclude_has_deserialization_error() | ||
|
|
||
| for store_model in qs.iterator(): | ||
| yield DeserializeTask(store_model, self.fk_cache) |
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,104 @@ | ||
| import abc | ||
| from typing import Generator | ||
| from typing import Iterator | ||
| from typing import Optional | ||
| from typing import TypeVar | ||
|
|
||
| from morango.models.certificates import Filter | ||
| from morango.sync.stream.core import Source | ||
|
|
||
|
|
||
| class SourceTask(abc.ABC): | ||
|
bjester marked this conversation as resolved.
|
||
| """Typing for source object passed through streaming pipeline""" | ||
|
|
||
| __slots__ = () | ||
|
|
||
| @property | ||
| @abc.abstractmethod | ||
| def id(self) -> str: | ||
| pass | ||
|
|
||
|
|
||
| T = TypeVar("T", bound=SourceTask) | ||
|
|
||
|
|
||
| class MorangoSource(Source[T], abc.ABC): | ||
| """ | ||
| Common source functionality for Morango sources, such as SyncableModels and Store records. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| profile: str, | ||
| sync_filter: Optional[Filter] = None, | ||
| dirty_only: bool = True, | ||
| partition_order: str = "asc", | ||
| ): | ||
| """ | ||
| :param profile: The Morango model profile | ||
| :param sync_filter: The Filter object for this sync | ||
| :param dirty_only: Whether to filter on dirty records only | ||
| :param partition_order: Controls how the filter specificity is applied, "asc" or "desc" | ||
| """ | ||
| self.profile = profile | ||
| self.sync_filter = sync_filter | ||
| self.dirty_only = dirty_only | ||
| self.partition_order = partition_order | ||
| self._seen: Optional[set] = None | ||
|
|
||
| def begin(self) -> None: | ||
| """Initialize seen set at the beginning of the stream""" | ||
| self._seen = set() | ||
|
bjester marked this conversation as resolved.
bjester marked this conversation as resolved.
bjester marked this conversation as resolved.
|
||
|
|
||
| def prefix_conditions(self) -> Generator[Optional[str], None, None]: | ||
| """ | ||
| Generates partition prefixes for queries based on the sync filter and partition order. | ||
|
|
||
| This method outputs prefixes in sorted order according to the specified partition | ||
| order. If no sync filter is provided, it yields `None` to indicate a query | ||
| without filtering by partition. | ||
|
|
||
| :return: A generator yielding partition prefixes or `None` if no filtering is applied. | ||
| """ | ||
| if self.sync_filter is None: | ||
| # yield None once, so we do one query without a partition filter (everything) | ||
| yield None | ||
| else: | ||
| partitions_prefixes = [str(prefix) for prefix in self.sync_filter] | ||
|
bjester marked this conversation as resolved.
|
||
| partition_iterator = sorted( | ||
| partitions_prefixes, | ||
| reverse=self.partition_order == "desc", | ||
| ) | ||
|
|
||
| for prefix in partition_iterator: | ||
| yield prefix | ||
|
|
||
| def stream(self) -> Generator[T, None, None]: | ||
| """ | ||
| Streams unique objects based on prefix conditions. This generator method iterates over | ||
| partition conditions defined in the sync_filter and passes through to `stream_for_filter` | ||
| to stream back objects, ensuring that only objects with unique `id` values are yielded. | ||
|
|
||
| :return: A generator yielding unique objects. | ||
| """ | ||
| for partition_condition in self.prefix_conditions(): | ||
|
bjester marked this conversation as resolved.
|
||
| for obj in self.stream_for_filter(partition_condition): | ||
| # partition filtering could result in overlaps, and since we're walking | ||
| # through the partitions one by one, we should avoid duplicates. Morango | ||
| # syncable models and store records have unique IDs across the entire profile | ||
| if obj.id not in self._seen: | ||
| # without sync filters, we do not need to worry about repeating objects | ||
| if self.sync_filter is not None: | ||
| self._seen.add(obj.id) | ||
| yield obj | ||
|
|
||
| @abc.abstractmethod | ||
| def stream_for_filter(self, partition_condition: Optional[str]) -> Iterator[T]: | ||
| """ | ||
| This method is intended to generate an iterator that yields data based on the given | ||
| filtering condition. | ||
|
|
||
| :param partition_condition: A string representing a partition filter prefix condition | ||
| :return: An iterator yielding items | ||
| """ | ||
| pass | ||
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.