Skip to content

Commit 6431aa1

Browse files
bjesterclaude
andcommitted
Add transforms for deserializing and validating store records
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 12b3880 commit 6431aa1

2 files changed

Lines changed: 601 additions & 0 deletions

File tree

‎morango/sync/stream/deserialize.py‎

Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,33 @@
1+
import json
2+
from collections import namedtuple
13
from typing import Dict
24
from typing import Generator
35
from typing import List
46
from typing import Optional
7+
from typing import Set
8+
from typing import Tuple
59
from typing import Type
610

11+
from django.core import exceptions
12+
from django.db.models import ForeignKey
13+
from django.db.utils import IntegrityError
14+
15+
from morango.errors import MorangoDirtyParent
16+
from morango.errors import MorangoMissingParent
717
from morango.models.certificates import Filter
818
from morango.models.core import Store
919
from morango.models.core import SyncableModel
1020
from morango.registry import syncable_models
21+
from morango.sync.stream.core import Transform
1122
from morango.sync.stream.source import MorangoSource
1223
from morango.sync.stream.source import SourceTask
1324

25+
DIRTY_PARENT_MESSAGE = "Parent is dirty; could not deserialize."
26+
MISSING_PARENT_MESSAGE = "Parent does not exist in Store; could not deserialize."
27+
28+
# the store state of an FK target, used to resolve validation failures
29+
_TargetState = namedtuple("_TargetState", ["deleted", "hard_deleted", "dirty_bit"])
30+
1431

