-
-
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
base: release-v0.9.x
Are you sure you want to change the base?
Changes from all commits
3dd72c8
6913e46
c0eaf3f
f688e77
b0b1fd4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| 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 or {} | ||
| self.skip_errored = skip_errored | ||
|
|
||
| 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) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| 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): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Verified on this class shape: One task instance exists per record streamed, in a pipeline whose stated point is "reducing memory overhead" ( |
||
| """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 = set() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Skipping the bookkeeping when there is a single prefix condition covers that case. Also note |
||
|
|
||
| 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] | ||
| 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(): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Partition-major iteration drops the model-dependency ordering deserialization relies on. This loops prefixes outer, models inner, so emission is
Ordering is irrelevant for serialization, which is presumably why the base landed this way. For deserialization it is the guarantee. Either invert the loops in
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There are no cross-partition FKs. The ordering is a naive approach that works with known filters, which prioritize the shortest filters first, which are likely the least specific. |
||
| 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 | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: This is a verbatim extraction of
operations.py:326-336, comment included, but that call site still hand-rolls the annotation. Swapping it forstore_models.exclude_has_deserialization_error()is one line and keeps the two from drifting — #317's "do not modify the existing deserialization process" is about behaviour, and this is behaviour-preserving.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The code in
operations.pywill eventually be removed. There is no need to update it.