| 1 |
"""Update expression merging for before_event action changes. |
| 2 |
|
| 3 |
When a ``before_event(Update)`` handler modifies document fields, those |
| 4 |
changes must be included in the update expression sent to MongoDB. This |
| 5 |
module provides a general-purpose merger with configurable conflict |
| 6 |
resolution. |
| 7 |
|
| 8 |
A *conflict* occurs when a field (identified by its dotted path in the |
| 9 |
MongoDB document) is modified by both the explicit update arguments and |
| 10 |
a ``before_event`` handler. |
| 11 |
|
| 12 |
Strategies |
| 13 |
---------- |
| 14 |
``UPDATE_WINS`` (default) |
| 15 |
Explicit update arguments take precedence. Action changes are |
| 16 |
included only for fields not already targeted by the update. |
| 17 |
|
| 18 |
``ACTION_WINS`` |
| 19 |
Action changes take precedence. For conflicting fields, the |
| 20 |
before_event value replaces whatever the update expression would |
| 21 |
have set. Non-conflicting update fields are preserved. |
| 22 |
|
| 23 |
``ACTION_OVERRIDE`` |
| 24 |
Action changes completely replace the entire update expression. |
| 25 |
The original update arguments are discarded. |
| 26 |
|
| 27 |
``RAISE`` |
| 28 |
Raises ``MergeConflictError`` if any field is modified by both |
| 29 |
the update expression and a before_event handler. |
| 30 |
""" |
| 31 |
|
| 32 |
from collections.abc import Mapping |
| 33 |
from enum import Enum |
| 34 |
from typing import Any |
| 35 |
|
| 36 |
from beanie.odm.operators.update import BaseUpdateOperator |
| 37 |
from beanie.odm.operators.update.general import SetRevisionId |
| 38 |
|
| 39 |
|
| 40 |
class ActionConflictResolution(str, Enum): |
| 41 |
"""Strategy for resolving conflicts between before_event field changes |
| 42 |
and explicit update arguments. |
| 43 |
""" |
| 44 |
|
| 45 |
UPDATE_WINS = "update_wins" |
| 46 |
ACTION_WINS = "action_wins" |
| 47 |
ACTION_OVERRIDE = "action_override" |
| 48 |
RAISE = "raise" |
| 49 |
|
| 50 |
|
| 51 |
class MergeConflictError(Exception): |
| 52 |
"""Raised when ``RAISE`` strategy detects conflicting fields.""" |
| 53 |
|
| 54 |
def __init__(self, conflicting_fields: set[str]) -> None: |
| 55 |
self.conflicting_fields = conflicting_fields |
| 56 |
fields_str = ", ".join(sorted(conflicting_fields)) |
| 57 |
super().__init__( |
| 58 |
f"before_event and update expression both modify: {fields_str}. " |
| 59 |
f"Use a different ActionConflictResolution strategy or adjust " |
| 60 |
f"the before_event handler." |
| 61 |
) |
| 62 |
|
| 63 |
|
| 64 |
def _consolidate_update_query( |
| 65 |
update_args: list[dict[str, Any] | Mapping[str, Any]], |
| 66 |
) -> dict[str, dict[str, Any]]: |
| 67 |
"""Build a single consolidated MongoDB update dict from a list of |
| 68 |
update expressions. |
| 69 |
|
| 70 |
Merges multiple ``$set``, ``$inc``, ``$unset``, etc. into one dict |
| 71 |
where each operator key maps to a combined dict of field-value pairs. |
| 72 |
|
| 73 |
``SetRevisionId`` and aggregation pipeline (list) expressions are |
| 74 |
skipped -- they are handled separately by the query builder. |
| 75 |
|
| 76 |
:param update_args: list of update expressions (dicts, |
| 77 |
BaseUpdateOperator instances, etc.) |
| 78 |
:return: consolidated ``{operator: {field: value, ...}, ...}`` dict |
| 79 |
""" |
| 80 |
consolidated: dict[str, dict[str, Any]] = {} |
| 81 |
|
| 82 |
for arg in update_args: |
| 83 |
if isinstance(arg, SetRevisionId): |
| 84 |
continue |
| 85 |
if isinstance(arg, list): |
| 86 |
continue |
| 87 |
|
| 88 |
if isinstance(arg, BaseUpdateOperator): |
| 89 |
raw = dict(arg.query) |
| 90 |
elif isinstance(arg, dict): |
| 91 |
raw = arg |
| 92 |
elif isinstance(arg, Mapping): |
| 93 |
raw = dict(arg) |
| 94 |
else: |
| 95 |
raise TypeError( |
| 96 |
f"Unsupported update expression type: {type(arg)!r}" |
| 97 |
) |
| 98 |
|
| 99 |
for operator_key, fields in raw.items(): |
| 100 |
if not isinstance(fields, (dict, Mapping)): |
| 101 |
continue |
| 102 |
if operator_key not in consolidated: |
| 103 |
consolidated[operator_key] = {} |
| 104 |
consolidated[operator_key].update(fields) |
| 105 |
|
| 106 |
return consolidated |
| 107 |
|
| 108 |
|
| 109 |
def _extract_targeted_fields( |
| 110 |
consolidated: dict[str, dict[str, Any]], |
| 111 |
) -> set[str]: |
| 112 |
"""Extract the set of all field names targeted by any update operator. |
| 113 |
|
| 114 |
:param consolidated: output of ``_consolidate_update_query`` |
| 115 |
:return: set of dotted field paths |
| 116 |
""" |
| 117 |
fields: set[str] = set() |
| 118 |
for operator_fields in consolidated.values(): |
| 119 |
fields.update(operator_fields.keys()) |
| 120 |
return fields |
| 121 |
|
| 122 |
|
| 123 |
def merge_update_expressions( |
| 124 |
update_args: list[dict[str, Any] | Mapping[str, Any]], |
| 125 |
action_changes: dict[str, Any], |
| 126 |
strategy: ActionConflictResolution = ActionConflictResolution.UPDATE_WINS, |
| 127 |
) -> list[dict[str, Any] | Mapping[str, Any]]: |
| 128 |
"""Merge before_event field changes into update arguments. |
| 129 |
|
| 130 |
Produces a single consolidated update expression that includes both |
| 131 |
the original update arguments and the before_event changes, resolved |
| 132 |
according to the chosen conflict strategy. |
| 133 |
|
| 134 |
Expressions that are not standard update operators (``SetRevisionId``, |
| 135 |
aggregation pipelines) are preserved and passed through unchanged. |
| 136 |
|
| 137 |
:param update_args: original update expressions passed to |
| 138 |
``Document.update()`` |
| 139 |
:param action_changes: dict of ``{field: value}`` changes produced |
| 140 |
by before_event handlers |
| 141 |
:param strategy: conflict resolution strategy |
| 142 |
:return: new list of update expressions with action changes merged |
| 143 |
:raises MergeConflictError: when strategy is ``RAISE`` and conflicts |
| 144 |
exist |
| 145 |
""" |
| 146 |
if not action_changes: |
| 147 |
return list(update_args) |
| 148 |
|
| 149 |
if strategy is ActionConflictResolution.ACTION_OVERRIDE: |
| 150 |
passthrough = _collect_passthrough(update_args) |
| 151 |
return [{"$set": dict(action_changes)}] + passthrough |
| 152 |
|
| 153 |
consolidated = _consolidate_update_query(update_args) |
| 154 |
targeted = _extract_targeted_fields(consolidated) |
| 155 |
conflicting = set(action_changes.keys()) & targeted |
| 156 |
|
| 157 |
if conflicting and strategy is ActionConflictResolution.RAISE: |
| 158 |
raise MergeConflictError(conflicting) |
| 159 |
|
| 160 |
set_fields = consolidated.get("$set", {}) |
| 161 |
|
| 162 |
if strategy in ( |
| 163 |
ActionConflictResolution.UPDATE_WINS, |
| 164 |
ActionConflictResolution.RAISE, |
| 165 |
): |
| 166 |
for key, value in action_changes.items(): |
| 167 |
if key not in targeted: |
| 168 |
set_fields[key] = value |
| 169 |
|
| 170 |
elif strategy is ActionConflictResolution.ACTION_WINS: |
| 171 |
# Remove conflicting fields from non-$set operators |
| 172 |
for operator_key in list(consolidated.keys()): |
| 173 |
if operator_key == "$set": |
| 174 |
continue |
| 175 |
for field in conflicting: |
| 176 |
consolidated[operator_key].pop(field, None) |
| 177 |
if not consolidated[operator_key]: |
| 178 |
del consolidated[operator_key] |
| 179 |
|
| 180 |
set_fields.update(action_changes) |
| 181 |
|
| 182 |
if set_fields: |
| 183 |
consolidated["$set"] = set_fields |
| 184 |
|
| 185 |
# Remove empty operators |
| 186 |
consolidated = {k: v for k, v in consolidated.items() if v} |
| 187 |
|
| 188 |
passthrough = _collect_passthrough(update_args) |
| 189 |
|
| 190 |
if consolidated: |
| 191 |
return [consolidated] + passthrough |
| 192 |
return passthrough if passthrough else list(update_args) |
| 193 |
|
| 194 |
|
| 195 |
def _collect_passthrough( |
| 196 |
update_args: list[dict[str, Any] | Mapping[str, Any]], |
| 197 |
) -> list[Any]: |
| 198 |
"""Collect expressions that the merger does not process. |
| 199 |
|
| 200 |
``SetRevisionId`` and aggregation pipeline (list) expressions are |
| 201 |
managed elsewhere and must be passed through unchanged. |
| 202 |
|
| 203 |
:param update_args: original update expression list |
| 204 |
:return: list of pass-through expressions |
| 205 |
""" |
| 206 |
return [ |
| 207 |
arg for arg in update_args if isinstance(arg, (SetRevisionId, list)) |
| 208 |
] |