|
| 1 | +"""Partial admission for explicitly lenient legacy creative uploads. |
| 2 | +
|
| 3 | +The dispatcher owns format projection, not the seller's creative library. |
| 4 | +Never reconcile a destructive library replacement from a filtered request. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +from collections.abc import Mapping |
| 10 | +from contextvars import ContextVar |
| 11 | +from copy import deepcopy |
| 12 | +from dataclasses import dataclass, field |
| 13 | +from typing import Any |
| 14 | + |
| 15 | +from pydantic import ValidationError |
| 16 | + |
| 17 | +from adcp.canonical_formats.projection import ( |
| 18 | + LegacyCreativeProjectionError, |
| 19 | + LegacyFormatConverter, |
| 20 | + normalize_legacy_creative_request, |
| 21 | +) |
| 22 | + |
| 23 | + |
| 24 | +@dataclass(frozen=True) |
| 25 | +class PartialCreativeBatch: |
| 26 | + submitted_ids: tuple[str, ...] |
| 27 | + failures: tuple[dict[str, Any], ...] |
| 28 | + _typed_failures: dict[str, Any] = field(init=False, repr=False, compare=False) |
| 29 | + |
| 30 | + def __post_init__(self) -> None: |
| 31 | + from adcp.types import SyncCreativeResult |
| 32 | + |
| 33 | + # Materialize SDK-owned failures BEFORE dispatch can mutate anything. |
| 34 | + # The wire assignment_errors map permits arbitrary package IDs through |
| 35 | + # additionalProperties; its generated model over-restricts every key. |
| 36 | + # Validate our remaining fields, then retain our known string-valued |
| 37 | + # map without applying that extra generated key restriction. |
| 38 | + prepared = {} |
| 39 | + for failure in self.failures: |
| 40 | + row = SyncCreativeResult.model_validate( |
| 41 | + {key: value for key, value in failure.items() if key != "assignment_errors"} |
| 42 | + ) |
| 43 | + if "assignment_errors" in failure: |
| 44 | + row = row.model_copy( |
| 45 | + update={"assignment_errors": deepcopy(failure["assignment_errors"])} |
| 46 | + ) |
| 47 | + prepared[failure["creative_id"]] = row |
| 48 | + object.__setattr__(self, "_typed_failures", prepared) |
| 49 | + |
| 50 | + def merge(self, result: Any) -> None: |
| 51 | + """Overlay once per terminal result, before persistence or delivery. |
| 52 | +
|
| 53 | + Idempotency replays may already contain our rejection rows. Replacing |
| 54 | + them rather than appending makes repeated overlays idempotent too. |
| 55 | + Handler request-level errors retain their own terminal error branch. |
| 56 | + """ |
| 57 | + payload = ( |
| 58 | + result.model_dump(mode="json", exclude_none=True) |
| 59 | + if hasattr(result, "model_dump") |
| 60 | + else result |
| 61 | + ) |
| 62 | + if not isinstance(payload, dict) or "creatives" not in payload: |
| 63 | + return |
| 64 | + rows = payload["creatives"] |
| 65 | + if not isinstance(rows, list): |
| 66 | + raise ValueError("sync_creatives completion must contain a creatives array") |
| 67 | + by_id = {row["creative_id"]: row for row in rows} |
| 68 | + if len(by_id) != len(rows): |
| 69 | + raise ValueError("sync_creatives completion contains duplicate creative IDs") |
| 70 | + by_id.update((row["creative_id"], deepcopy(row)) for row in self.failures) |
| 71 | + if any(creative_id not in by_id for creative_id in self.submitted_ids): |
| 72 | + raise ValueError("sync_creatives completion omits an admitted creative") |
| 73 | + ordered = [by_id[creative_id] for creative_id in self.submitted_ids] |
| 74 | + submitted = set(self.submitted_ids) |
| 75 | + ordered.extend(row for row in rows if row["creative_id"] not in submitted) |
| 76 | + if isinstance(result, dict): |
| 77 | + result["creatives"] = ordered |
| 78 | + else: |
| 79 | + # Preserve the adopter's already-typed rows, including private |
| 80 | + # metadata. Rebuilding them from serialized data can reject a |
| 81 | + # conforming response or discard same-process projection state. |
| 82 | + original = { |
| 83 | + row["creative_id"] if isinstance(row, dict) else row.creative_id: row |
| 84 | + for row in result.creatives |
| 85 | + } |
| 86 | + result.creatives = [ |
| 87 | + ( |
| 88 | + self._typed_failures[row["creative_id"]].model_copy(deep=True) |
| 89 | + if row["creative_id"] in self._typed_failures |
| 90 | + else original[row["creative_id"]] |
| 91 | + ) |
| 92 | + for row in ordered |
| 93 | + ] |
| 94 | + |
| 95 | + |
| 96 | +partial_creative_batch: ContextVar[PartialCreativeBatch | None] = ContextVar( |
| 97 | + "adcp_partial_creative_batch", default=None |
| 98 | +) |
| 99 | + |
| 100 | + |
| 101 | +def normalize_lenient_creative_batch( |
| 102 | + value: Mapping[str, Any], |
| 103 | + *, |
| 104 | + legacy_format_converter: LegacyFormatConverter | None, |
| 105 | + projection_sources: list[Any], |
| 106 | +) -> tuple[dict[str, Any], PartialCreativeBatch | None]: |
| 107 | + """Validate the whole envelope before isolating unprojectable formats.""" |
| 108 | + from adcp.types.legacy import LegacySyncCreativesRequest |
| 109 | + |
| 110 | + try: |
| 111 | + LegacySyncCreativesRequest.model_validate(value) |
| 112 | + except ValidationError as exc: |
| 113 | + first = exc.errors(include_input=False, include_context=False, include_url=False)[0] |
| 114 | + path = ".".join(str(part) for part in first["loc"]) |
| 115 | + raise LegacyCreativeProjectionError( |
| 116 | + f"Invalid sync_creatives request at {path or 'request'}: {first['msg']}" |
| 117 | + ) from exc |
| 118 | + |
| 119 | + creatives = value.get("creatives") |
| 120 | + if not creatives: |
| 121 | + return ( |
| 122 | + normalize_legacy_creative_request( |
| 123 | + value, |
| 124 | + legacy_format_converter=legacy_format_converter, |
| 125 | + projection_sources=projection_sources, |
| 126 | + ), |
| 127 | + None, |
| 128 | + ) |
| 129 | + submitted_ids = tuple(row["creative_id"] for row in creatives) |
| 130 | + if len(set(submitted_ids)) != len(submitted_ids): |
| 131 | + raise LegacyCreativeProjectionError("sync_creatives requires unique creative IDs") |
| 132 | + |
| 133 | + normalized = normalize_legacy_creative_request( |
| 134 | + {key: child for key, child in value.items() if key != "creatives"}, |
| 135 | + legacy_format_converter=legacy_format_converter, |
| 136 | + projection_sources=projection_sources, |
| 137 | + ) |
| 138 | + admitted: list[dict[str, Any]] = [] |
| 139 | + failures: list[dict[str, Any]] = [] |
| 140 | + for index, creative in enumerate(creatives): |
| 141 | + creative_sources: list[Any] = [] |
| 142 | + try: |
| 143 | + projected = normalize_legacy_creative_request( |
| 144 | + creative, |
| 145 | + legacy_format_converter=legacy_format_converter, |
| 146 | + projection_sources=creative_sources, |
| 147 | + field_path=f"request.creatives[{index}]", |
| 148 | + ) |
| 149 | + except LegacyCreativeProjectionError as exc: |
| 150 | + message = str(exc) |
| 151 | + failures.append( |
| 152 | + { |
| 153 | + "creative_id": creative["creative_id"], |
| 154 | + "action": "failed", |
| 155 | + "errors": [ |
| 156 | + { |
| 157 | + "code": "UNSUPPORTED_FEATURE", |
| 158 | + "message": message, |
| 159 | + "field": message.split(" cannot be projected", 1)[0].removeprefix( |
| 160 | + "request." |
| 161 | + ), |
| 162 | + } |
| 163 | + ], |
| 164 | + } |
| 165 | + ) |
| 166 | + else: |
| 167 | + admitted.append(projected) |
| 168 | + projection_sources.extend(creative_sources) |
| 169 | + normalized["creatives"] = admitted |
| 170 | + if not failures: |
| 171 | + return normalized, None |
| 172 | + if value.get("delete_missing"): |
| 173 | + raise LegacyCreativeProjectionError( |
| 174 | + "delete_missing cannot reconcile a partially projected creative batch; " |
| 175 | + "retry the uploads without delete_missing, then reconcile the complete library" |
| 176 | + ) |
| 177 | + if value.get("creative_ids"): |
| 178 | + raise LegacyCreativeProjectionError( |
| 179 | + "creative_ids filtering cannot be combined with a partially projected batch; " |
| 180 | + "submit only the selected creatives instead" |
| 181 | + ) |
| 182 | + |
| 183 | + rejected = {row["creative_id"]: row for row in failures} |
| 184 | + assignments = [] |
| 185 | + for assignment in normalized.get("assignments", []): |
| 186 | + failure = rejected.get(assignment["creative_id"]) |
| 187 | + if failure is None: |
| 188 | + assignments.append(assignment) |
| 189 | + else: |
| 190 | + failure.setdefault("assignment_errors", {})[ |
| 191 | + assignment["package_id"] |
| 192 | + ] = "Assignment refused because this submitted creative's format cannot be projected" |
| 193 | + if assignments: |
| 194 | + if not admitted: |
| 195 | + raise LegacyCreativeProjectionError( |
| 196 | + "A batch with no projectable creatives cannot also apply unrelated assignments; " |
| 197 | + "retry the assignments separately" |
| 198 | + ) |
| 199 | + normalized["assignments"] = assignments |
| 200 | + else: |
| 201 | + normalized.pop("assignments", None) |
| 202 | + return normalized, PartialCreativeBatch(submitted_ids, tuple(failures)) |
0 commit comments