1532
class DeserializeOutcome:
1633
"""The resolved action for a `DeserializeTask`, which the sink applies"""
@@ -132,3 +149,177 @@ def stream_for_filter(
132149

133150
for store_model in qs.iterator():
134151
yield DeserializeTask(store_model, self.fk_cache)
152+
153+
154+
class AppModelDeserialize(Transform[DeserializeTask]):
155+
"""
156+
Builds the unsaved app model from each task's serialized store data. Deleted store records
157+
pass through untouched, since deleting the app model is left to the sink.
158+
"""
159+
160+
def __init__(self, sync_filter: Optional[Filter] = None):
161+
self.sync_filter = sync_filter
162+
163+
def transform(self, task: DeserializeTask) -> DeserializeTask:
164+
if task.store.deleted:
165+
return task
166+
167+
try:
168+
app_model = task.model.deserialize(
169+
json.loads(task.store.serialized), sync_filter=self.sync_filter
170+
)
171+
except (ValueError, exceptions.ValidationError) as e:
172+
# `json.JSONDecodeError` is a `ValueError`
173+
task.add_error(e)
174+
return task
175+
176+
app_model._morango_source_id = task.store.source_id
177+
app_model._morango_partition = task.store.partition
178+
app_model._morango_dirty_bit = False
179+
task.set_app_model(app_model)
180+
return task
181+
182+
183+
class AppModelValidate(Transform[DeserializeTask]):
184+
"""
185+
Validates each task's app model and resolves its outcome. The source streams FK targets ahead
186+
of the records that reference them, so a target validated earlier in the run is already in
187+
the shared `fk_cache` even though the sink may not have written it yet. A cache miss falls back
188+
to looking up the target in the app tables.
189+
190+
Must be instantiated per pipeline run, since it tracks which records failed or were deleted
191+
during the run, so that the records referencing them can be resolved accordingly.
192+
"""
193+
194+
def __init__(self, sync_filter: Optional[Filter] = None):
195+
self.sync_filter = sync_filter
196+
self.failed_ids: Set[str] = set()
197+
# maps the ID of a deleted record to whether the deletion is a hard deletion
198+
self.deleted_ids: Dict[str, bool] = {}
199+
200+
def transform(self, task: DeserializeTask) -> DeserializeTask:
201+
if task.has_errors:
202+
self.failed_ids.add(task.id)
203+
return task
204+
205+
if task.store.deleted:
206+
self.deleted_ids[task.id] = task.store.hard_deleted
207+
return task
208+
209+
fk_references = self._fk_references(task.app_model)
210+
211+
for _, target_id in fk_references:
212+
if target_id in self.deleted_ids:
213+
self._propagate_deletion(task, hard=self.deleted_ids[target_id])
214+
return task
215+
216+
for field, target_id in fk_references:
217+
if target_id in self.failed_ids:
218+
self._fail(task, self._failed_target_error(task, field, target_id))
219+
return task
220+
221+
try:
222+
task.app_model.cached_clean_fields(task.fk_cache, sync_filter=self.sync_filter)
223+
except (exceptions.ValidationError, exceptions.ObjectDoesNotExist) as e:
224+
self._classify_failure(task, fk_references, e)
225+
return task
226+
227+
@staticmethod
228+
def _fk_references(app_model: SyncableModel) -> List[Tuple[ForeignKey, str]]:
229+
"""The FK fields on the app model that hold a value, paired with that value"""
230+
references = []
231+
for field in app_model._meta.fields:
232+
if not isinstance(field, ForeignKey):
233+
continue
234+
target_id = getattr(app_model, field.attname)
235+
if target_id is not None:
236+
references.append((field, target_id))
237+
return references
238+
239+
@staticmethod
240+
def _failed_target_error(task: DeserializeTask, field: ForeignKey, target_id: str) -> Exception:
241+
if field.attname == task.self_referential_fk():
242+
return MorangoDirtyParent(DIRTY_PARENT_MESSAGE)
243+
return exceptions.ValidationError(
244+
"{} with id {} failed to deserialize".format(
245+
field.related_model._meta.verbose_name, target_id
246+
)
247+
)
248+
249+
def _classify_failure(
250+
self,
251+
task: DeserializeTask,
252+
fk_references: List[Tuple[ForeignKey, str]],
253+
error: Exception,
254+
) -> None:
255+
"""
256+
Resolves a validation failure using the store records of the FK targets. Only runs on
257+
failure, so it costs at most one query per failed record and none per valid record.
258+
"""
259+
targets = self._lookup_targets(fk_references)
260+
261+
# a reference to a deleted record propagates the deletion, instead of failing
262+
for _, target_id in fk_references:
263+
target = targets.get(target_id)
264+
if target is not None and (target.deleted or target.hard_deleted):
265+
self._propagate_deletion(task, hard=target.hard_deleted)
266+
return
267+
268+
self._fail(task, self._failure_error(task, fk_references, targets, error))
269+
270+
@staticmethod
271+
def _lookup_targets(
272+
fk_references: List[Tuple[ForeignKey, str]],
273+
) -> Dict[str, _TargetState]:
274+
"""The store state of each FK target that has a store record, keyed by the target ID"""
275+
if not fk_references:
276+
return {}
277+
target_ids = [target_id for _, target_id in fk_references]
278+
return {
279+
target_id: _TargetState(deleted, hard_deleted, dirty_bit)
280+
for target_id, deleted, hard_deleted, dirty_bit in Store.objects.filter(
281+
id__in=target_ids
282+
).values_list("id", "deleted", "hard_deleted", "dirty_bit")
283+
}
284+
285+
@staticmethod
286+
def _failure_error(
287+
task: DeserializeTask,
288+
fk_references: List[Tuple[ForeignKey, str]],
289+
targets: Dict[str, _TargetState],
290+
error: Exception,
291+
) -> Exception:
292+
"""
293+
The error to record for a failure that did not propagate a deletion. Problems with the
294+
parent take precedence, then missing targets, otherwise the original validation error.
295+
"""
296+
self_ref_fk = task.self_referential_fk()
297+
for field, target_id in fk_references:
298+
if field.attname != self_ref_fk:
299+
continue
300+
if target_id not in targets:
301+
return MorangoMissingParent(MISSING_PARENT_MESSAGE)
302+
if targets[target_id].dirty_bit:
303+
return MorangoDirtyParent(DIRTY_PARENT_MESSAGE)
304+
305+
for field, target_id in fk_references:
306+
if target_id not in targets:
307+
return IntegrityError(
308+
"{from_model}.{from_field} references non-existent {to_model} instance with "
309+
"id '{to_pk}'".format(
310+
from_model=task.model.__name__,
311+
from_field=field.attname,
312+
to_model=field.related_model._meta.verbose_name,
313+
to_pk=target_id,
314+
)
315+
)
316+
317+
return error
318+
319+
def _propagate_deletion(self, task: DeserializeTask, hard: bool) -> None:
320+
task.set_propagated_deletion(hard)
321+
self.deleted_ids[task.id] = hard
322+
323+
def _fail(self, task: DeserializeTask, error: Exception) -> None:
324+
task.add_error(error)
325+
self.failed_ids.add(task.id)

0 commit comments

Comments
 (0)